using System; using System.Collections.Generic; using System.Linq; using System.Text; using HeuristicLab.BackgroundProcessing; using System.Data; using HeuristicLab.OKB.Client; using HeuristicLab.OKB.Cockpit.Admin.OKBTables; namespace HeuristicLab.OKB.Cockpit.Admin { public class TableLoadWorker : ObservableBackgroundWorker { public string TableName { get; private set; } public DataTable Table { get; private set; } public Dictionary ForeignKeys { get; private set; } private bool loadForeignKeys; public TableLoadWorker(string tableName, bool loadForeignKeys) : base("loading " + tableName) { WorkerReportsProgress = true; WorkerSupportsCancellation = true; TableName = tableName; this.loadForeignKeys = loadForeignKeys; DoWork += (s, a) => { Table = loadTable(TableName); if (loadForeignKeys) ForeignKeys = LoadForeignKeys(); }; } private DataTable loadTable(string tableName) { ReportProgress(0); TableServiceClient client = ClientFactory.Create(); int nRows = 0; DataTable table = client.PrepareDataTable(out nRows, tableName); int stepSize = Math.Max(1, Math.Min(nRows / 100, 200)); if (nRows > 0) { DataTable newRows = new DataTable(); do { newRows = client.GetNextRows(stepSize); table.Merge(newRows); ReportProgress(100 * table.Rows.Count / nRows); } while (!CancellationPending && newRows.Rows.Count > 0); } client.FinishFetchingRows(); client.Close(); return table; } private Dictionary LoadForeignKeys() { var fk = new Dictionary(); Name = "loading referenced tables"; var foreignKeyColumns = Table.Columns.Cast() .Where(c => c.ColumnName.EndsWith("Id") && c.ColumnName.Length > 2); foreach (var column in foreignKeyColumns) { string tableName = column.ColumnName.Substring(0, column.ColumnName.Length - 2); DataTable referencedTable = loadTable(tableName); fk[column.ColumnName] = referencedTable; } return fk; } } }