// 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); }
public object Clone() { var copy = new ChartViewModel { Name = this.Name, FieldName = this.FieldName, ChartSchoolType = this.ChartSchoolType, ChartType = this.ChartType, ChartGroup = this.ChartGroup, TabType = this.TabType, ShowValue = this.ShowValue, MoreInfo = this.MoreInfo, LastYear = this.LastYear, Downloadable = this.Downloadable, HelpTooltip = this.HelpTooltip, TableColumns = new List <DataTableColumnViewModel>(), }; if (TableColumns != null) { TableColumns.ForEach(tc => copy.TableColumns.Add((DataTableColumnViewModel)tc.Clone())); } return(copy); }
protected void InsertColumns(params object[] columns) { foreach (var column in columns) { TableColumns.Add(column); } }
private static void writeToIdDictionaryMethod(TextWriter writer, TableColumns tableColumns) { writer.WriteLine("public static Dictionary<" + tableColumns.KeyColumns.Single().DataTypeName + ", Row> ToIdDictionary( this IEnumerable<Row> rows ) {"); writer.WriteLine( "return rows.ToDictionary( i => i." + Utility.GetCSharpIdentifier(tableColumns.KeyColumns.Single().PascalCasedNameExceptForOracle) + " );"); writer.WriteLine("}"); }
public void Creation() { var TempTableColumns = new TableColumns(); Assert.NotNull(TempTableColumns); Assert.Equal(20, TempTableColumns.Order); }
public List <TableColumn> GetColumnsOrdered() { var columns = TableColumns.OrderBy(tc => tc.OrderIndex).AsEnumerable(); if (HasTableIndexColumn) { columns = columns.Prepend(new TableColumn { Name = "#", ClassName = "non-toggleable", Key = ServerSide ? "_index" : null }); } if (CheckboxSelection) { columns = columns.Prepend(new TableColumn { Name = "<i class=\"far fa-square\"></i>", DefaultContent = "", ClassName = "select-checkbox non-toggleable", HeaderClassName = "select-all-checkbox" }); } return(columns.ToList()); }
/// <summary> /// Default constructor. /// </summary> public TableMetaBlock() { _hasIdentityColumn = false; _tableName = string.Empty; _changeNumber = string.Empty; _columns = new TableColumns(); }
private void Save() { if ((connectionViewModel.ConnectionType != EditingInfo.ConnectionType) || (connectionViewModel.ConnectionString != EditingInfo.ConnectionString)) { if (EditingInfo.ConnectionString.IsEmptyConnectionString()) { EditingInfo.ShouldUpdateConnectionString = true; } else if (ShowMessage != null) { var args = new ShowMessageEventArgs("Would you like to save the change to the connection string?", "Save", MessageBoxButton.YesNoCancel, MessageBoxImage.Question); ShowMessage(this, args); switch (args.MessageResponse) { case MessageBoxResult.Cancel: return; case MessageBoxResult.Yes: EditingInfo.ShouldUpdateConnectionString = true; break; } } EditingInfo.ConnectionType = connectionViewModel.ConnectionType; EditingInfo.ConnectionString = connectionViewModel.ConnectionString; } EditingInfo.TableName = TableName; EditingInfo.TableColumns = new DatabaseModel.Columns(TableColumns.Select(c => c.Column)); DialogResult = true; }
private void ListKP_KeyDown(object sender, KeyEventArgs e) { if (e.Control && e.KeyCode == Keys.C) { DataObject d = TableColumns.GetClipboardContent(); Clipboard.SetDataObject(d); e.Handled = true; } else if (e.Control && e.KeyCode == Keys.V) { string s = Clipboard.GetText(); string[] lines = s.Split('\n'); int row = TableColumns.CurrentCell.RowIndex; int col = TableColumns.CurrentCell.ColumnIndex; string[] cells = lines[0].Split('\t'); int cellsSelected = cells.Length; for (int i = 0; i < cellsSelected; i++) { TableColumns[col, row].Value = cells[i]; col++; } } else if (e.Control && e.KeyCode == Keys.X) { CopyToClipboard(); //Copy to clipboard //Clear selected cells ClearSelection(); } else if (e.KeyCode == Keys.Delete) { ClearSelection(); } }
private static void writeGetRowMatchingIdMethod( DBConnection cn, TextWriter writer, Database database, string table, TableColumns tableColumns, bool isSmallTable, bool tableUsesRowVersionedCaching, bool isRevisionHistoryTable) { writer.WriteLine("public static Row GetRowMatchingId( " + tableColumns.KeyColumns.Single().DataTypeName + " id, bool returnNullIfNoMatch = false ) {"); if (isSmallTable) { writer.WriteLine("var cache = Cache.Current;"); var commandConditionsExpression = isRevisionHistoryTable ? "getLatestRevisionsCondition().ToSingleElementArray()" : "new InlineDbCommandCondition[ 0 ]"; writer.WriteLine("cache.Queries.GetResultSet( " + commandConditionsExpression + ", commandConditions => {"); writeResultSetCreatorBody(cn, writer, database, table, tableColumns, tableUsesRowVersionedCaching, isRevisionHistoryTable, "true"); writer.WriteLine("} );"); var rowsByPkExpression = "cache.{0}RowsByPk".FormatWith(isRevisionHistoryTable ? "LatestRevision" : ""); writer.WriteLine("if( !returnNullIfNoMatch )"); writer.WriteLine("return {0}[ System.Tuple.Create( id ) ];".FormatWith(rowsByPkExpression)); writer.WriteLine("Row row;"); writer.WriteLine("return {0}.TryGetValue( System.Tuple.Create( id ), out row ) ? row : null;".FormatWith(rowsByPkExpression)); } else { writer.WriteLine( "var rows = GetRows( new " + DataAccessStatics.GetEqualityConditionClassName(cn, database, table, tableColumns.KeyColumns.Single()) + "( id ) );"); writer.WriteLine("return returnNullIfNoMatch ? rows.SingleOrDefault() : rows.Single();"); } writer.WriteLine("}"); }
private void OnDataCollected(FdrManagerEventArgs e) { Ordinats.Clear(); cb_Abscissa.Items.Clear(); TableColumns.Clear(); foreach (var title in m_DataProcessingHelper.GetCollectedMeasuresNames()) { CheckedListItem <string> item = new CheckedListItem <string>() { Item = title }; item.PropertyChanged += onOrdinateChecked; Ordinats.Add(item); cb_Abscissa.Items.Add(title); item = new CheckedListItem <string>() { Item = title }; item.PropertyChanged += onTabColumnChecked; TableColumns.Add(item); } StatusLabelMain.Content = Properties.Resources.state_success; Started = false; }
public static void ParseShouldNumberParameters() { TableColumns one = new TableColumns(); QueryFilter <TableColumns> e = one.ColumnOne == "monkey" && one.ColumnTwo != "banana"; Out(e.Parse(), ConsoleColor.Cyan); }
public PostgreSqlBuilder(IEnumerable <TableColumn> tableColumns) { if (tableColumns != null) { TableColumns.AddRange(tableColumns); } }
public override DataTable GetTableInfo(string tableName) { try { String[] columnRestrictions = new String[4]; if (tableName == null) { columnRestrictions[2] = SelectedTable; } else { columnRestrictions[2] = tableName; } DataTable departmentIDSchemaTable = connection.GetSchema("Columns", columnRestrictions); TableColumns.Clear(); DataView dv = departmentIDSchemaTable.DefaultView; departmentIDSchemaTable.DefaultView.Sort = "ORDINAL_POSITION Asc"; var SortedView = dv.ToTable(); foreach (DataRow row in SortedView.Rows) { TableColumns.Add(new Column(row, DbType)); } return(departmentIDSchemaTable); } catch (Exception ex) { return(null); } }
public string GetHeaderText() { TableColumns columns = table.Header.Columns; string value = columns[0].Name; return(value); }
protected override string mergeUpdateValues(TableColumns cols) { return(string.Format("{0}, {1}, {2}", cols.FormattedColumnValuePair("SOURCE_FILE"), cols.FormattedColumnValuePair("FUNC_NAME"), cols.FormattedColumnValuePair("DEPRECATED"))); }
private static void writeClass( DBConnection cn, string tableName, bool isRevisionHistoryTable, bool isRevisionHistoryClass ) { columns = new TableColumns( cn, tableName, isRevisionHistoryClass ); writer.WriteLine( "public partial class " + GetClassName( cn, tableName, isRevisionHistoryTable, isRevisionHistoryClass ) + " {" ); var revisionHistorySuffix = GetRevisionHistorySuffix( isRevisionHistoryClass ); // Write public static methods. writeInsertRowMethod( tableName, revisionHistorySuffix, "", columns.KeyColumns ); writeInsertRowMethod( tableName, revisionHistorySuffix, "WithoutAdditionalLogic", columns.KeyColumns ); writeUpdateRowsMethod( cn, tableName, revisionHistorySuffix, "" ); writeUpdateRowsMethod( cn, tableName, revisionHistorySuffix, "WithoutAdditionalLogic" ); writeDeleteRowsMethod( cn, tableName, revisionHistorySuffix, true ); writeDeleteRowsMethod( cn, tableName, revisionHistorySuffix + "WithoutAdditionalLogic", false ); writePrivateDeleteRowsMethod( cn, tableName, isRevisionHistoryClass ); writer.WriteLine( "static partial void preDelete( List<" + DataAccessStatics.GetTableConditionInterfaceName( cn, database, tableName ) + "> conditions, ref " + getPostDeleteCallClassName( cn, tableName ) + " postDeleteCall );" ); writer.WriteLine( "private ModificationType modType;" ); writer.WriteLine( "private List<" + DataAccessStatics.GetTableConditionInterfaceName( cn, database, tableName ) + "> conditions;" ); foreach( var column in columns.AllColumnsExceptRowVersion ) writeFieldsAndPropertiesForColumn( column ); foreach( var column in columns.DataColumns.Where( i => !columns.KeyColumns.Contains( i ) ) ) FormItemStatics.WriteFormItemGetters( writer, column.GetModificationField() ); // Write constructors. writeCreateForInsertMethod( cn, tableName, isRevisionHistoryTable, isRevisionHistoryClass, revisionHistorySuffix ); writeCreateForUpdateMethod( cn, tableName, isRevisionHistoryTable, isRevisionHistoryClass, revisionHistorySuffix ); if( columns.DataColumns.Any() ) writeCreateForSingleRowUpdateMethod( cn, tableName, isRevisionHistoryTable, isRevisionHistoryClass, revisionHistorySuffix ); writeGetConditionListMethod( cn, tableName ); writer.WriteLine( "private " + GetClassName( cn, tableName, isRevisionHistoryTable, isRevisionHistoryClass ) + "() {}" ); if( columns.DataColumns.Any() ) writeSetAllDataMethod(); // Write execute methods and helpers. writeExecuteMethod( tableName ); writer.WriteLine( "partial void preInsert();" ); writer.WriteLine( "partial void preUpdate();" ); writeExecuteWithoutAdditionalLogicMethod( tableName ); writeExecuteInsertOrUpdateMethod( cn, tableName, isRevisionHistoryClass, columns.KeyColumns, columns.IdentityColumn ); writeAddColumnModificationsMethod( columns.AllNonIdentityColumnsExceptRowVersion ); if( isRevisionHistoryClass ) { writeCopyLatestRevisionsMethod( cn, tableName, columns.AllNonIdentityColumnsExceptRowVersion ); DataAccessStatics.WriteGetLatestRevisionsConditionMethod( writer, columns.PrimaryKeyAndRevisionIdColumn.Name ); } writeRethrowAsEwfExceptionIfNecessary(); writer.WriteLine( "static partial void populateConstraintNamesToViolationErrorMessages( Dictionary<string,string> constraintNamesToViolationErrorMessages );" ); writer.WriteLine( "partial void postInsert();" ); writer.WriteLine( "partial void postUpdate();" ); writeMarkColumnValuesUnchangedMethod(); writer.WriteLine( "}" ); }
private void MakeColumnsAsLocalSubSelect() { TableColumns.Clear(); List <ColumnClause> lst = GetAllColumns().ToList(); HashSet <string> str = new HashSet <string>(); foreach (var c in lst) { string alias = c.ExtractAlias(); if (alias == null) { alias = ""; } var tp = c.ColumnExpression.GetResultType(); if (tp == SimpleTypes.Geometry) { CoordinateSystem = c.ColumnExpression.GetCoordinateSystem(); } TableColumns.Add(new ColumnSubSelect() { ColumnClause = c, Name = alias, SimpleType = tp }); } }
// It is called when preparing this dialog for editing/adding a table or when context changes (not during the process) // Essentially, we do it when data context is set. private void initViewModel() { DcSpace space = mainVM.Space; if (IsNew) { TableName = "New Table"; TableFormula = ""; FilePath = ""; HasHeaderRecord = true; Delimiter = ","; Decimal = "."; TableColumns.Clear(); } else { TableName = Table.Name; TableFormula = Table.GetData().WhereFormula; FilePath = ((TableCsv)Table).FilePath; HasHeaderRecord = ((TableCsv)Table).HasHeaderRecord; Delimiter = ((TableCsv)Table).Delimiter; Decimal = ((TableCsv)Table).CultureInfo.NumberFormat.NumberDecimalSeparator; UpdateColumnList(); } FirePropertyNotifyChanged(""); }
public override void Prepare() { base.Prepare(); for (int i = 0; i < ReturningColumns.Count; i++) { ReturningColumns[i].Prepare(); } TableColumns.Clear(); List <ColumnClause> lst = ReturningColumns.ToList(); HashSet <string> str = new HashSet <string>(); foreach (var c in lst) { string alias = c.ExtractAlias(); if (alias == null) { alias = ""; } var tp = c.ColumnExpression.GetResultType(); if (tp == SimpleTypes.Geometry) { CoordinateSystem = c.ColumnExpression.GetCoordinateSystem(); } TableColumns.Add(new ColumnSubSelect() { ColumnClause = c, Name = alias, SimpleType = tp }); } }
private static void writeCacheClass( DBConnection cn, TextWriter writer, IDatabase database, string table, TableColumns tableColumns, bool isRevisionHistoryTable) { var cacheKey = table.TableNameToPascal(cn) + "TableRetrieval"; var pkTupleTypeArguments = getPkTupleTypeArguments(tableColumns); writer.WriteLine("private partial class Cache {"); writer.WriteLine("internal static Cache Current { get { return DataAccessState.Current.GetCacheValue( \"" + cacheKey + "\", () => new Cache() ); } }"); writer.WriteLine("private readonly TableRetrievalQueryCache<Row> queries = new TableRetrievalQueryCache<Row>();"); writer.WriteLine( $"private readonly Dictionary<{TypeNames.Tuple}<{pkTupleTypeArguments}>, Row> rowsByPk = new Dictionary<{TypeNames.Tuple}<{pkTupleTypeArguments}>, Row>();"); if (isRevisionHistoryTable) { writer.WriteLine( $"private readonly Dictionary<{TypeNames.Tuple}<{pkTupleTypeArguments}>, Row> latestRevisionRowsByPk = new Dictionary<{TypeNames.Tuple}<{pkTupleTypeArguments}>, Row>();"); } writer.WriteLine("private Cache() {}"); writer.WriteLine("internal TableRetrievalQueryCache<Row> Queries => queries; "); writer.WriteLine($"internal Dictionary<{TypeNames.Tuple}<" + pkTupleTypeArguments + ">, Row> RowsByPk => rowsByPk;"); if (isRevisionHistoryTable) { writer.WriteLine( $"internal Dictionary<{TypeNames.Tuple}<" + pkTupleTypeArguments + ">, Row> LatestRevisionRowsByPk { get { return latestRevisionRowsByPk; } }"); } writer.WriteLine("}"); }
private static void writeGetRowsMethod( DBConnection cn, TextWriter writer, IDatabase database, string table, TableColumns tableColumns, bool isSmallTable, bool tableUsesRowVersionedCaching, bool isRevisionHistoryTable, bool excludePreviousRevisions, int?commandTimeoutSeconds) { // header var methodName = "GetRows" + (isSmallTable ? "MatchingConditions" : "") + (isRevisionHistoryTable && !excludePreviousRevisions ? "IncludingPreviousRevisions" : ""); CodeGenerationStatics.AddSummaryDocComment( writer, "Retrieves the rows from the table that match the specified conditions, ordered in a stable way." + (isSmallTable ? " Since the table is specified as small, you should only use this method if you cannot filter the rows in code." : "")); writer.WriteLine( "public static IEnumerable<Row> " + methodName + "( params " + DataAccessStatics.GetTableConditionInterfaceName(cn, database, table) + "[] conditions ) {"); // body // If it's a primary key query, use RowsByPk if possible. foreach (var i in tableColumns.KeyColumns) { var equalityConditionClassName = DataAccessStatics.GetEqualityConditionClassName(cn, database, table, i); writer.WriteLine("var {0}Condition = conditions.OfType<{1}>().FirstOrDefault();".FormatWith(i.CamelCasedName, equalityConditionClassName)); } writer.WriteLine("var cache = Cache.Current;"); var pkConditionVariableNames = tableColumns.KeyColumns.Select(i => i.CamelCasedName + "Condition"); writer.WriteLine( "var isPkQuery = " + StringTools.ConcatenateWithDelimiter(" && ", pkConditionVariableNames.Select(i => i + " != null").ToArray()) + " && conditions.Count() == " + tableColumns.KeyColumns.Count() + ";"); writer.WriteLine("if( isPkQuery ) {"); writer.WriteLine("Row row;"); writer.WriteLine( "if( cache." + (excludePreviousRevisions ? "LatestRevision" : "") + $"RowsByPk.TryGetValue( {TypeNames.Tuple}.Create( " + StringTools.ConcatenateWithDelimiter(", ", pkConditionVariableNames.Select(i => i + ".Value").ToArray()) + " ), out row ) )"); writer.WriteLine("return new [] {row};"); writer.WriteLine("}"); var commandConditionsExpression = "conditions.Select( i => i.CommandCondition )"; if (excludePreviousRevisions) { commandConditionsExpression += ".Concat( new [] {getLatestRevisionsCondition()} )"; } writer.WriteLine("return cache.Queries.GetResultSet( " + commandConditionsExpression + ", commandConditions => {"); writeResultSetCreatorBody( cn, writer, database, table, tableColumns, tableUsesRowVersionedCaching, excludePreviousRevisions, "!isPkQuery", commandTimeoutSeconds); writer.WriteLine("} );"); writer.WriteLine("}"); }
private static string getInlineSelectExpression( Table table, TableColumns tableColumns, string selectExpressions, string cacheQueryInDbExpression, int?commandTimeoutSeconds) { var concatenateWithDelimiter = StringTools.ConcatenateWithDelimiter(", ", tableColumns.KeyColumns.Select(i => i.Name)); return ($@"new {TypeNames.InlineSelect}( new[] {{ {selectExpressions} }}, ""FROM {table.ObjectIdentifier}"", {cacheQueryInDbExpression}, {commandTimeoutSeconds?.ToString() ?? "null"}, orderByClause: ""ORDER BY {concatenateWithDelimiter}"" )"); }
public static void OrShouldParseNoParens() { TableColumns one = new TableColumns(); QueryFilter <TableColumns> e = (one.ColumnOne == "monkey").Or(one.ColumnTwo != "banana"); Out(e.Parse(), ConsoleColor.Cyan); Expect.AreEqual("[ColumnOne] = @ColumnOne1 OR [ColumnTwo] <> @ColumnTwo2", e.Parse()); }
public static void AndOperatorShouldParseParens() { TableColumns one = new TableColumns(); QueryFilter <TableColumns> e = one.ColumnOne == "dookey" && one.ColumnTwo == "poo"; Out(e.Parse(), ConsoleColor.Cyan); Expect.AreEqual("([ColumnOne] = @ColumnOne1) AND ([ColumnTwo] = @ColumnTwo2)", e.Parse()); }
public static void EndsWithShouldParseValidWhereExpression() { TableColumns test = new TableColumns(); QueryFilter <TableColumns> e = test.TestOne.EndsWith("gorilla boat"); Out(e.Parse(), ConsoleColor.Cyan); Expect.AreEqual("TestOne LIKE '%' + @TestOne1", e.Parse()); }
private static string getInlineSelectExpression(string table, TableColumns tableColumns, string selectExpressions, string cacheQueryInDbExpression) { return("new InlineSelect( {0}, \"FROM {1}\", {2}, orderByClause: \"ORDER BY {3}\" )".FormatWith( "new[] { " + selectExpressions + " }", table, cacheQueryInDbExpression, StringTools.ConcatenateWithDelimiter(", ", tableColumns.KeyColumns.Select(i => i.Name).ToArray()))); }
void OnStartNewDataCollecting(FdrManagerEventArgs e) { Ordinats.Clear(); cb_Abscissa.Items.Clear(); TableColumns.Clear(); StatusLabelSecond.Content = ""; StatusLabelMain.Content = Properties.Resources.state_collecting; }
public void Add(TableColumns tableColumns) { if(! tables.ContainsKey(tableColumns.Table)) { tables.Add(tableColumns.Table, new HashSet<string>()); } tables[tableColumns.Table].Add(tableColumns.Column); }
public static void ExtensionClassShouldWorkTheSameAsQueryFilter() { TableColumns test = new TableColumns(); QueryFilter <TableColumns> e = test.TestOne == "monkey"; Out(e.Parse(), ConsoleColor.Cyan); Expect.AreEqual("[TestOne] = @TestOne1", e.Parse()); }
/// <summary> /// This method is used to fetch data from the database with joins. /// </summary> /// <param name="conditions">An object that contains logical operator and conditions.</param> /// <returns>Returns fetched data.</returns> public DataTable GetRecords(DatabaseTable mainTable, JoinConditions conditions) { string mainTableName = DatabaseTableNameFetcher.GetName(mainTable); string mainColumn = TableColumns.GetBaseTablePrimaryColumn(mainTable); string query = string.Format("SELECT DISTINCT {0}.{1}", mainTableName, TableColumns.COMMON_ID); // If mainColumn value is not empty = It is not a relationship table. if (!mainColumn.Equals(string.Empty)) { query = string.Format("{0}, {1}.{2}", query, mainTableName, mainColumn); } string from = string.Format("FROM {0}", mainTableName); string where = string.Format("WHERE {0}.{1} = 0", mainTableName, TableColumns.COMMON_DELETED); // If search conditions are provided. // All conditions are calculated with AND operator. if (conditions.Search != null) { foreach (var condition in conditions.Search) { string baseTable = DatabaseTableNameFetcher.GetName(condition.BaseTable); where = string.Format("{0} AND {1}.{2} = {3}", where, baseTable, condition.Column, condition.Value); } } // Create Join Conditions foreach (var condition in conditions.Conditions) { string baseTable = DatabaseTableNameFetcher.GetName(condition.BaseTable); string joinTable = DatabaseTableNameFetcher.GetName(condition.JoinTable); string baseColumn = TableColumns.GetBaseTablePrimaryColumn(condition.BaseTable); query = string.Format("{0}, {1}.{2}", query, baseTable, baseColumn); where = string.Format("{0} {5} {1}.{2} = {3}.{4}", where, baseTable, TableColumns.COMMON_ID, joinTable, condition.JoinTableColumnName, conditions.LogicalOperator); if (!from.Contains(baseTable)) { from = string.Format("{0}, {1}", from, baseTable); } } where = ApplicationSettingData.Setting.Helper.EndsWith(where, "WHERE"); where = ApplicationSettingData.Setting.Helper.EndsWith(where, conditions.LogicalOperator); query = string.Format("{0} {1} {2}", query, from, where); return(ApplicationSettingData.Setting.DataCommunicator.Read(query)); }
protected StoredProcedure(string name, StoredProcedureParameters parameters, string table, TableColumns columns, string keyName, string keyColumn, string keyType) { Name = name; Parameters = parameters; Table = table; Columns = columns; KeyPropertyName = keyName; KeyColumn = keyColumn; KeyType = keyType; }
private static string getPkAndVersionTupleTypeArguments( DBConnection cn, TableColumns tableColumns ) { return "{0}, {1}".FormatWith( getPkTupleTypeArguments( tableColumns ), cn.DatabaseInfo is OracleInfo ? oracleRowVersionDataType : tableColumns.RowVersionColumn.DataTypeName ); }
private static string getPkTupleTypeArguments( TableColumns tableColumns ) { return StringTools.ConcatenateWithDelimiter( ", ", tableColumns.KeyColumns.Select( i => i.DataTypeName ).ToArray() ); }
// Generates content of tableDefinitionPart2. private void GenerateTableDefinitionPart2Content(TableDefinitionPart tableDefinitionPart2) { Table table2 = new Table(){ Id = (UInt32Value)5U, Name = "ProductTable2", DisplayName = "ProductTable2", Reference = "H1:I11", TotalsRowShown = false, HeaderRowFormatId = (UInt32Value)2U }; AutoFilter autoFilter2 = new AutoFilter(){ Reference = "H1:I11" }; TableColumns tableColumns2 = new TableColumns(){ Count = (UInt32Value)2U }; TableColumn tableColumn2 = new TableColumn(){ Id = (UInt32Value)1U, Name = "ProductName" }; TableColumn tableColumn3 = new TableColumn(){ Id = (UInt32Value)2U, Name = "Price", DataFormatId = (UInt32Value)1U }; tableColumns2.Append(tableColumn2); tableColumns2.Append(tableColumn3); TableStyleInfo tableStyleInfo2 = new TableStyleInfo(){ Name = "TableStyleMedium2", ShowFirstColumn = false, ShowLastColumn = false, ShowRowStripes = true, ShowColumnStripes = false }; table2.Append(autoFilter2); table2.Append(tableColumns2); table2.Append(tableStyleInfo2); tableDefinitionPart2.Table = table2; }
private static void writeGetRowMatchingPkMethod( DBConnection cn, TextWriter writer, Database database, string table, TableColumns tableColumns, bool isSmallTable, bool tableUsesRowVersionedCaching, bool isRevisionHistoryTable) { var pkIsId = tableColumns.KeyColumns.Count() == 1 && tableColumns.KeyColumns.Single().Name.ToLower().EndsWith( "id" ); var methodName = pkIsId ? "GetRowMatchingId" : "GetRowMatchingPk"; var pkParameters = pkIsId ? "{0} id".FormatWith( tableColumns.KeyColumns.Single().DataTypeName ) : StringTools.ConcatenateWithDelimiter( ", ", tableColumns.KeyColumns.Select( i => "{0} {1}".FormatWith( i.DataTypeName, i.CamelCasedName ) ).ToArray() ); writer.WriteLine( "public static Row " + methodName + "( " + pkParameters + ", bool returnNullIfNoMatch = false ) {" ); if( isSmallTable ) { writer.WriteLine( "var cache = Cache.Current;" ); var commandConditionsExpression = isRevisionHistoryTable ? "getLatestRevisionsCondition().ToSingleElementArray()" : "new InlineDbCommandCondition[ 0 ]"; writer.WriteLine( "cache.Queries.GetResultSet( " + commandConditionsExpression + ", commandConditions => {" ); writeResultSetCreatorBody( cn, writer, database, table, tableColumns, tableUsesRowVersionedCaching, isRevisionHistoryTable, "true" ); writer.WriteLine( "} );" ); var rowsByPkExpression = "cache.{0}RowsByPk".FormatWith( isRevisionHistoryTable ? "LatestRevision" : "" ); var pkTupleCreationArguments = pkIsId ? "id" : StringTools.ConcatenateWithDelimiter( ", ", tableColumns.KeyColumns.Select( i => i.CamelCasedName ).ToArray() ); writer.WriteLine( "if( !returnNullIfNoMatch )" ); writer.WriteLine( "return {0}[ System.Tuple.Create( {1} ) ];".FormatWith( rowsByPkExpression, pkTupleCreationArguments ) ); writer.WriteLine( "Row row;" ); writer.WriteLine( "return {0}.TryGetValue( System.Tuple.Create( {1} ), out row ) ? row : null;".FormatWith( rowsByPkExpression, pkTupleCreationArguments ) ); } else { writer.WriteLine( "var rows = GetRows( {0} );".FormatWith( pkIsId ? "new {0}( id )".FormatWith( DataAccessStatics.GetEqualityConditionClassName( cn, database, table, tableColumns.KeyColumns.Single() ) ) : StringTools.ConcatenateWithDelimiter( ", ", tableColumns.KeyColumns.Select( i => "new {0}( {1} )".FormatWith( DataAccessStatics.GetEqualityConditionClassName( cn, database, table, i ), i.CamelCasedName ) ).ToArray() ) ) ); writer.WriteLine( "return returnNullIfNoMatch ? rows.SingleOrDefault() : rows.Single();" ); } writer.WriteLine( "}" ); }
// Generates content of tableDefinitionPart1. private void GenerateTableDefinitionPart1Content(TableDefinitionPart tableDefinitionPart1) { Table table1 = new Table(){ Id = (UInt32Value)1U, Name = "Table_Query", DisplayName = "Table_Query", Reference = "B2:I13", TableType = TableValues.QueryTable, TotalsRowShown = false }; AutoFilter autoFilter1 = new AutoFilter(){ Reference = "B2:I13" }; TableColumns tableColumns1 = new TableColumns(){ Count = (UInt32Value)8U }; TableColumn tableColumn1 = new TableColumn(){ Id = (UInt32Value)1U, UniqueName = "1", Name = "account_id", QueryTableFieldId = (UInt32Value)1U }; TableColumn tableColumn2 = new TableColumn(){ Id = (UInt32Value)2U, UniqueName = "2", Name = "account_parent", QueryTableFieldId = (UInt32Value)2U }; TableColumn tableColumn3 = new TableColumn(){ Id = (UInt32Value)3U, UniqueName = "3", Name = "account_description", QueryTableFieldId = (UInt32Value)3U }; TableColumn tableColumn4 = new TableColumn(){ Id = (UInt32Value)4U, UniqueName = "4", Name = "account_type", QueryTableFieldId = (UInt32Value)4U }; TableColumn tableColumn5 = new TableColumn(){ Id = (UInt32Value)5U, UniqueName = "5", Name = "account_rollup", QueryTableFieldId = (UInt32Value)5U }; TableColumn tableColumn6 = new TableColumn(){ Id = (UInt32Value)6U, UniqueName = "6", Name = "Custom Members", QueryTableFieldId = (UInt32Value)6U }; TableColumn tableColumn7 = new TableColumn(){ Id = (UInt32Value)7U, UniqueName = "7", Name = "CurrentUser", QueryTableFieldId = (UInt32Value)7U }; TableColumn tableColumn8 = new TableColumn(){ Id = (UInt32Value)8U, UniqueName = "8", Name = "RefreshTime", QueryTableFieldId = (UInt32Value)8U, DataFormatId = (UInt32Value)0U }; tableColumns1.Append(tableColumn1); tableColumns1.Append(tableColumn2); tableColumns1.Append(tableColumn3); tableColumns1.Append(tableColumn4); tableColumns1.Append(tableColumn5); tableColumns1.Append(tableColumn6); tableColumns1.Append(tableColumn7); tableColumns1.Append(tableColumn8); TableStyleInfo tableStyleInfo1 = new TableStyleInfo(){ Name = "TableStyleMedium2", ShowFirstColumn = false, ShowLastColumn = false, ShowRowStripes = true, ShowColumnStripes = false }; table1.Append(autoFilter1); table1.Append(tableColumns1); table1.Append(tableStyleInfo1); tableDefinitionPart1.Table = table1; }
private static string getInlineSelectExpression( string table, TableColumns tableColumns, string selectExpressions, string cacheQueryInDbExpression ) { return "new InlineSelect( {0}, \"FROM {1}\", {2}, orderByClause: \"ORDER BY {3}\" )".FormatWith( "new[] { " + selectExpressions + " }", table, cacheQueryInDbExpression, StringTools.ConcatenateWithDelimiter( ", ", tableColumns.KeyColumns.Select( i => i.Name ).ToArray() ) ); }
public UpdateStp(string name, StoredProcedureParameters parameters, string table, TableColumns columns, string keyName, string keyColumn, string keyType, TEntity entity) : base(name, parameters, table, columns, keyName, keyColumn, keyType) { Entity = entity; }
// Generates content of tableDefinitionPart4. private void GenerateTableDefinitionPart4Content(TableDefinitionPart tableDefinitionPart4) { Table table4 = new Table(){ Id = (UInt32Value)3U, Name = "SalesTable1", DisplayName = "SalesTable1", Reference = "K1:K11", TotalsRowShown = false, HeaderRowFormatId = (UInt32Value)9U }; AutoFilter autoFilter4 = new AutoFilter(){ Reference = "K1:K11" }; TableColumns tableColumns4 = new TableColumns(){ Count = (UInt32Value)1U }; TableColumn tableColumn10 = new TableColumn(){ Id = (UInt32Value)1U, Name = "Employee" }; tableColumns4.Append(tableColumn10); TableStyleInfo tableStyleInfo4 = new TableStyleInfo(){ Name = "TableStyleMedium2", ShowFirstColumn = false, ShowLastColumn = false, ShowRowStripes = true, ShowColumnStripes = false }; table4.Append(autoFilter4); table4.Append(tableColumns4); table4.Append(tableStyleInfo4); tableDefinitionPart4.Table = table4; }
// Generates content of tableDefinitionPart3. private void GenerateTableDefinitionPart3Content(TableDefinitionPart tableDefinitionPart3) { Table table3 = new Table(){ Id = (UInt32Value)4U, Name = "DataTable2", DisplayName = "DataTable2", Reference = "A1:F6", TotalsRowShown = false }; AutoFilter autoFilter3 = new AutoFilter(){ Reference = "A1:F6" }; SortState sortState1 = new SortState(){ Reference = "A2:F2001" }; SortCondition sortCondition1 = new SortCondition(){ Reference = "A2" }; sortState1.Append(sortCondition1); TableColumns tableColumns3 = new TableColumns(){ Count = (UInt32Value)6U }; TableColumn tableColumn4 = new TableColumn(){ Id = (UInt32Value)1U, Name = "Date", DataFormatId = (UInt32Value)8U }; TableColumn tableColumn5 = new TableColumn(){ Id = (UInt32Value)2U, Name = "Product", DataFormatId = (UInt32Value)7U }; TableColumn tableColumn6 = new TableColumn(){ Id = (UInt32Value)3U, Name = "Quantity", DataFormatId = (UInt32Value)6U }; TableColumn tableColumn7 = new TableColumn(){ Id = (UInt32Value)4U, Name = "Price", DataFormatId = (UInt32Value)5U }; TableColumn tableColumn8 = new TableColumn(){ Id = (UInt32Value)5U, Name = "DeliveryDate", DataFormatId = (UInt32Value)4U }; TableColumn tableColumn9 = new TableColumn(){ Id = (UInt32Value)6U, Name = "Employee", DataFormatId = (UInt32Value)3U }; tableColumns3.Append(tableColumn4); tableColumns3.Append(tableColumn5); tableColumns3.Append(tableColumn6); tableColumns3.Append(tableColumn7); tableColumns3.Append(tableColumn8); tableColumns3.Append(tableColumn9); TableStyleInfo tableStyleInfo3 = new TableStyleInfo(){ Name = "TableStyleMedium2", ShowFirstColumn = false, ShowLastColumn = false, ShowRowStripes = true, ShowColumnStripes = false }; table3.Append(autoFilter3); table3.Append(sortState1); table3.Append(tableColumns3); table3.Append(tableStyleInfo3); tableDefinitionPart3.Table = table3; }
private static void writeResultSetCreatorBody( DBConnection cn, TextWriter writer, Database database, string table, TableColumns tableColumns, bool tableUsesRowVersionedCaching, bool excludesPreviousRevisions, string cacheQueryInDbExpression) { if( tableUsesRowVersionedCaching ) { writer.WriteLine( "var results = new List<Row>();" ); writer.WriteLine( DataAccessStatics.GetConnectionExpression( database ) + ".ExecuteInTransaction( delegate {" ); // Query for the cache keys of the results. writer.WriteLine( "var keyCommand = {0};".FormatWith( getInlineSelectExpression( table, tableColumns, "{0}, \"{1}\"".FormatWith( StringTools.ConcatenateWithDelimiter( ", ", tableColumns.KeyColumns.Select( i => "\"{0}\"".FormatWith( i.Name ) ).ToArray() ), cn.DatabaseInfo is OracleInfo ? "ORA_ROWSCN" : tableColumns.RowVersionColumn.Name ), cacheQueryInDbExpression ) ) ); writer.WriteLine( getCommandConditionAddingStatement( "keyCommand" ) ); writer.WriteLine( "var keys = new List<System.Tuple<{0}>>();".FormatWith( getPkAndVersionTupleTypeArguments( cn, tableColumns ) ) ); writer.WriteLine( "keyCommand.Execute( " + DataAccessStatics.GetConnectionExpression( database ) + ", r => { while( r.Read() ) keys.Add( " + "System.Tuple.Create( {0}, {1} )".FormatWith( StringTools.ConcatenateWithDelimiter( ", ", tableColumns.KeyColumns.Select( ( c, i ) => c.GetDataReaderValueExpression( "r", ordinalOverride: i ) ).ToArray() ), cn.DatabaseInfo is OracleInfo ? "({0})r.GetValue( {1} )".FormatWith( oracleRowVersionDataType, tableColumns.KeyColumns.Count() ) : tableColumns.RowVersionColumn.GetDataReaderValueExpression( "r", ordinalOverride: tableColumns.KeyColumns.Count() ) ) + " ); } );" ); writer.WriteLine( "var rowsByPkAndVersion = getRowsByPkAndVersion();" ); writer.WriteLine( "var cachedKeyCount = keys.Where( i => rowsByPkAndVersion.ContainsKey( i ) ).Count();" ); // If all but a few results are cached, execute a single-row query for each missing result. writer.WriteLine( "if( cachedKeyCount >= keys.Count() - 1 || cachedKeyCount >= keys.Count() * .99 ) {" ); writer.WriteLine( "foreach( var key in keys ) {" ); writer.WriteLine( "results.Add( new Row( rowsByPkAndVersion.GetOrAdd( key, () => {" ); writer.WriteLine( "var singleRowCommand = {0};".FormatWith( getInlineSelectExpression( table, tableColumns, "\"*\"", "false" ) ) ); foreach( var i in tableColumns.KeyColumns.Select( ( c, i ) => new { column = c, index = i } ) ) { writer.WriteLine( "singleRowCommand.AddCondition( ( ({0})new {1}( key.Item{2} ) ).CommandCondition );".FormatWith( DataAccessStatics.GetTableConditionInterfaceName( cn, database, table ), DataAccessStatics.GetEqualityConditionClassName( cn, database, table, i.column ), i.index + 1 ) ); } writer.WriteLine( "var singleRowResults = new List<BasicRow>();" ); writer.WriteLine( "singleRowCommand.Execute( " + DataAccessStatics.GetConnectionExpression( database ) + ", r => { while( r.Read() ) singleRowResults.Add( new BasicRow( r ) ); } );" ); writer.WriteLine( "return singleRowResults.Single();" ); writer.WriteLine( "} ) ) );" ); writer.WriteLine( "}" ); writer.WriteLine( "}" ); // Otherwise, execute the full query. writer.WriteLine( "else {" ); writer.WriteLine( "var command = {0};".FormatWith( getInlineSelectExpression( table, tableColumns, cn.DatabaseInfo is OracleInfo ? "\"{0}.*\", \"ORA_ROWSCN\"".FormatWith( table ) : "\"*\"", cacheQueryInDbExpression ) ) ); writer.WriteLine( getCommandConditionAddingStatement( "command" ) ); writer.WriteLine( "command.Execute( " + DataAccessStatics.GetConnectionExpression( database ) + ", r => {" ); writer.WriteLine( "while( r.Read() ) results.Add( new Row( rowsByPkAndVersion.GetOrAdd( System.Tuple.Create( {0}, {1} ), () => new BasicRow( r ) ) ) );".FormatWith( StringTools.ConcatenateWithDelimiter( ", ", tableColumns.KeyColumns.Select( i => i.GetDataReaderValueExpression( "r" ) ).ToArray() ), cn.DatabaseInfo is OracleInfo ? "({0})r.GetValue( {1} )".FormatWith( oracleRowVersionDataType, tableColumns.AllColumns.Count() ) : tableColumns.RowVersionColumn.GetDataReaderValueExpression( "r" ) ) ); writer.WriteLine( "} );" ); writer.WriteLine( "}" ); writer.WriteLine( "} );" ); } else { writer.WriteLine( "var command = {0};".FormatWith( getInlineSelectExpression( table, tableColumns, "\"*\"", cacheQueryInDbExpression ) ) ); writer.WriteLine( getCommandConditionAddingStatement( "command" ) ); writer.WriteLine( "var results = new List<Row>();" ); writer.WriteLine( "command.Execute( " + DataAccessStatics.GetConnectionExpression( database ) + ", r => { while( r.Read() ) results.Add( new Row( new BasicRow( r ) ) ); } );" ); } // Add all results to RowsByPk. writer.WriteLine( "foreach( var i in results ) {" ); var pkTupleCreationArgs = tableColumns.KeyColumns.Select( i => "i." + EwlStatics.GetCSharpIdentifierSimple( i.PascalCasedNameExceptForOracle ) ); var pkTuple = "System.Tuple.Create( " + StringTools.ConcatenateWithDelimiter( ", ", pkTupleCreationArgs.ToArray() ) + " )"; writer.WriteLine( "cache.RowsByPk[ " + pkTuple + " ] = i;" ); if( excludesPreviousRevisions ) writer.WriteLine( "cache.LatestRevisionRowsByPk[ " + pkTuple + " ] = i;" ); writer.WriteLine( "}" ); writer.WriteLine( "return results;" ); }
internal static void Generate( DBConnection cn, TextWriter writer, string namespaceDeclaration, Database database, Configuration.SystemDevelopment.Database configuration) { writer.WriteLine( namespaceDeclaration ); foreach( var table in DatabaseOps.GetDatabaseTables( database ) ) { CodeGenerationStatics.AddSummaryDocComment( writer, "Contains logic that retrieves rows from the " + table + " table." ); writer.WriteLine( "public static partial class " + GetClassName( cn, table ) + " {" ); var isRevisionHistoryTable = DataAccessStatics.IsRevisionHistoryTable( table, configuration ); var columns = new TableColumns( cn, table, isRevisionHistoryTable ); // Write nested classes. DataAccessStatics.WriteRowClasses( writer, columns.AllColumns, localWriter => { if( !columns.DataColumns.Any() ) return; var modClass = database.SecondaryDatabaseName + "Modification." + StandardModificationStatics.GetClassName( cn, table, isRevisionHistoryTable, isRevisionHistoryTable ); var revisionHistorySuffix = StandardModificationStatics.GetRevisionHistorySuffix( isRevisionHistoryTable ); writer.WriteLine( "public " + modClass + " ToModification" + revisionHistorySuffix + "() {" ); writer.WriteLine( "return " + modClass + ".CreateForSingleRowUpdate" + revisionHistorySuffix + "( " + StringTools.ConcatenateWithDelimiter( ", ", columns.AllColumnsExceptRowVersion.Select( i => EwlStatics.GetCSharpIdentifierSimple( i.PascalCasedNameExceptForOracle ) ).ToArray() ) + " );" ); writer.WriteLine( "}" ); } ); writeCacheClass( cn, writer, database, table, columns, isRevisionHistoryTable ); var isSmallTable = configuration.SmallTables != null && configuration.SmallTables.Any( i => i.EqualsIgnoreCase( table ) ); var tableUsesRowVersionedCaching = configuration.TablesUsingRowVersionedDataCaching != null && configuration.TablesUsingRowVersionedDataCaching.Any( i => i.EqualsIgnoreCase( table ) ); if( tableUsesRowVersionedCaching && columns.RowVersionColumn == null && !( cn.DatabaseInfo is OracleInfo ) ) { throw new UserCorrectableException( cn.DatabaseInfo is MySqlInfo ? "Row-versioned data caching cannot currently be used with MySQL databases." : "Row-versioned data caching can only be used with the {0} table if you add a rowversion column.".FormatWith( table ) ); } if( isSmallTable ) writeGetAllRowsMethod( writer, isRevisionHistoryTable, false ); writeGetRowsMethod( cn, writer, database, table, columns, isSmallTable, tableUsesRowVersionedCaching, isRevisionHistoryTable, false ); if( isRevisionHistoryTable ) { if( isSmallTable ) writeGetAllRowsMethod( writer, true, true ); writeGetRowsMethod( cn, writer, database, table, columns, isSmallTable, tableUsesRowVersionedCaching, true, true ); } if( columns.KeyColumns.Count() == 1 && columns.KeyColumns.Single().Name.ToLower().EndsWith( "id" ) ) writeGetRowMatchingIdMethod( cn, writer, database, table, columns, isSmallTable, tableUsesRowVersionedCaching, isRevisionHistoryTable ); if( isRevisionHistoryTable ) DataAccessStatics.WriteGetLatestRevisionsConditionMethod( writer, columns.PrimaryKeyAndRevisionIdColumn.Name ); if( tableUsesRowVersionedCaching ) { var keyTupleTypeArguments = getPkAndVersionTupleTypeArguments( cn, columns ); writer.WriteLine( "private static " + "Cache<System.Tuple<" + keyTupleTypeArguments + ">, BasicRow>" + " getRowsByPkAndVersion() {" ); writer.WriteLine( "return AppMemoryCache.GetCacheValue<{0}>( \"{1}\", () => new {0}( i => System.Tuple.Create( {2} ) ) ).RowsByPkAndVersion;".FormatWith( "VersionedRowDataCache<System.Tuple<{0}>, System.Tuple<{1}>, BasicRow>".FormatWith( getPkTupleTypeArguments( columns ), keyTupleTypeArguments ), database.SecondaryDatabaseName + table.TableNameToPascal( cn ) + "TableRetrievalRowsByPkAndVersion", StringTools.ConcatenateWithDelimiter( ", ", Enumerable.Range( 1, columns.KeyColumns.Count() ).Select( i => "i.Item{0}".FormatWith( i ) ).ToArray() ) ) ); writer.WriteLine( "}" ); } // Initially we did not generate this method for small tables, but we found a need for it when the cache is disabled since that will cause // GetRowMatchingId to repeatedly query. if( columns.KeyColumns.Count() == 1 && columns.KeyColumns.Single().Name.ToLower().EndsWith( "id" ) ) writeToIdDictionaryMethod( writer, columns ); writer.WriteLine( "}" ); // class } writer.WriteLine( "}" ); // namespace }
internal static void SetTableDataAndDateIfNecessary(Table table, int row, string newValue, TableColumns.NameValuePairs valueColumn, TableColumns.NameValuePairs dateColumn) { string oldValue = table.GetData(row, (int)valueColumn); if (oldValue.Equals(newValue)) return; table.SetData(row, (int)valueColumn, newValue); table.SetData(row, (int)dateColumn, DateTime.Today.ToString(Strings.DateColumnFormatString)); }
private static void writeToIdDictionaryMethod( TextWriter writer, TableColumns tableColumns ) { writer.WriteLine( "public static Dictionary<" + tableColumns.KeyColumns.Single().DataTypeName + ", Row> ToIdDictionary( this IEnumerable<Row> rows ) {" ); writer.WriteLine( "return rows.ToDictionary( i => i." + EwlStatics.GetCSharpIdentifierSimple( tableColumns.KeyColumns.Single().PascalCasedNameExceptForOracle ) + " );" ); writer.WriteLine( "}" ); }
/// <summary> /// Default Values for a Table Column /// </summary> /// <param name="id">The statistical ID associated with the column</param> /// <param name="name">The Name to put on the column heading</param> /// <param name="defaultDisplay">The default display type</param> /// <param name="graphical">Whether the value can be displayed graphically</param> /// <param name="display">Whether to display the column by default</param> /// <param name="width">The default with of the column</param> public TableColumn(TableColumns id, string name, ColumnDisplayType defaultDisplay, List<ColumnDisplayType> displayOptions, bool display, bool compare, uint width) { this.columnIDfield = id; this.columnNamefield = name; this.defaultDisplayTypefield = defaultDisplay; this.displayTypeOptionsfiels = displayOptions; this.displayColumnfield = display; this.canComparefield = compare; this.defaultWidthfield = width; }
public DeleteStp(string name, StoredProcedureParameters parameters, string table, TableColumns columns, string keyName, string keyColumn, string keyType, object keyValue) : base(name, parameters, table, columns, keyName, keyColumn, keyType) { KeyValue = keyValue; }
// Generates content of tableDefinitionPart5. private void GenerateTableDefinitionPart5Content(TableDefinitionPart tableDefinitionPart5) { Table table5 = new Table(){ Id = (UInt32Value)2U, Name = "ProductTable1", DisplayName = "ProductTable1", Reference = "H1:I11", TotalsRowShown = false, HeaderRowFormatId = (UInt32Value)11U }; AutoFilter autoFilter5 = new AutoFilter(){ Reference = "H1:I11" }; TableColumns tableColumns5 = new TableColumns(){ Count = (UInt32Value)2U }; TableColumn tableColumn11 = new TableColumn(){ Id = (UInt32Value)1U, Name = "ProductName" }; TableColumn tableColumn12 = new TableColumn(){ Id = (UInt32Value)2U, Name = "Price", DataFormatId = (UInt32Value)10U }; tableColumns5.Append(tableColumn11); tableColumns5.Append(tableColumn12); TableStyleInfo tableStyleInfo5 = new TableStyleInfo(){ Name = "TableStyleMedium2", ShowFirstColumn = false, ShowLastColumn = false, ShowRowStripes = true, ShowColumnStripes = false }; table5.Append(autoFilter5); table5.Append(tableColumns5); table5.Append(tableStyleInfo5); tableDefinitionPart5.Table = table5; }
// Generates content of tableDefinitionPart1. private void GenerateTableDefinitionPart1Content(TableDefinitionPart tableDefinitionPart1) { Table table1 = new Table(){ Id = (UInt32Value)2U, Name = "Table2", DisplayName = "Table2", Reference = "E1:G4", TotalsRowShown = false }; AutoFilter autoFilter1 = new AutoFilter(){ Reference = "E1:G4" }; TableColumns tableColumns1 = new TableColumns(){ Count = (UInt32Value)3U }; TableColumn tableColumn1 = new TableColumn(){ Id = (UInt32Value)1U, Name = "Column1" }; TableColumn tableColumn2 = new TableColumn(){ Id = (UInt32Value)2U, Name = "Column2" }; TableColumn tableColumn3 = new TableColumn(){ Id = (UInt32Value)3U, Name = "Column3" }; tableColumns1.Append(tableColumn1); tableColumns1.Append(tableColumn2); tableColumns1.Append(tableColumn3); TableStyleInfo tableStyleInfo1 = new TableStyleInfo(){ Name = "TableStyleMedium2", ShowFirstColumn = false, ShowLastColumn = false, ShowRowStripes = true, ShowColumnStripes = false }; table1.Append(autoFilter1); table1.Append(tableColumns1); table1.Append(tableStyleInfo1); tableDefinitionPart1.Table = table1; }
// Generates content of tableDefinitionPart2. private void GenerateTableDefinitionPart2Content(TableDefinitionPart tableDefinitionPart2) { Table table2 = new Table(){ Id = (UInt32Value)1U, Name = "Table1", DisplayName = "Table1", Reference = "A1:C4", TotalsRowShown = false }; AutoFilter autoFilter2 = new AutoFilter(){ Reference = "A1:C4" }; TableColumns tableColumns2 = new TableColumns(){ Count = (UInt32Value)3U }; TableColumn tableColumn4 = new TableColumn(){ Id = (UInt32Value)1U, Name = "Column1" }; TableColumn tableColumn5 = new TableColumn(){ Id = (UInt32Value)2U, Name = "Column2" }; TableColumn tableColumn6 = new TableColumn(){ Id = (UInt32Value)3U, Name = "Column3" }; tableColumns2.Append(tableColumn4); tableColumns2.Append(tableColumn5); tableColumns2.Append(tableColumn6); TableStyleInfo tableStyleInfo2 = new TableStyleInfo(){ Name = "TableStyleMedium2", ShowFirstColumn = false, ShowLastColumn = false, ShowRowStripes = true, ShowColumnStripes = false }; table2.Append(autoFilter2); table2.Append(tableColumns2); table2.Append(tableStyleInfo2); tableDefinitionPart2.Table = table2; }
private static void writeGetRowsMethod( DBConnection cn, TextWriter writer, Database database, string table, TableColumns tableColumns, bool isSmallTable, bool tableUsesRowVersionedCaching, bool isRevisionHistoryTable, bool excludePreviousRevisions) { // header var methodName = "GetRows" + ( isSmallTable ? "MatchingConditions" : "" ) + ( isRevisionHistoryTable && !excludePreviousRevisions ? "IncludingPreviousRevisions" : "" ); CodeGenerationStatics.AddSummaryDocComment( writer, "Retrieves the rows from the table that match the specified conditions, ordered in a stable way." + ( isSmallTable ? " Since the table is specified as small, you should only use this method if you cannot filter the rows in code." : "" ) ); writer.WriteLine( "public static IEnumerable<Row> " + methodName + "( params " + DataAccessStatics.GetTableConditionInterfaceName( cn, database, table ) + "[] conditions ) {" ); // body // If it's a primary key query, use RowsByPk if possible. foreach( var i in tableColumns.KeyColumns ) { var equalityConditionClassName = DataAccessStatics.GetEqualityConditionClassName( cn, database, table, i ); writer.WriteLine( "var {0}Condition = conditions.OfType<{1}>().FirstOrDefault();".FormatWith( i.CamelCasedName, equalityConditionClassName ) ); } writer.WriteLine( "var cache = Cache.Current;" ); var pkConditionVariableNames = tableColumns.KeyColumns.Select( i => i.CamelCasedName + "Condition" ); writer.WriteLine( "var isPkQuery = " + StringTools.ConcatenateWithDelimiter( " && ", pkConditionVariableNames.Select( i => i + " != null" ).ToArray() ) + " && conditions.Count() == " + tableColumns.KeyColumns.Count() + ";" ); writer.WriteLine( "if( isPkQuery ) {" ); writer.WriteLine( "Row row;" ); writer.WriteLine( "if( cache." + ( excludePreviousRevisions ? "LatestRevision" : "" ) + "RowsByPk.TryGetValue( System.Tuple.Create( " + StringTools.ConcatenateWithDelimiter( ", ", pkConditionVariableNames.Select( i => i + ".Value" ).ToArray() ) + " ), out row ) )" ); writer.WriteLine( "return row.ToSingleElementArray();" ); writer.WriteLine( "}" ); var commandConditionsExpression = "conditions.Select( i => i.CommandCondition )"; if( excludePreviousRevisions ) commandConditionsExpression += ".Concat( getLatestRevisionsCondition().ToSingleElementArray() )"; writer.WriteLine( "return cache.Queries.GetResultSet( " + commandConditionsExpression + ", commandConditions => {" ); writeResultSetCreatorBody( cn, writer, database, table, tableColumns, tableUsesRowVersionedCaching, excludePreviousRevisions, "!isPkQuery" ); writer.WriteLine( "} );" ); writer.WriteLine( "}" ); }
private static void writeGetRowMatchingIdMethod( DBConnection cn, TextWriter writer, Database database, string table, TableColumns tableColumns, bool isSmallTable, bool tableUsesRowVersionedCaching, bool isRevisionHistoryTable) { writer.WriteLine( "public static Row GetRowMatchingId( " + tableColumns.KeyColumns.Single().DataTypeName + " id, bool returnNullIfNoMatch = false ) {" ); if( isSmallTable ) { writer.WriteLine( "var cache = Cache.Current;" ); var commandConditionsExpression = isRevisionHistoryTable ? "getLatestRevisionsCondition().ToSingleElementArray()" : "new InlineDbCommandCondition[ 0 ]"; writer.WriteLine( "cache.Queries.GetResultSet( " + commandConditionsExpression + ", commandConditions => {" ); writeResultSetCreatorBody( cn, writer, database, table, tableColumns, tableUsesRowVersionedCaching, isRevisionHistoryTable, "true" ); writer.WriteLine( "} );" ); var rowsByPkExpression = "cache.{0}RowsByPk".FormatWith( isRevisionHistoryTable ? "LatestRevision" : "" ); writer.WriteLine( "if( !returnNullIfNoMatch )" ); writer.WriteLine( "return {0}[ System.Tuple.Create( id ) ];".FormatWith( rowsByPkExpression ) ); writer.WriteLine( "Row row;" ); writer.WriteLine( "return {0}.TryGetValue( System.Tuple.Create( id ), out row ) ? row : null;".FormatWith( rowsByPkExpression ) ); } else { writer.WriteLine( "var rows = GetRows( new " + DataAccessStatics.GetEqualityConditionClassName( cn, database, table, tableColumns.KeyColumns.Single() ) + "( id ) );" ); writer.WriteLine( "return returnNullIfNoMatch ? rows.SingleOrDefault() : rows.Single();" ); } writer.WriteLine( "}" ); }
internal static void Generate( DBConnection cn, TextWriter writer, string baseNamespace, Database database, Configuration.SystemDevelopment.Database configuration) { if( configuration.rowConstantTables == null ) return; writer.WriteLine( "namespace " + baseNamespace + "." + database.SecondaryDatabaseName + "RowConstants {" ); foreach( var table in configuration.rowConstantTables ) { Column valueColumn; var orderIsSpecified = !table.orderByColumn.IsNullOrWhiteSpace(); var values = new List<string>(); var names = new List<string>(); try { var columns = new TableColumns( cn, table.tableName, false ); valueColumn = columns.AllColumnsExceptRowVersion.Single( column => column.Name.ToLower() == table.valueColumn.ToLower() ); var nameColumn = columns.AllColumnsExceptRowVersion.Single( column => column.Name.ToLower() == table.nameColumn.ToLower() ); var cmd = new InlineSelect( new[] { valueColumn.Name, nameColumn.Name }, "FROM " + table.tableName, false, orderByClause: orderIsSpecified ? "ORDER BY " + table.orderByColumn : "" ); cmd.Execute( cn, reader => { while( reader.Read() ) { if( reader.IsDBNull( reader.GetOrdinal( valueColumn.Name ) ) ) values.Add( valueColumn.NullValueExpression.Any() ? valueColumn.NullValueExpression : "null" ); else { var valueString = valueColumn.ConvertIncomingValue( reader[ valueColumn.Name ] ).ToString(); values.Add( valueColumn.DataTypeName == typeof( string ).ToString() ? "\"{0}\"".FormatWith( valueString ) : valueString ); } names.Add( nameColumn.ConvertIncomingValue( reader[ nameColumn.Name ] ).ToString() ); } } ); } catch( Exception e ) { throw new UserCorrectableException( "Column or data retrieval failed for the " + table.tableName + " row constant table. Make sure the table and the value, name, and order by columns exist.", e ); } CodeGenerationStatics.AddSummaryDocComment( writer, "Provides constants copied from the " + table.tableName + " table." ); var className = table.tableName.TableNameToPascal( cn ) + "Rows"; writer.WriteLine( "public class " + className + " {" ); // constants for( var i = 0; i < values.Count; i++ ) { CodeGenerationStatics.AddSummaryDocComment( writer, "Constant generated from row in database table." ); // It's important that row constants actually *be* constants (instead of static readonly) so they can be used in switch statements. writer.WriteLine( "public const " + valueColumn.DataTypeName + " " + EwlStatics.GetCSharpIdentifier( names[ i ] ) + " = " + values[ i ] + ";" ); } // one to one map var dictionaryType = "OneToOneMap<" + valueColumn.DataTypeName + ", string>"; writer.WriteLine( "private static readonly " + dictionaryType + " " + dictionaryName + " = new " + dictionaryType + "();" ); writeStaticConstructor( writer, className, names, values, valueColumn.DataTypeName ); // methods writeGetNameFromValueMethod( writer, valueColumn.DataTypeName ); writeGetValueFromNameMethod( writer, valueColumn.DataTypeName ); if( orderIsSpecified ) { writeGetValuesToNamesMethod( writer, valueColumn.DataTypeName ); writeFillListControlMethod( writer, valueColumn ); } writer.WriteLine( "}" ); // class } writer.WriteLine( "}" ); // namespace }
private static void writeCacheClass( DBConnection cn, TextWriter writer, Database database, string table, TableColumns tableColumns, bool isRevisionHistoryTable) { var cacheKey = database.SecondaryDatabaseName + table.TableNameToPascal( cn ) + "TableRetrieval"; var pkTupleTypeArguments = getPkTupleTypeArguments( tableColumns ); writer.WriteLine( "private class Cache {" ); writer.WriteLine( "internal static Cache Current { get { return DataAccessState.Current.GetCacheValue( \"" + cacheKey + "\", () => new Cache() ); } }" ); writer.WriteLine( "private readonly TableRetrievalQueryCache<Row> queries = new TableRetrievalQueryCache<Row>();" ); writer.WriteLine( "private readonly Dictionary<System.Tuple<{0}>, Row> rowsByPk = new Dictionary<System.Tuple<{0}>, Row>();".FormatWith( pkTupleTypeArguments ) ); if( isRevisionHistoryTable ) { writer.WriteLine( "private readonly Dictionary<System.Tuple<{0}>, Row> latestRevisionRowsByPk = new Dictionary<System.Tuple<{0}>, Row>();".FormatWith( pkTupleTypeArguments ) ); } writer.WriteLine( "private Cache() {}" ); writer.WriteLine( "internal TableRetrievalQueryCache<Row> Queries { get { return queries; } }" ); writer.WriteLine( "internal Dictionary<System.Tuple<" + pkTupleTypeArguments + ">, Row> RowsByPk { get { return rowsByPk; } }" ); if( isRevisionHistoryTable ) writer.WriteLine( "internal Dictionary<System.Tuple<" + pkTupleTypeArguments + ">, Row> LatestRevisionRowsByPk { get { return latestRevisionRowsByPk; } }" ); writer.WriteLine( "}" ); }
// Generates content of tableDefinitionPart6. private void GenerateTableDefinitionPart6Content(TableDefinitionPart tableDefinitionPart6) { Table table6 = new Table(){ Id = (UInt32Value)1U, Name = "DataTable1", DisplayName = "DataTable1", Reference = "A1:F5", TotalsRowShown = false }; AutoFilter autoFilter6 = new AutoFilter(){ Reference = "A1:F5" }; SortState sortState2 = new SortState(){ Reference = "A2:F2001" }; SortCondition sortCondition2 = new SortCondition(){ Reference = "A2:A2001" }; sortState2.Append(sortCondition2); TableColumns tableColumns6 = new TableColumns(){ Count = (UInt32Value)6U }; TableColumn tableColumn13 = new TableColumn(){ Id = (UInt32Value)1U, Name = "Date", DataFormatId = (UInt32Value)13U }; TableColumn tableColumn14 = new TableColumn(){ Id = (UInt32Value)2U, Name = "Product" }; TableColumn tableColumn15 = new TableColumn(){ Id = (UInt32Value)3U, Name = "Quantity" }; TableColumn tableColumn16 = new TableColumn(){ Id = (UInt32Value)4U, Name = "Price" }; TableColumn tableColumn17 = new TableColumn(){ Id = (UInt32Value)5U, Name = "DeliveryDate", DataFormatId = (UInt32Value)12U }; TableColumn tableColumn18 = new TableColumn(){ Id = (UInt32Value)6U, Name = "Employee" }; tableColumns6.Append(tableColumn13); tableColumns6.Append(tableColumn14); tableColumns6.Append(tableColumn15); tableColumns6.Append(tableColumn16); tableColumns6.Append(tableColumn17); tableColumns6.Append(tableColumn18); TableStyleInfo tableStyleInfo6 = new TableStyleInfo(){ Name = "TableStyleMedium2", ShowFirstColumn = false, ShowLastColumn = false, ShowRowStripes = true, ShowColumnStripes = false }; table6.Append(autoFilter6); table6.Append(sortState2); table6.Append(tableColumns6); table6.Append(tableStyleInfo6); tableDefinitionPart6.Table = table6; }
internal static void SetTableDataAndDateIfNecessary(Table table, int row, string newValue, TableColumns.NameValuePairs valueColumn, TableColumns.NameValuePairs dateColumn) { string oldValue = table.GetData(row, (int)valueColumn); if (oldValue.Equals(newValue)) return; table.SetData(row, (int)valueColumn, newValue); //table.SetData(row, (int)dateColumn, DateTime.Today.ToString(Strings.DateColumnFormatString)); if (table.GetData(0,0) != "Mode") { table.SetData(row, (int)dateColumn, PathMaker.LookupChangeLogShadow().GetLastChangeVersion());//JDK added this to fix highlighting by version } }
/// <summary> /// Generates content of tableDefinitionPart1. /// </summary> /// <param name="tableDefinitionPart">Table definition.</param> private static void GenerateTableDefinitionPartContent(TableDefinitionPart tableDefinitionPart) { Table table1 = new Table() { Id = (UInt32Value)5U, Name = Constants.MetadataRangeName, DisplayName = Constants.MetadataRangeName, Reference = "A1:B44", TotalsRowShown = false }; AutoFilter autoFilter1 = new AutoFilter() { Reference = "A1:B44" }; TableColumns tableColumns1 = new TableColumns() { Count = (UInt32Value)2U }; TableColumn tableColumn1 = new TableColumn() { Id = (UInt32Value)1U, Name = "Name" }; TableColumn tableColumn2 = new TableColumn() { Id = (UInt32Value)2U, Name = "Value" }; tableColumns1.Append(tableColumn1); tableColumns1.Append(tableColumn2); TableStyleInfo tableStyleInfo1 = new TableStyleInfo() { Name = Constants.MetadataTableStyleName, ShowFirstColumn = false, ShowLastColumn = false, ShowRowStripes = true, ShowColumnStripes = false }; table1.Append(autoFilter1); table1.Append(tableColumns1); table1.Append(tableStyleInfo1); tableDefinitionPart.Table = table1; }
/// <summary> /// Generates content of tableDefinitionPart1. /// </summary> /// <param name="tableDefinitionPart">Table definition part.</param> /// <param name="hasFileLevelMetadata">Has file level metadata.</param> private static void GenerateParameterTablePartContent(TableDefinitionPart tableDefinitionPart, bool hasFileLevelMetadata) { string reference = hasFileLevelMetadata ? "D1:I44" : "A1:F44"; Table table1 = new Table() { Id = (UInt32Value)6U, Name = Constants.ParaMetadataRangeName, DisplayName = Constants.ParaMetadataRangeName, Reference = reference, TotalsRowShown = false }; AutoFilter autoFilter1 = new AutoFilter() { Reference = reference }; TableColumns tableColumns1 = new TableColumns() { Count = (UInt32Value)6U }; tableColumns1.Append(new TableColumn() { Id = (UInt32Value)1U, Name = Statics.TableName }); tableColumns1.Append(new TableColumn() { Id = (UInt32Value)2U, Name = Statics.TableDescription }); tableColumns1.Append(new TableColumn() { Id = (UInt32Value)3U, Name = Statics.FieldName }); tableColumns1.Append(new TableColumn() { Id = (UInt32Value)4U, Name = Statics.FieldDescription }); tableColumns1.Append(new TableColumn() { Id = (UInt32Value)5U, Name = Statics.DataType }); tableColumns1.Append(new TableColumn() { Id = (UInt32Value)6U, Name = Statics.Units }); TableStyleInfo tableStyleInfo1 = new TableStyleInfo() { Name = Constants.MetadataTableStyleName, ShowFirstColumn = false, ShowLastColumn = false, ShowRowStripes = true, ShowColumnStripes = false }; table1.Append(autoFilter1); table1.Append(tableColumns1); table1.Append(tableStyleInfo1); tableDefinitionPart.Table = table1; }
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; }