/// <summary> /// GetVariableMarkup gets both the markup used in the HTMLRESULTS section and a DataTable /// with a row for each TABLES and its properties. /// </summary> /// <param name="table">An instance of a DataTable containing properties of TABLES.</param> /// <returns>Returns the markup used in the HTMLRESULTS section.</returns> private string GetTableMarkup(out DataTable table) { StringBuilder sb = new StringBuilder(); table = new DataTable(); table.Columns.Add(ColumnNames.DATA_TABLE_NAME, typeof(string)); table.Columns.Add(ColumnNames.TYPE, typeof(string)); table.Columns.Add(ColumnNames.NUMBER_OF_FIELDS, typeof(Int16)); table.Columns.Add(ColumnNames.LINK, typeof(string)); table.Columns.Add(ColumnNames.PRIMARY_KEY, typeof(string)); table.Columns.Add(ColumnNames.DESCRIPTION, typeof(string)); try { IDbDriver driver = null; if (this.Context.CurrentRead != null) { driver = Epi.Data.DBReadExecute.GetDataDriver(this.Context.CurrentRead.File); } if (!string.IsNullOrEmpty(dbViewsOpt)) { driver = Epi.Data.DBReadExecute.GetDataDriver(dbViewsOpt); } List <string> tableNames = driver.GetTableNames(); int colCount; foreach (string name in tableNames) { StringBuilder primaryKeys = new StringBuilder(); colCount = driver.GetTableData(name).Columns.Count; foreach (DataColumn key in driver.GetTableData(name).PrimaryKey) { primaryKeys.Append(string.Format("{0} ", key.ColumnName)); } DataRow row = table.NewRow(); row[ColumnNames.DATA_TABLE_NAME] = name; row[ColumnNames.TYPE] = GetTableTypeName(name, colCount); row[ColumnNames.NUMBER_OF_FIELDS] = colCount; row[ColumnNames.LINK] = string.Empty; row[ColumnNames.PRIMARY_KEY] = primaryKeys.ToString(); row[ColumnNames.DESCRIPTION] = string.Empty; table.Rows.Add(row); } } catch (NullReferenceException) { throw new GeneralException(SharedStrings.NO_DATA_SOURCE); } return(BuildMarkupFromTable(table, string.Empty)); }
GlobalizationDataSet ReadResourcesFromDatabase(IDbDriver dataSource, string tableName) { AppendToLog("Reading database"); GlobalizationDataSet ds = new GlobalizationDataSet(); if (string.IsNullOrEmpty(tableName)) { // default table name tableName = ds.CulturalResources.TableName; } DataTable dt = dataSource.GetTableData(tableName); try { DataTableReader reader = new DataTableReader(dt); ds.CulturalResources.BeginLoadData(); ds.CulturalResources.Load(reader); ds.CulturalResources.EndLoadData(); } catch (Exception ex) { throw new GeneralException("Import database format is invalid.", ex); } return(ds); }
GlobalizationDataSet ReadResourcesFromDatabase(IDbDriver dataSource, string tableName) { AppendToLog("Reading database"); GlobalizationDataSet ds = new GlobalizationDataSet(); if (string.IsNullOrEmpty(tableName)) { // default table name tableName = ds.CulturalResources.TableName; } DataTable dt = dataSource.GetTableData(tableName); try { DataTableReader reader = new DataTableReader(dt); ds.CulturalResources.BeginLoadData(); ds.CulturalResources.Load(reader); ds.CulturalResources.EndLoadData(); } catch (Exception ex) { throw new GeneralException("Import database format is invalid.", ex); } return ds; }
public static DataTable JoinPageTables(IDbDriver db, View vw) { DataTable unfilteredTable = new DataTable(); // Get the form's field count, adding base table fields plus GUID field for each page. If less than 255, use SQL relate; otherwise, >255 exceeds OLE field capacity and we need to use a less efficient method if (vw.Fields.DataFields.Count + vw.Pages.Count + 5 < 255 && vw.Pages.Count < 15) { unfilteredTable = db.Select(db.CreateQuery("SELECT * " + vw.FromViewSQL)); if (unfilteredTable.Columns["RecStatus"] == null && unfilteredTable.Columns["t.RecStatus"] != null) { unfilteredTable.Columns["t.RecStatus"].ColumnName = "RecStatus"; } if (unfilteredTable.Columns.Contains("t.GlobalRecordId")) { unfilteredTable.Columns["t.GlobalRecordId"].ColumnName = "GlobalRecordId"; } foreach (Epi.Page page in vw.Pages) { string pageGUIDName = page.TableName + "." + "GlobalRecordId"; if (unfilteredTable.Columns.Contains(pageGUIDName)) { unfilteredTable.Columns.Remove(pageGUIDName); } } } else { DataTable viewTable = new DataTable(); viewTable = db.GetTableData(vw.TableName, "GlobalRecordId, UniqueKey, RECSTATUS"); viewTable.TableName = vw.TableName; DataTable relatedTable = new DataTable("relatedTable"); //int total = 0; //// Get totals for percent completion calculation //foreach (Epi.Page page in vw.Pages) //{ // string pageColumnsToSelect = String.Empty; // foreach (Field field in page.Fields) // { // if (field is RenderableField && field is IDataField) // { // total++; // } // } //} //total = total * RecordCount; //int counter = 0; foreach (Epi.Page page in vw.Pages) { List <string> pageColumnsToSelect = new List <string>(); foreach (Field field in page.Fields) { if (field is RenderableField && field is IDataField) { pageColumnsToSelect.Add(field.Name); } } pageColumnsToSelect.Add("GlobalRecordId"); DataTable pageTable = db.GetTableData(page.TableName, pageColumnsToSelect); pageTable.TableName = page.TableName; foreach (DataColumn dc in pageTable.Columns) { if (dc.ColumnName != "GlobalRecordId") { viewTable.Columns.Add(dc.ColumnName, dc.DataType); } } //try //{ // assume GlobalUniqueId column is unique and try to make it the primary key. DataColumn[] parentPrimaryKeyColumns = new DataColumn[1]; parentPrimaryKeyColumns[0] = viewTable.Columns["GlobalRecordId"]; viewTable.PrimaryKey = parentPrimaryKeyColumns; //} //catch (Exception) //{ //} foreach (DataRow row in pageTable.Rows) { DataRow viewRow = viewTable.Rows.Find(row["GlobalRecordId"].ToString()); viewRow.BeginEdit(); if (viewRow["GlobalRecordId"].ToString().Equals(row["GlobalRecordId"].ToString())) { foreach (DataColumn dc in pageTable.Columns) { if (dc.ColumnName == "GlobalRecordId") { continue; } if (row[dc.ColumnName] != DBNull.Value) { viewRow[dc.ColumnName] = row[dc]; } //counter++; //if (counter % 200 == 0 && inputs != null) //{ // if (counter > total) // { // counter = total; // } // inputs.UpdateGadgetProgress(((double)counter / (double)total) * 100); // if (total == 0) // { // inputs.UpdateGadgetStatus(SharedStrings.DASHBOARD_GADGET_STATUS_RELATING_PAGES_NO_PROGRESS); // } // else // { // inputs.UpdateGadgetStatus(string.Format(SharedStrings.DASHBOARD_GADGET_STATUS_RELATING_PAGES, ((double)counter / (double)total).ToString("P0"))); // } // if (inputs.IsRequestCancelled()) // { // return null; // } //} } } viewRow.EndEdit(); } } unfilteredTable = viewTable; } return(unfilteredTable); }
/// <summary> /// performs execution of the WRITE command /// </summary> /// <returns>object</returns> public override object Execute() { object result = null; Context.AnalysisCheckCodeInterface.ShowWaitDialog("Exporting data..."); //string[] tmp = this.OutTarget.ToString().Split(':'); //string FilePath = null; //if (tmp.Length <= 2) //{ // FilePath = tmp[0]; //} //else //{ // FilePath = tmp[0] + ":" + tmp[1]; //} //FilePath = FilePath.Trim().Trim(new char[] { '\'' }); //string TableName; //if (tmp.Length > 1) //{ // TableName = tmp[tmp.Length - 1].Replace("]", "").Replace("[", "").Trim().Trim('\''); //} //else //{ // TableName = this.OutTarget; // FilePath = this.Context.CurrentProject.CollectedDataConnectionString; //} CurrentDataTable = this.Context.DataSet.Tables["output"].Clone(); foreach (DataRow row in this.Context.GetOutput(new List <string>())) { CurrentDataTable.ImportRow(row); } if (this.IdentifierList[0] == "*") { for (int i = 0; i < CurrentDataTable.Columns.Count; i++) { IVariable var = (IVariable)this.Context.GetVariable(CurrentDataTable.Columns[i].ColumnName); if (var != null) { if (var.VarType != VariableType.Global && var.VarType != VariableType.Permanent) { TempVariableList.Add(CurrentDataTable.Columns[i].ColumnName.ToUpperInvariant()); } } else { TempVariableList.Add(CurrentDataTable.Columns[i].ColumnName.ToUpperInvariant()); } } } else { for (int i = 0; i < this.IdentifierList.Length; i++) { TempVariableList.Add(this.IdentifierList[i].ToUpperInvariant()); } } if (isExceptionList) { for (int i = CurrentDataTable.Columns.Count - 1; i > -1; i--) { if (TempVariableList.Contains(CurrentDataTable.Columns[i].ColumnName.ToUpperInvariant())) { //CurrentDataTable.Columns.Remove(CurrentDataTable.Columns[i]); } else { if (this.IdentifierList[0] == "*") { IVariable var = (IVariable)this.Context.GetVariable(CurrentDataTable.Columns[i].ColumnName); if (var != null) { if (var != null && var.VarType != VariableType.Global && var.VarType != VariableType.Permanent) { VariableList.Add(var.Name.ToUpperInvariant()); } } } else { VariableList.Add(CurrentDataTable.Columns[i].ColumnName.ToUpperInvariant()); } } } } else // is NOT an isExceptionList { for (int i = 0; i < CurrentDataTable.Columns.Count; i++) { if (TempVariableList.Contains(CurrentDataTable.Columns[i].ColumnName.ToUpperInvariant())) { VariableList.Add(CurrentDataTable.Columns[i].ColumnName.ToUpperInvariant()); } else { //CurrentDataTable.Columns.Remove(CurrentDataTable.Columns[i]); } } } try { Dictionary <string, List <TableColumn> > WideTableColumns = null; DataSets.Config.DataDriverDataTable dataDrivers = Configuration.GetNewInstance().DataDrivers; IDbDriverFactory dbFactory = null; foreach (DataSets.Config.DataDriverRow dataDriver in dataDrivers) { dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(dataDriver.Type); if (dbFactory.CanClaimConnectionString(FilePath)) { break; } } OutputDriver = DBReadExecute.GetDataDriver(FilePath, this.isConnectionString); if (OutputDriver.GetType().Name.Equals("CsvFile", StringComparison.OrdinalIgnoreCase) || this.FileDataFormat.Equals("TEXT", StringComparison.OrdinalIgnoreCase)) { if (!this.TableName.EndsWith(".txt") && !this.TableName.EndsWith(".csv") && !this.TableName.EndsWith("#csv") && !this.TableName.EndsWith("#txt")) { this.TableName = this.TableName + ".csv"; } } this.OutTarget = this.FilePath + ":" + this.TableName; this.curFile = OutputDriver.DataSource; if (!OutputDriver.CheckDatabaseExistance(FilePath, TableName, this.isConnectionString)) { DbDriverInfo collectDbInfo = new DbDriverInfo(); Type SqlDriverType = Type.GetType("Epi.Data.SqlServer.SqlDBFactory, Epi.Data.SqlServer"); if (DBReadExecute.DataSource.GetType().AssemblyQualifiedName == SqlDriverType.AssemblyQualifiedName) { collectDbInfo.DBCnnStringBuilder = new System.Data.SqlClient.SqlConnectionStringBuilder(); } else { collectDbInfo.DBCnnStringBuilder = new System.Data.OleDb.OleDbConnectionStringBuilder(); } collectDbInfo.DBCnnStringBuilder.ConnectionString = dbFactory.ConvertFileStringToConnectionString(FilePath); //collectDbInfo.DBCnnStringBuilder = dbFactory.RequestDefaultConnection(dbFactory.FilePath.Trim()); OutputDriver = dbFactory.CreateDatabaseObject(collectDbInfo.DBCnnStringBuilder); collectDbInfo.DBName = OutputDriver.DbName; dbFactory.CreatePhysicalDatabase(collectDbInfo); } bool?deleteSuccessful = null; if (this.WriteMode.Equals("REPLACE", StringComparison.OrdinalIgnoreCase) && DBReadExecute.CheckDatabaseTableExistance(FilePath, TableName, this.isConnectionString)) { deleteSuccessful = OutputDriver.DeleteTable(TableName); } List <TableColumn> TableColumns = new List <TableColumn>(); if (!DBReadExecute.CheckDatabaseTableExistance(FilePath, TableName, this.isConnectionString)) { foreach (DataColumn column in CurrentDataTable.Columns) { if (VariableList.Contains(column.ColumnName.ToUpperInvariant())) { bool isPermanentVariable = false; IVariable candidate = Context.MemoryRegion.GetVariable(column.ColumnName); if (candidate != null && candidate.IsVarType(VariableType.Permanent)) { isPermanentVariable = true; } if (isPermanentVariable == false) { TableColumn newTableColumn; if (column.DataType.ToString() == "System.String") { if (column.MaxLength <= 0) { newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), int.MaxValue, column.AllowDBNull); } else { newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), column.MaxLength, column.AllowDBNull); } } else if (column.DataType.ToString() == "System.Guid") { if (column.MaxLength <= 0) { newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), int.MaxValue, column.AllowDBNull); } else { newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), column.MaxLength, column.AllowDBNull); } } else { newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), column.AllowDBNull); } newTableColumn.AllowNull = column.AllowDBNull; newTableColumn.IsIdentity = column.Unique; TableColumns.Add(newTableColumn); } } } if ( ( (!(OutputDriver.GetType().Name.Equals("AccessDatabase", StringComparison.OrdinalIgnoreCase) || OutputDriver.GetType().Name.Equals("Access2007Database", StringComparison.OrdinalIgnoreCase) || OutputDriver.GetType().Name.Equals("ExcelWorkbook", StringComparison.OrdinalIgnoreCase) || OutputDriver.GetType().Name.Equals("Excel2007Workbook", StringComparison.OrdinalIgnoreCase)) && VariableList.Count <= Max_Number_Columns) || OutputDriver.GetType().Name.Equals("SqlDatabase", StringComparison.OrdinalIgnoreCase) ) ) { OutputDriver.CreateTable(TableName, TableColumns); } else { if (OutputDriver.GetType().Name.Equals("ExcelWorkbook", StringComparison.OrdinalIgnoreCase) || OutputDriver.GetType().Name.Equals("Excel2007Workbook", StringComparison.OrdinalIgnoreCase)) { WideTableColumns = this.CreateExcelWideTable(TableColumns); } else if (!OutputDriver.GetType().Name.Equals("CsvFile", StringComparison.OrdinalIgnoreCase)) { WideTableColumns = this.CreateAccessWideTable(TableColumns); } } } else // check that column name exists in destinationl { foreach (string columnName in VariableList) { bool isFound = false; foreach (DataColumn column in CurrentDataTable.Columns) { if (column.ColumnName.ToUpperInvariant() == columnName.ToUpperInvariant()) { isFound = true; break; } } if (!isFound) { TableColumn newTableColumn; DataColumn column = CurrentDataTable.Columns[columnName]; if (column.DataType.ToString() == "System.String") { newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), column.MaxLength, column.AllowDBNull); } else if (column.DataType.ToString() == "System.Guid") { newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), column.MaxLength, column.AllowDBNull); } else { newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), column.AllowDBNull); } newTableColumn.AllowNull = column.AllowDBNull; newTableColumn.IsIdentity = column.Unique; OutputDriver.AddColumn(TableName, newTableColumn); } } if ((OutputDriver.GetType().Name.Equals("AccessDatabase", StringComparison.OrdinalIgnoreCase) || OutputDriver.GetType().Name.Equals("Access2007Database", StringComparison.OrdinalIgnoreCase) || OutputDriver.GetType().Name.Equals("ExcelWorkbook", StringComparison.OrdinalIgnoreCase) || OutputDriver.GetType().Name.Equals("Excel2007Workbook", StringComparison.OrdinalIgnoreCase)) && VariableList.Count > Max_Number_Columns) { foreach (DataColumn column in CurrentDataTable.Columns) { if (VariableList.Contains(column.ColumnName.ToUpperInvariant())) { bool isPermanentVariable = false; IVariable candidate = Context.MemoryRegion.GetVariable(column.ColumnName); if (candidate != null && candidate.IsVarType(VariableType.Permanent)) { isPermanentVariable = true; } if (isPermanentVariable == false) { TableColumn newTableColumn; if (column.DataType.ToString() == "System.String") { if (column.MaxLength <= 0) { newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), int.MaxValue, column.AllowDBNull); } else { newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), column.MaxLength, column.AllowDBNull); } } else if (column.DataType.ToString() == "System.Guid") { if (column.MaxLength <= 0) { newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), int.MaxValue, column.AllowDBNull); } else { newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), column.MaxLength, column.AllowDBNull); } } else { newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), column.AllowDBNull); } newTableColumn.AllowNull = column.AllowDBNull; newTableColumn.IsIdentity = column.Unique; TableColumns.Add(newTableColumn); } } } if (OutputDriver.GetType().Name.Equals("ExcelWorkbook", StringComparison.OrdinalIgnoreCase) || OutputDriver.GetType().Name.Equals("Excel2007Workbook", StringComparison.OrdinalIgnoreCase)) { WideTableColumns = this.CreateExcelWideTable(TableColumns); } else { WideTableColumns = this.CreateAccessWideTable(TableColumns, false); } } } ////APPEND| REPLACE | !Null //if (this.WriteMode.Equals("REPLACE", StringComparison.OrdinalIgnoreCase)) //{ // WriteMethod = this.ReplaceWrite; //} //else //{ // WriteMethod = this.AppendWrite; //} if (OutputDriver.GetType().Name.Equals("CsvFile", StringComparison.OrdinalIgnoreCase) || this.FileDataFormat.Equals("TEXT", StringComparison.OrdinalIgnoreCase)) { if (TableColumns.Count == 0) { foreach (DataColumn column in CurrentDataTable.Columns) { if (VariableList.Contains(column.ColumnName.ToUpperInvariant())) { bool isPermanentVariable = false; IVariable candidate = Context.MemoryRegion.GetVariable(column.ColumnName); if (candidate != null && candidate.IsVarType(VariableType.Permanent)) { isPermanentVariable = true; } if (isPermanentVariable == false) { TableColumn newTableColumn; if (column.DataType.ToString() == "System.String") { if (column.MaxLength <= 0) { newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), int.MaxValue, column.AllowDBNull); } else { newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), column.MaxLength, column.AllowDBNull); } } else if (column.DataType.ToString() == "System.Guid") { if (column.MaxLength <= 0) { newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), int.MaxValue, column.AllowDBNull); } else { newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), column.MaxLength, column.AllowDBNull); } } else { newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), column.AllowDBNull); } newTableColumn.AllowNull = column.AllowDBNull; newTableColumn.IsIdentity = column.Unique; TableColumns.Add(newTableColumn); } } } } this.WriteCSVFile(TableColumns); } else if ((OutputDriver.GetType().Name.Equals("AccessDatabase", StringComparison.OrdinalIgnoreCase) || OutputDriver.GetType().Name.Equals("Access2007Database", StringComparison.OrdinalIgnoreCase) || OutputDriver.GetType().Name.Equals("ExcelWorkbook", StringComparison.OrdinalIgnoreCase) || OutputDriver.GetType().Name.Equals("Excel2007Workbook", StringComparison.OrdinalIgnoreCase)) && VariableList.Count > Max_Number_Columns) { this.PopulateTable(WideTableColumns); } else { DataTable sourceTable = OutputDriver.GetTableData(TableName); OutputDriver.IsBulkOperation = true; StringBuilder sqlquery = new StringBuilder(); int count = 0; sqlquery.Append("create table [" + TableName + "] ( "); foreach (string column in VariableList) { string columnName = String.Empty; if (!column.Contains(".") && !OutputDriver.ColumnExists(TableName, column)) { columnName = column; if (count > 0) { sqlquery.Append(", "); } sqlquery.Append(" [" + columnName + "] " + DBReadExecute.SQLGetType(CurrentDataTable.Columns[column])); count++; } } sqlquery.Append(" )"); if (count > 0) { Query qr = OutputDriver.CreateQuery(sqlquery.ToString()); OutputDriver.ExecuteNonQuery(qr); } OutputDriver.IsBulkOperation = false; //Insert data into table ////Open connection ////Setup Schema ////Loop through records ////Close connection DataTable WritableTable = CurrentDataTable.Clone(); for (int i = WritableTable.Columns.Count - 1; i > -1; i--) { if (WritableTable.Columns[i].DataType == typeof(Guid)) { WritableTable.Columns[i].DataType = typeof(String); } } for (int i = WritableTable.Columns.Count - 1; i > -1; i--) { DataColumn col = WritableTable.Columns[i]; if (!VariableList.Contains(col.ColumnName.ToUpperInvariant())) { WritableTable.Columns.Remove(col); } } foreach (DataRow row in CurrentDataTable.Select("", this.Context.SortExpression.ToString())) { DataRow newRow = WritableTable.NewRow(); foreach (string column in VariableList) { newRow[column] = row[column]; } WritableTable.Rows.Add(newRow); } System.Data.Common.DbDataReader DataReader = WritableTable.CreateDataReader(); DBReadExecute.InsertBulkRows(FilePath, "Select * From [" + TableName + "]", DataReader, SetGadgetStatusHandler); if (CurrentDataTable.Rows.Count > 0) { this.statusMessage = "Export completed successfully, "; } else { this.statusMessage = "Export was not completed successfully, "; } this.statusMessage += CurrentDataTable.Rows.Count.ToString() + " records written."; DataReader.Close(); } } catch (Exception ex) { this.statusMessage = "Problems exporting records: " + ex.ToString(); System.Console.Write(ex); } finally { Context.AnalysisCheckCodeInterface.HideWaitDialog(); } /* * * * * * Comments * Records deleted in Enter or selected in Analysis are handled as in other Analysis commands. * Defined variables may be written, allowing the creation of a new Epi Info file that makes the changes permanent. * Global and permanent variables will not be written unless explicitly specified. * To write only selected variables, the word EXCEPT may be inserted to indicate all variables except those following EXCEPT. * If the output file specified does not exist, the WRITE command will attempt to create it. * Either APPEND or REPLACE must be specified to indicate that an existing file/table by the * same name will be erased or records will be appended to the existing file/table. * If some, but not all, of the fields being written match those in an existing file during an APPEND, * the unmatched fields are added to the output table. * For Epi 6 REC or Access/EpiInfo table outputs, if there are no records, * the WRITE command creates a table/file with variable information but no data. * * WRITE <METHOD> {<output type>} {<project>:}table {[<variable(s)>]} * WRITE <METHOD> {<output type>} {<project>:}table * EXCEPT {[<variable(s)>]} * * The <METHOD> represents either REPLACE or APPEND * The <project> represents the path and filename of the output. * The <variable(s)> represents one or more variable names. * The <output type> represents the following allowable outputs: * * Database Type Specifier Element * * Jet "Access 97" "Access 2000" * "Epi 2000" <path:<table> * dBase III "dBase III" <path> * dBase IV "dBase IV" <path> * dBase 5.0 "dBase 5.0" <path> * Paradox 3.x "Paradox 3.x" <path> * Paradox 4.x "Paradox 4.x" <path> * FoxPro 2.0 "FoxPro 2.0" <path> * FoxPro 2.5 "FoxPro 2.5" <path> * FoxPro 2.6 "FoxPro 2.6" <path> * Excel 3.0 "Excel 3.0" <path> * Excel 4.0 "Excel 4.0" <path> * Epi Info 6 "Epi6" <path> * Text (Delimited) "Text" <path> * */ args.Add("COMMANDNAME", CommandNames.WRITE); args.Add("WRITEMODE", this.WriteMode); args.Add("OUTTARGET", this.OutTarget); args.Add("STATUS", this.statusMessage); //args.Add("PROGRESST", this.progress.ToString()); //args.Add("ROWCOUNT", CurrentDataTable.Select("", this.Context.SortExpression.ToString()).Length.ToString()); this.Context.AnalysisCheckCodeInterface.Display(args); return(result); }
// /// <summary> // /// Returns the Code Table Columns Schema as a datatable // /// </summary> // /// <param name="tableName"></param> // /// <returns></returns> //[Obsolete("Use of DataTable in this context is no different than the use of a multidimensional System.Object array (not recommended).", false)] // public DataTable GetCodeTableColumnSchema(string tableName) // { // Util.Assert(tableName.StartsWith("meta") == false); // return db.GetTableColumnSchema(tableName); // } /// <summary> /// Returns the data in the code table as a DataTable /// </summary> /// <param name="tableName"></param> /// <returns></returns> public DataTable GetCodeTableData(string tableName) { Util.Assert(tableName.StartsWith("meta") == false); return(db.GetTableData(tableName)); }
/// <summary> /// Checks for problems in the source project /// </summary> protected void CheckForProblems() { IDbDriver driver = SourceProject.CollectedData.GetDatabase(); if (driver == null) { ExportInfo.Succeeded = false; ExportInfo.AddError("Data driver is null.", "999999"); throw new InvalidOperationException("Data driver cannot be null"); } // Check #1 - Make sure the base table exists and that it has a Global Record Id field, Record status field, and Unique key field. DataTable dt = driver.GetTableData(SourceForm.TableName, "GlobalRecordId, RECSTATUS, UniqueKey"); if (dt == null) { ExportInfo.Succeeded = false; ExportInfo.AddError("Source table is null.", "999998"); throw new InvalidOperationException("Source table cannot be null"); } else if (dt.Columns.Count == 0) { ExportInfo.Succeeded = false; ExportInfo.AddError("Source table has zero columns.", "999997"); throw new InvalidOperationException("Source table cannot have zero columns"); } else if (dt.Columns.Count == 1) { ExportInfo.Succeeded = false; ExportInfo.AddError("Source table has only one column.", "999996"); throw new InvalidOperationException("Source table cannot have only one column"); } int baseTableRowCount = dt.Rows.Count; // Check #2a - Make sure GlobalRecordId is a string. if (!dt.Columns[0].DataType.ToString().Equals("System.String")) { ExportInfo.Succeeded = false; ExportInfo.AddError(ImportExportSharedStrings.ERROR_PACKAGER_CHECK_INVALID_GUID_COLUMN, "101000"); throw new ApplicationException(ImportExportSharedStrings.ERROR_PACKAGER_CHECK_INVALID_GUID_COLUMN); } // Check #2b - Make sure RECSTATUS is a number if (!(dt.Columns[1].DataType.ToString().Equals("System.Byte") || dt.Columns[1].DataType.ToString().Equals("System.Int16") || dt.Columns[1].DataType.ToString().Equals("System.Int32"))) { ExportInfo.Succeeded = false; ExportInfo.AddError(ImportExportSharedStrings.ERROR_PACKAGER_CHECK_INVALID_RECSTATUS_COLUMN, "101001"); throw new ApplicationException(ImportExportSharedStrings.ERROR_PACKAGER_CHECK_INVALID_RECSTATUS_COLUMN); } // Check #3 - Make sure GlobalRecordId values haven't been replaced with something that isn't actually a GUID. // For performance reasons only the first few values are checked. if (baseTableRowCount >= 1) { string value = dt.Rows[0][0].ToString(); System.Guid guid = new Guid(value); if (baseTableRowCount >= 30) { for (int i = 0; i < 30; i++) { value = dt.Rows[i][0].ToString(); guid = new Guid(value); } } } // Check #4a - See if global record ID values are distinct on the base table. Query selectDistinctQuery = driver.CreateQuery("SELECT DISTINCT [GlobalRecordId] FROM [" + SourceForm.TableName + "]"); DataTable distinctTable = driver.Select(selectDistinctQuery); if (distinctTable.Rows.Count != baseTableRowCount) { ExportInfo.Succeeded = false; ExportInfo.AddError(ImportExportSharedStrings.ERROR_PACKAGER_CHECK_GUID_NOT_UNIQUE, "101002"); throw new ApplicationException(ImportExportSharedStrings.ERROR_PACKAGER_CHECK_GUID_NOT_UNIQUE); } // Check #4b - See if global record ID values are distinct on each page table. foreach (Page page in SourceForm.Pages) { selectDistinctQuery = driver.CreateQuery("SELECT DISTINCT [GlobalRecordId] FROM [" + page.TableName + "]"); distinctTable = driver.Select(selectDistinctQuery); if (distinctTable.Rows.Count != baseTableRowCount) { ExportInfo.Succeeded = false; ExportInfo.AddError(ImportExportSharedStrings.ERROR_PACKAGER_CHECK_GUID_NOT_UNIQUE_PAGE, "101003"); throw new ApplicationException(string.Format(ImportExportSharedStrings.ERROR_PACKAGER_CHECK_GUID_NOT_UNIQUE_PAGE, page.TableName)); } } // Check #5 - Make sure RECSTATUS has valid values. selectDistinctQuery = driver.CreateQuery("SELECT DISTINCT [RecStatus] FROM [" + SourceForm.TableName + "]"); distinctTable = driver.Select(selectDistinctQuery); foreach (DataRow row in distinctTable.Rows) { if (!row[0].ToString().Equals("1") && !row[0].ToString().Equals("0")) { ExportInfo.Succeeded = false; ExportInfo.AddError(ImportExportSharedStrings.ERROR_PACKAGER_CHECK_RECSTATUS_VALUES_INVALID, "101004"); throw new ApplicationException(ImportExportSharedStrings.ERROR_PACKAGER_CHECK_RECSTATUS_VALUES_INVALID); } } // Check #7 - Should never get here because the UI should prevent it, but do a check just in case if (SourceForm.IsRelatedView == true) { ExportInfo.Succeeded = false; ExportInfo.AddError(ImportExportSharedStrings.ERROR_PACKAGER_CHECK_RELATED_FORM, "101005"); throw new ApplicationException(ImportExportSharedStrings.ERROR_PACKAGER_CHECK_RELATED_FORM); } distinctTable = null; selectDistinctQuery = null; driver.Dispose(); driver = null; }
private void Export() { if (string.IsNullOrEmpty(txtConnectionInformation.Text)) { return; } string tableName = string.Empty; if (cmbDestinationTable.SelectedItem != null) { tableName = cmbDestinationTable.SelectedItem.ToString(); } else { tableName = cmbDestinationTable.Text; } if (string.IsNullOrEmpty(tableName)) { return; } if ( cmbDataFormats.SelectedItem != null && (cmbDataFormats.SelectedItem.ToString().Contains(".mdb") || cmbDataFormats.SelectedItem.ToString().Contains("SQL Server")) && db.TableExists("metaViews") && db.ColumnExists("metaViews", "Name") && db.TableExists("metaFields") && db.ColumnExists("metaFields", "DataTableName") ) { List <string> columnNames = new List <string>(); columnNames.Add("Name"); DataTable dt = db.GetTableData("metaViews", columnNames); foreach (DataRow row in dt.Rows) { string rowDataTable = row["Name"].ToString(); if (rowDataTable.StartsWith(tableName) || rowDataTable.ToLower().StartsWith(tableName.ToLower())) { Epi.WPF.Dashboard.Dialogs.MsgBox.ShowError(ImportExportSharedStrings.ERROR_EXPORT_CANNOT_USE_EXISTING_FORM_NAME); return; } } columnNames = new List <string>(); columnNames.Add("DataTableName"); dt = db.GetTableData("metaFields", columnNames); foreach (DataRow row in dt.Rows) { string rowDataTable = row["DataTableName"].ToString(); if (!string.IsNullOrEmpty(rowDataTable) && (tableName.StartsWith(rowDataTable) || tableName.ToLower().StartsWith(rowDataTable.ToLower()))) { string diff = tableName.Replace(rowDataTable, ""); int num = -1; bool success = int.TryParse(diff, out num); if (success) { Epi.WPF.Dashboard.Dialogs.MsgBox.ShowError(ImportExportSharedStrings.ERROR_EXPORT_CANNOT_OVERWRITE_FORM_TABLE); return; } } } List <string> protectedTableNames = new List <string>(); protectedTableNames.Add("metaBackgrounds"); protectedTableNames.Add("metaDataTypes"); protectedTableNames.Add("metaDbInfo"); protectedTableNames.Add("metaFields"); protectedTableNames.Add("metaFieldTypes"); protectedTableNames.Add("metaImages"); protectedTableNames.Add("metaLinks"); protectedTableNames.Add("metaPages"); protectedTableNames.Add("metaViews"); foreach (string protectedTableName in protectedTableNames) { if (protectedTableName.Equals(tableName) || protectedTableName.ToLower().Equals(tableName.ToLower())) { Epi.WPF.Dashboard.Dialogs.MsgBox.ShowError(ImportExportSharedStrings.ERROR_EXPORT_CANNOT_OVERWRITE_META); return; } } } List <string> badFieldNames = new List <string>(); foreach (string fieldName in lbxExportFields.SelectedItems) { if (fieldName.StartsWith(" ") || fieldName.EndsWith(" ")) { badFieldNames.Add(fieldName); } } string fileName = db.DataSource + "\\" + tableName; if (!fileName.ToLower().EndsWith(".csv") && !fileName.ToLower().EndsWith(".txt")) { fileName = fileName + ".csv"; } bool writeToFlatFile = false; if (cmbDataFormats.SelectedItem.ToString().ToLower().Contains("ascii")) { writeToFlatFile = true; } if (!writeToFlatFile) { if (badFieldNames.Count > 0) { string problemFields = string.Empty; int count = 0; foreach (string fieldName in badFieldNames) { problemFields = problemFields + fieldName + ", "; count++; } problemFields = problemFields.TrimEnd().TrimEnd(','); problemFields = problemFields + "."; Epi.WPF.Dashboard.Dialogs.MsgBox.ShowError(string.Format(SharedStrings.EXPORT_CANNOT_PROCEED_LEADING_TRAILING_SPACES, problemFields)); return; } } messagePanel.MessagePanelType = Controls.MessagePanelType.StatusPanel; messagePanel.Text = string.Empty; messagePanel.Visibility = System.Windows.Visibility.Visible; messagePanel.SetProgressBarMax(dashboardHelper.RecordCount); messagePanel.SetProgressBarValue(0); messagePanel.ShowProgressBar(); exportFields.Clear(); if (lbxExportFields.SelectedItems.Count > 0) { foreach (string item in lbxExportFields.SelectedItems) { if (!string.IsNullOrEmpty(item)) { exportFields.Add(item); } } } if (lbxExportFields.Items.Count == lbxExportFields.SelectedItems.Count) { allFieldsSelected = true; } else { allFieldsSelected = false; } if (checkboxUsePrompts.IsChecked == true) { useFieldPrompts = true; } else { useFieldPrompts = false; } if (checkboxTabOrder.IsChecked == true) { useTabOrder = true; } else { useTabOrder = false; } if (worker != null && worker.WorkerSupportsCancellation) { worker.CancelAsync(); } lock (syncLock) { btnExport.IsEnabled = false; cmbDestinationTable.IsEnabled = false; cmbDataFormats.IsEnabled = false; btnConnectionBrowse.IsEnabled = false; worker = new System.ComponentModel.BackgroundWorker(); worker.WorkerSupportsCancellation = true; if (!writeToFlatFile) { worker.DoWork += new System.ComponentModel.DoWorkEventHandler(datadriverWorker_DoWork); worker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(datadriverWorker_WorkerCompleted); worker.RunWorkerAsync(tableName); } else { worker.DoWork += new System.ComponentModel.DoWorkEventHandler(fileIOWorker_DoWork); worker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(fileIOWorker_WorkerCompleted); worker.RunWorkerAsync(fileName); } } }
void ToNodeFiller_DoWork(object sender, DoWorkEventArgs e) { try { if (lvLinkedTo.InvokeRequired) { lvLinkedTo.Invoke(new MethodInvoker(delegate { lvLinkedTo.Items.Clear(); lvLinkedTo.Groups.Clear(); })); } else { lvLinkedTo.Items.Clear(); lvLinkedTo.Groups.Clear(); } if (btnUnlinkTo.InvokeRequired) { btnUnlinkTo.Invoke(new MethodInvoker(delegate { btnUnlinkTo.Enabled = false; })); } else { btnUnlinkTo.Enabled = false; } Dictionary <string, string> fieldNames = new Dictionary <string, string>(); Query query; query = db.CreateQuery ( "SELECT [metaPages.PageId] as PageId, [metaPages.ViewId] as ViewId, [metaViews.Name] as Name " + "FROM [metaPages] " + "LEFT OUTER JOIN [metaViews] ON metaPages.ViewId = metaViews.ViewId " + "WHERE [metaPages.Position] = 0" ); DataTable pageIds = db.Select(query); query = db.CreateQuery ( "SELECT [metaFields.Name] as Name, [metaFields.PageId] as PageId, [metaFields.ViewId] as ViewId, [metaFields.TabIndex] as TabIndex " + "FROM [metaFields] " + "LEFT OUTER JOIN [metaPages] ON metaPages.ViewId = metaFields.ViewId " + "WHERE [metaFields.HasTabStop] = true AND [metaPages.Position] = 0 " + "ORDER BY [metaFields.ViewId], [metaFields.TabIndex]" ); DataTable fields = db.Select(query); List <string> list = fields.AsEnumerable().Select(r => r.Field <string>(0)).ToList(); string uniqueKeys = ""; string parens = ""; string joins = ""; foreach (View view in enterMainForm.View.Project.Views) { if (!string.IsNullOrEmpty(view.TableName) && db.TableExists(view.TableName)) { if (!view.IsRelatedView) { uniqueKeys += "t" + view.Id + ".UniqueKey as Key" + view.Id + ", "; parens += "("; joins += "left outer join " + view.TableName + " t" + view.Id + " on m.ToRecordGuid = t" + view.Id + ".GlobalRecordId) "; } } } uniqueKeys = uniqueKeys.Substring(0, uniqueKeys.Length - 2) + " "; query = db.CreateQuery(@"Select FromRecordGuid, ToRecordGuid, FromViewId, ToViewId, " + uniqueKeys + " from " + parens + "metaLinks m " + joins + " where m.FromRecordGuid = @GlobalRecordId"); QueryParameter parameter = new QueryParameter("@GlobalRecordId", DbType.StringFixedLength, enterMainForm.View.CurrentGlobalRecordId); parameter.Size = enterMainForm.View.CurrentGlobalRecordId.Length; query.Parameters.Add(parameter); DataTable data = db.Select(query); if (data.Rows.Count > 0) { foreach (View view in enterMainForm.View.Project.Views) { if (lvLinkedTo.InvokeRequired) { lvLinkedTo.Invoke(new MethodInvoker(delegate { lvLinkedTo.Groups.Add(view.Id.ToString(), view.Name); })); } else { lvLinkedTo.Groups.Add(view.Id.ToString(), view.Name); } } } List <string> names = new List <string>(); string toViewId = string.Empty; string toRecordGuid = string.Empty; string fieldPrint = string.Empty; DataRow[] fieldRows = null; List <string> fieldPrintList; string collectedDataTableName = string.Empty; foreach (DataRow row in data.Rows) { ListViewItem item = new ListViewItem(); toViewId = row["ToViewId"].ToString(); toRecordGuid = row["ToRecordGuid"].ToString(); DataRow[] oneRow = pageIds.Select("ViewId = '" + toViewId + "'"); collectedDataTableName = ((string)oneRow[0]["Name"]) + ((string)oneRow[0]["PageId"].ToString()); fieldRows = fields.Select("ViewId = " + toViewId); List <string> columnNames = db.GetTableColumnNames(collectedDataTableName); fieldPrintList = fieldRows.Select(r => r.Field <string>(0)).ToList(); fieldPrintList = fieldPrintList.Intersect(columnNames).ToList(); fieldPrintList.Add("GlobalRecordId"); var datatable = db.GetTableData(collectedDataTableName, fieldPrintList); var theRow = datatable.Select("GlobalRecordId = '" + toRecordGuid + "'"); fieldPrint = row["Key" + row["ToViewId"].ToString()].ToString();; if (theRow != null) { fieldPrint += " :: "; fieldPrint += theRow[0][0].ToString() + "; " + theRow[0][1].ToString() + "; " + theRow[0][2].ToString(); } item = new ListViewItem(fieldPrint); item.Tag = row["Key" + row["ToViewId"].ToString()].ToString(); item.Name = toRecordGuid; for (int x = 0; x < data.Columns.Count; x++) { item.SubItems.Add(row[x].ToString()); } item.ImageIndex = 0; item.Group = lvLinkedTo.Groups[row["ToViewId"].ToString()]; if (names.Contains(toRecordGuid) == false) { names.Add(toRecordGuid); if (lvLinkedTo.InvokeRequired) { lvLinkedTo.Invoke(new MethodInvoker(delegate { if (lvLinkedTo.Items.ContainsKey(toRecordGuid) == false) { lvLinkedTo.Items.Add(item); } })); } else { if (lvLinkedTo.Items.ContainsKey(toRecordGuid) == false) { lvLinkedTo.Items.Add(item); } } } } } catch { } }
/// <summary> /// GetViewMarkup gets both the markup used in the HTMLRESULTS section and a DataTable /// with a row for each DBVIEW and its properties. /// </summary> /// <param name="table">An instance of a DataTable containing properties of DBVIEW.</param> /// <returns>Returns the markup used in the HTMLRESULTS section.</returns> private string GetViewMarkup(out DataTable table) { StringBuilder sb = new StringBuilder(); table = new DataTable(); table.Columns.Add(ColumnNames.DATA_TABLE_NAME, typeof(string)); table.Columns.Add(ColumnNames.TYPE, typeof(string)); table.Columns.Add(ColumnNames.LINK, typeof(string)); table.Columns.Add(ColumnNames.PARENT_VIEW, typeof(string)); table.Columns.Add(ColumnNames.CHILD_TYPE, typeof(string)); table.Columns.Add(ColumnNames.CHILD_TABLES, typeof(string)); try { IDbDriver driver = null; if (this.Context.CurrentRead != null) { driver = Epi.Data.DBReadExecute.GetDataDriver(this.Context.CurrentRead.File); } if (!string.IsNullOrEmpty(dbViewsOpt)) { driver = Epi.Data.DBReadExecute.GetDataDriver(dbViewsOpt); } List <string> tableNames = driver.GetTableNames(); int colCount; ///////////////////////////////// //ViewCollection Views = metadata.GetViews(); //////Views parent list //List<string> pViewsList = new List<string>(); //foreach (var view in Views) //{ // pViewsList.Add(metadata.GetAvailDataTableName(((Epi.View)(view)).Name)); //} //////Views list //List<string> ViewsList = new List<string>(); //foreach (var view in Views) //{ // ViewsList.Add(((Epi.View)(view)).Name); //} //////Code table list //List<string> CodeTableList = new List<string>(); //DataTable CodeTables = metadata.GetCodeTableList(); //foreach (DataRow CodeTable in CodeTables.Rows) //{ // CodeTableList.Add(((Epi.DataSets.TableSchema.TablesRow)(CodeTable)).TABLE_NAME); //} //////Data table list //List<string> DataTableList = new List<string>(); //DataTableList = metadata.GetDataTableList(); //////////////////////////////// foreach (string name in tableNames) { StringBuilder primaryKeys = new StringBuilder(); DataTable currentTable = driver.GetTableData(name); colCount = table.Columns.Count; DataRow row = table.NewRow(); row[ColumnNames.DATA_TABLE_NAME] = name; //issue 769 start //if (this.Context.CurrentRead != null) //{ // if (this.Context.CurrentProject != null && this.Context.CurrentProject.Views.Exists(this.Context.CurrentRead.Identifier)) // { // row[ColumnNames.TYPE] = "View"; // } // else // { // row[ColumnNames.TYPE] = "Data"; // } //} //else //{ // row[ColumnNames.TYPE] = "Data"; //} row[ColumnNames.TYPE] = GetTableTypeName(name, colCount); //issue 769 end row[ColumnNames.LINK] = string.Empty; row[ColumnNames.PARENT_VIEW] = string.Empty; row[ColumnNames.CHILD_TYPE] = string.Empty; row[ColumnNames.CHILD_TABLES] = string.Empty; table.Rows.Add(row); } } catch (NullReferenceException) { throw new GeneralException(SharedStrings.NO_DATA_SOURCE); } return(BuildMarkupFromTable(table, string.Empty)); }
/// <summary> /// GetVariableMarkup gets both the markup used in the HTMLRESULTS section and a DataTable /// with a row for each DBVARIABLE and its properties. /// </summary> /// <param name="table">An instance of a DataTable containing properties of DBVARIABLES.</param> /// <returns>Returns the markup used in the HTMLRESULTS section.</returns> private string GetVariableMarkup(out DataTable table) { StringBuilder sb = new StringBuilder(); string[] varNames = null; table = new DataTable(); if (!string.IsNullOrEmpty(this.identifierList)) { varNames = this.identifierList.Split(' '); foreach (string s in varNames) { s.Trim(); } } VariableCollection vars = this.GetVariables(varNames, this.dbVariablesOpt); this.Context.GetOutput(); /* * table.Columns.Add(new DataColumn(ColumnNames.VARIABLE, typeof(string))); * table.Columns.Add(new DataColumn(ColumnNames.TABLE, typeof(string))); * table.Columns.Add(new DataColumn(ColumnNames.FIELDTYPE, typeof(string))); * table.Columns.Add(new DataColumn(ColumnNames.FORMATVALUE, typeof(string))); * table.Columns.Add(new DataColumn(ColumnNames.SPECIALINFO, typeof(string))); * table.Columns.Add(new DataColumn(ColumnNames.PROMPT, typeof(string))); */ table.Columns.Add(new DataColumn(ColumnNames.PAGE_NUMBER, typeof(string))); table.Columns.Add(new DataColumn(ColumnNames.PROMPT, typeof(string))); table.Columns.Add(new DataColumn(ColumnNames.FIELDTYPE, typeof(string))); table.Columns.Add(new DataColumn(ColumnNames.VARIABLE, typeof(string))); table.Columns.Add(new DataColumn(ColumnNames.VARIABLE_VALUE, typeof(string))); table.Columns.Add(new DataColumn(ColumnNames.FORMATVALUE, typeof(string))); table.Columns.Add(new DataColumn(ColumnNames.SPECIALINFO, typeof(string))); table.Columns.Add(new DataColumn(ColumnNames.TABLE, typeof(string))); string tableText = string.Empty; string pattern = string.Empty; IDbDriver driver = null; DataTable viewTable = null; DataRow[] rows = null; Dictionary <string, string> formatStrings = new Dictionary <string, string>(); if (this.Context.CurrentRead != null) { tableText = this.Context.CurrentRead.Identifier; driver = Epi.Data.DBReadExecute.GetDataDriver(this.Context.CurrentRead.File); List <string> tableNames = driver.GetTableNames(); string viewTableName = "view" + tableText; List <string> tableNamesUpper = new List <string> { }; foreach (string name in tableNames) { tableNamesUpper.Add(name.ToUpperInvariant()); } //if TableNamesUpper contains an Epi 3 viewTable then get that table's data if (tableNamesUpper.Contains(viewTableName.ToUpperInvariant())) { viewTable = driver.GetTableData(viewTableName); if (varNames == null) { rows = viewTable.Select(); } else { StringBuilder filter = new StringBuilder(); foreach (string name in varNames) { filter.Append(string.Format(" OR Name = '{0}'", name)); } rows = viewTable.Select(filter.ToString().Substring(4)); } foreach (DataRow row in rows) { formatStrings.Add(row[ColumnNames.NAME].ToString(), row[ColumnNames.FORMATSTRING].ToString()); } } } List <string> RelatedTableList = new List <string>(); if (this.Context.CurrentRead != null) { for (int i = 0; Context.CurrentRead.RelatedTables.Count > i; i++) { RelatedTableList.Add(Context.CurrentRead.RelatedTables[i]); } } List <string> varnamelist = new List <string>(); if (varNames != null) { foreach (string name in varNames) { varnamelist.Add(name); } } //foreach (IVariable var in vars) foreach (DataColumn dataColumn in this.Context.DataSet.Tables["output"].Columns) { string ColumnsNames = ""; tableText = ""; if (this.Context.CurrentRead != null) { foreach (var RTable in RelatedTableList) { if (this.Context.CurrentRead.IsEpi7ProjectRead && this.Context.CurrentProject.Views.Exists(RTable)) { View tempView = this.Context.CurrentProject.Metadata.GetViewByFullName(RTable); ColumnsNames = this.Context.CurrentProject.Metadata.GetTableColumnNames(tempView.Id); if (ColumnsNames.Contains(dataColumn.ToString())) { tableText = RTable; break; } } } if (string.IsNullOrEmpty(tableText)) { tableText = this.Context.CurrentRead.Identifier; } } else { tableText = "output"; } if (varNames != null) { if (varnamelist.Contains(dataColumn.Caption.ToString().ToUpperInvariant())) { table.Rows.Add(GetDataTable(dataColumn, tableText, pattern, formatStrings, rows, table)); } } else if (vars != null) { if (vars.Contains(dataColumn.Caption.ToString().ToUpperInvariant())) { if (this.dbVariablesOpt == "FIELDVAR") { IVariable var = (IVariable)this.Context.GetVariable(dataColumn.ColumnName); if (var.VarType == VariableType.DataSource || var.VarType == VariableType.DataSourceRedefined) { table.Rows.Add(GetDataTable(dataColumn, tableText, pattern, formatStrings, rows, table)); } } else { table.Rows.Add(GetDataTable(dataColumn, tableText, pattern, formatStrings, rows, table)); } } } else { if (this.dbVariablesOpt == "FIELDVAR") { IVariable var = (IVariable)this.Context.GetVariable(dataColumn.ColumnName); if (var.VarType == VariableType.DataSource || var.VarType == VariableType.DataSourceRedefined) { table.Rows.Add(GetDataTable(dataColumn, tableText, pattern, formatStrings, rows, table)); } } else { table.Rows.Add(GetDataTable(dataColumn, tableText, pattern, formatStrings, rows, table)); } } //pattern = string.Empty; //IVariable var = (IVariable)this.Context.GetVariable(dataColumn.ColumnName); //if (var != null && (var.VarType == VariableType.DataSource) || (var.VarType == VariableType.DataSourceRedefined)) //{ // formatStrings.TryGetValue(var.Name, out pattern); //} //else //{ // tableText = "Defined"; //} //DataRow row = table.NewRow(); /* * row[ColumnNames.VARIABLE] = var.Name; * row[ColumnNames.TABLE] = tableText; * row[ColumnNames.FIELDTYPE] = var.DataType.ToString(); * row[ColumnNames.FORMATVALUE] = pattern; * row[ColumnNames.SPECIALINFO] = var.VarType.ToString(); * row[ColumnNames.PROMPT] = var.PromptText; */ // row[ColumnNames.PAGE_NUMBER] = var.???; //if (this.Context.CurrentRead.IsEpi7ProjectRead && this.Context.CurrentProject.Views.Exists(this.Context.CurrentRead.Identifier) && this.Context.CurrentProject.Views[this.Context.CurrentRead.Identifier].Fields.Exists(var.Name)) //{ // Epi.Fields.Field field = this.Context.CurrentProject.Views[this.Context.CurrentRead.Identifier].Fields[var.Name]; // if (field is FieldWithSeparatePrompt) // { // row[ColumnNames.PROMPT] = ((FieldWithSeparatePrompt)field).PromptText; // } // else // { // row[ColumnNames.PROMPT] = var.PromptText; // } //} //else //{ // row[ColumnNames.PROMPT] = var.PromptText; //} //if (this.Context.DataSet.Tables.Contains("output")) //{ // row[ColumnNames.FIELDTYPE] = this.Context.DataSet.Tables["output"].Columns[var.Name].DataType.ToString(); //} //else //{ // row[ColumnNames.FIELDTYPE] = var.DataType.ToString(); //} //row[ColumnNames.VARIABLE] = var.Name; ////row[ColumnNames.VARIABLE_VALUE] = var.???; //row[ColumnNames.FORMATVALUE] = pattern; //row[ColumnNames.SPECIALINFO] = var.VarType.ToString(); //row[ColumnNames.TABLE] = tableText; //table.Rows.Add(row); } return(BuildMarkupFromTable(table, string.Format("{0} ASC, {1} ASC", ColumnNames.TABLE, ColumnNames.VARIABLE))); }