public static int GetTableCount(string FilePath) { int tablecount = 0; FileStream stream = File.Open(FilePath, FileMode.Open, FileAccess.Read); IExcelDataReader excelreader = ExcelReaderFactory.CreateReader(stream); ExcelSheet = excelreader.AsDataSet(new ExcelDataSetConfiguration() { UseColumnDataType = true, ConfigureDataTable = (tablereader) => new ExcelDataTableConfiguration() { EmptyColumnNamePrefix = "Colume", UseHeaderRow = true, } }); DataTableCollection table = ExcelSheet.Tables; if (table.Contains("Conditional Execute")) { tablecount = ExcelSheet.Tables.Count - 2; } else if (table.Contains("Keyword Data")) { tablecount = ExcelSheet.Tables.Count - 1; } else { tablecount = ExcelSheet.Tables.Count; } excelreader.Close(); return(tablecount); }
public Boolean Contains(FeatureDataTable item) { if (item == null) { throw new ArgumentNullException("item"); } return(_tables.Contains(item.TableName)); }
public void Contains() { DataTableCollection tbcol = _dataset[0].Tables; tbcol.Clear(); /* _tables is array of DataTables defined in Setup */ tbcol.AddRange(_tables); string tblname = ""; /* checking for a recently input table, expecting true */ Assert.Equal(true, tbcol.Contains(_tables[0].TableName)); /* trying to check with a empty string, expecting false */ Assert.Equal(false, tbcol.Contains(tblname)); /* trying to check for a table that donot exist, expecting false */ Assert.Equal(false, tbcol.Contains("InvalidTableName")); }
private void CheckDataSource(object source) { if (source is IList || source is IListSource || source is IBindingList) { //DataTable this.dataSource = source; DataTable table = this.dataSource as DataTable; if (table != null) { this.dataMember = table.TableName; return; } //DataSet DataSet dataSet = this.dataSource as DataSet; if (dataSet != null) { if (dataSet.Tables.Count > 0) { DataTable tbl; if (String.IsNullOrEmpty(this.dataMember)) { tbl = dataSet.Tables[0]; } else { DataTableCollection tcol = dataSet.Tables; if (tcol.Contains(this.dataMember)) { tbl = tcol[this.dataMember]; this.dataSource = tbl; } } } else { throw new MissingDataSourceException(); } return; } //IList IList list = source as IList; if (list != null) { this.dataSource = list; this.dataMember = source.ToString(); if (list.Count == 0) { throw new MissingDataSourceException(); } return; } } else { throw new MissingDataSourceException(); } }
private static UnformattedExportSettings GetSettings(DataTableCollection tables) { if (!tables.Contains(SettingsTableName)) { return(null); } var settingsDataTable = tables[SettingsTableName]; return(new UnformattedExportSettings(settingsDataTable)); }
public static void AddOrMerge(this DataTableCollection tables, DataTable dt) { if (tables.Contains(dt.TableName)) { tables[dt.TableName].Merge(dt); } else { tables.Add(dt); } }
public IContent WritePage(ISource source, IPageData pageData, OutputData outputData) { TkDebug.AssertArgumentNull(outputData, "outputData", this); PageMakerUtil.AssertType(source, outputData, SourceOutputType.XmlReader, SourceOutputType.DataSet); if (outputData.OutputType == SourceOutputType.DataSet) { DataSet ds = PageMakerUtil.GetObject <DataSet>(outputData); DataTableCollection tables = ds.Tables; foreach (string tableName in fRemoveTables) { if (tables.Contains(tableName)) { tables.Remove(tableName); } } foreach (var mapping in fTableMappings) { if (tables.Contains(mapping.Key)) { DataTable table = tables[mapping.Key]; DataColumnCollection columns = table.Columns; foreach (string field in mapping.Value) { if (columns.Contains(field)) { columns.Remove(field); } } } } } using (XmlReader reader = PageMakerUtil.GetDataSetReader(outputData)) { string xml = XmlUtil.GetJson(reader, Result); return(new SimpleContent(ContentTypeConst.JSON, xml)); } }
public DataTable CreateVirtualTable(bool useAllFields = false) { DataTableCollection tables = HostDataSet.Tables; if (!tables.Contains(TableName)) { DataTable table = DataSetUtil.CreateDataTable(TableName, useAllFields ? fScheme.AllFields : fScheme.Fields); tables.Add(table); return(table); } return(tables[TableName]); }
private void DoPerTableRow(DataTableCollection tables, string table, Action <DataTable, DataRow> act) { if (tables.Contains(table)) { var dataTable = tables[table]; var rows = dataTable.Rows.Cast <DataRow>().ToList(); foreach (var row in rows) { act(dataTable, row); } } }
// <Snippet1> private void RemoveTables() { // Set the name of the table to test for and remove. string name = "Suppliers"; // Presuming a DataGrid is displaying more than one table, get its DataSet. DataSet thisDataSet = (DataSet)DataGrid1.DataSource; DataTableCollection tablesCol = thisDataSet.Tables; if (tablesCol.Contains(name) && tablesCol.CanRemove(tablesCol[name])) { tablesCol.Remove(name); } }
/// <summary> /// Get the specified table if exist. Return null if the table name doesn't exist. /// </summary> /// <param name="tables"></param> /// <param name="tableName">The name of the table.</param> /// <returns></returns> public static DataTable GetTable(this DataTableCollection tables, string tableName) { if (tables.Contains(tableName)) { foreach (DataTable t in tables) { if (t.TableName == tableName) { return(t); } } } return(null); }
// <Snippet1> private void GetIndexes() { // Get the DataSet of a DataGrid. DataSet thisDataSet = (DataSet)DataGrid1.DataSource; // Get the DataTableCollection through the Tables property. DataTableCollection tables = thisDataSet.Tables; // Get the index of the table named "Authors", if it exists. if (tables.Contains("Authors")) { System.Diagnostics.Debug.WriteLine(tables.IndexOf("Authors")); } }
// <Snippet1> private void TestForTableName() { // Get the DataSet of a DataGrid. DataSet thisDataSet = (DataSet)DataGrid1.DataSource; // Get the DataTableCollection through the Tables property. DataTableCollection tablesCol = thisDataSet.Tables; // Check if the named table exists. if (tablesCol.Contains("Suppliers")) { Console.WriteLine("Table named Suppliers exists"); } }
private void ProcessInstructionsSheet(IXlsxDocumentBuilder document, DataTableCollection tables) { if (!tables.Contains(InstructionsTableName)) { return; } var instructionsDataTable = tables[InstructionsTableName]; var instructionsSheetBuilder = new SqadXlsxUnformattedViewInstructionsSheetBuilder(); document.AppendSheet(instructionsSheetBuilder); AppendColumnsAndRows(instructionsSheetBuilder, instructionsDataTable); }
private static void AddInfoToDataSet(DataSet data, IUserInfo info, string source, bool isModule, Guid guid, string tkx, string sessionId) { DataTable infoTable = DataSetUtil.CreateDataTable(INFO_TABLE_NAME, INFO_ARRAY); DataTableCollection tables = data.Tables; if (!tables.Contains(infoTable.TableName)) { DataRow row = infoTable.NewRow(); DataSetUtil.SetRowValues(row, INFO_ARRAY, info.UserId, info.MainOrgId, source, isModule ? 1 : 0, 0, guid, tkx, sessionId); infoTable.Rows.Add(row); tables.Add(infoTable); } }
private void button1_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.InitialDirectory = "c:\\"; openFileDialog1.Filter = "xml files (*.xml)|*.xml"; openFileDialog1.FilterIndex = 2; openFileDialog1.RestoreDirectory = true; if (openFileDialog1.ShowDialog() == DialogResult.OK) { try { Debug.WriteLine(string.Format( "button1_Click -> file name {0}" , openFileDialog1.FileName)); string filePath = openFileDialog1.FileName; DataSet myDataSet = new DataSet(); myDataSet.ReadXml(filePath); DataTableCollection tables = myDataSet.Tables; if (tables.Contains("point")) { DataTable tb = tables["point"]; this.dgvImportedPoints.Rows.Clear(); int i = 1; foreach (DataRow dr in tb.Rows) { Debug.WriteLine(string.Format( "button1_Click -> {0} {1} {2}" , dr[0].ToString(), dr[1].ToString(), dr[2].ToString())); string[] row1 = new string[] { i.ToString(), dr[0].ToString(), dr[2].ToString(), dr[1].ToString() }; this.dgvImportedPoints.Rows.Add(row1); i++; } } else { MessageBox.Show("选择文件中数据格式有误!"); } } catch (Exception ex) { MessageBox.Show("读取文件时发生意外错误: " + ex.Message); } } }
private static void AddUrlToDataSet(DataSet data, Uri retUrl, Uri selfUrl, Uri encodeSelfUrl) { DataTable urlTable = DataSetUtil.CreateDataTable(URL_TABLE_NAME, URL_ARRAY); DataTableCollection tables = data.Tables; if (!tables.Contains(urlTable.TableName)) { DataRow row = urlTable.NewRow(); string returl = GetUrlValue(retUrl); string selfurl = GetUrlValue(selfUrl); string encodeUrl = GetUrlValue(encodeSelfUrl); DataSetUtil.SetRowValues(row, URL_ARRAY, returl, selfurl, HttpUtility.UrlEncode(returl, Encoding.UTF8), HttpUtility.UrlEncode(encodeUrl, Encoding.UTF8)); urlTable.Rows.Add(row); tables.Add(urlTable); } }
private void ProcessDataSheet(IXlsxDocumentBuilder document, DataTableCollection tables) { if (!tables.Contains(_dataTableName)) { return; } var dataTable = tables[_dataTableName]; //note: dirty fix, remove dummy row for JSON deserialization dataTable.Rows.RemoveAt(0); var dataSheetBuilder = new SqadXlsxUnformattedViewDataSheetBuilder(_dataTableName); document.AppendSheet(dataSheetBuilder); AppendColumnsAndRows(dataSheetBuilder, dataTable); }
private void toolPart_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e) { string tableName = e.ClickedItem.Text; if (tableName == "All" || tableName == "Tất cả") { grid.DataSource = tablePart; toolPart.Text = tableName; if (lang == AvailableLanguage.Vietnamese) { grid.Columns[0].HeaderText = "Tùy chọn"; } } else { if (tables.Contains(tableName)) { grid.DataSource = tables[tableName]; switch (Language) { case AvailableLanguage.Vietnamese: for (int i = 0; i < grid.Columns.Count; i++) { grid.Columns[i].HeaderText = viGridHeader[i]; } toolPart.Text = "Mục: " + tableName; break; case AvailableLanguage.English: toolPart.Text = "Part: " + tableName; break; } } else { grid.DataMember = ""; } } setPermission(tableName); }
private void pmbtn_Click(object sender, System.EventArgs e) { int rowCnt, i; DataTable bookTable; DataRow row; string s1; if (isoTB.Text.Trim() == "") { return; } DataTableCollection tablesCol = bookdSet.Tables; if (tablesCol.Contains("book") && tablesCol.CanRemove(tablesCol["book"])) { tablesCol.Remove("book"); } if (isoTB.Text.Trim() == "0") { sqlComm.CommandText = "SELECT book.ID, book.书名, book.文种号, book.图书分类号, book.种次号, borrow.副本, borrow.借出时间, borrow.归还时间, borrow.续借次数, borrow.电话, borrow.Ecode AS ISO编号, borrow.中文姓名 FROM book INNER JOIN borrow ON book.文种号 = borrow.文种号 AND book.种次号 = borrow.种次号 AND book.图书分类号 = borrow.图书分类号 WHERE (borrow.Ecode = '" + isoTB.Text.Trim() + "') AND (borrow.实际归还时间 IS NULL) AND (归还时间<'" + System.DateTime.Now.ToString() + "') AND (borrow.中文姓名 = '" + nmTB.Text.Trim() + "')"; sqlDataAdap.SelectCommand = sqlComm; sqlDataAdap.Fill(bookdSet, "book"); bookDG.CaptionText = "查询人员:(" + isoTB.Text.Trim().ToUpper() + ")"; dv.Table = bookdSet.Tables["book"]; this.bookDG.DataSource = dv; return; } //sqlhrComm.CommandText="SELECT employees.ecode, employees.ecname, codeorgs.cdptname FROM employees INNER JOIN codeorgs ON employees.dept = codeorgs.dptno WHERE (employees.ecode = '"+isoTB.Text.Trim()+"')"; //sqlhrConn.Open(); //sqldr=sqlhrComm.ExecuteReader(); OracleComm.CommandText = "select v_sys_psn.psncode, v_sys_psn.psnname, v_sys_dept.first_deptname, v_sys_dept.second_deptname, v_sys_dept.third_deptname, v_sys_psn.mobile, v_sys_psn.officephone, v_sys_corp.UNITNAME from v_sys_psn LEFT OUTER JOIN V_SYS_DEPT ON v_sys_psn.pk_deptdoc = v_sys_dept.pk_fourtdept LEFT OUTER JOIN v_sys_corp ON v_sys_psn.PK_CORP=v_sys_corp.PK_CORP where v_sys_psn.psncode=N'" + isoTB.Text.Trim().PadLeft(5, '0') + "' ";//写好想执行的Sql语句 OracleConn.Open(); odr = OracleComm.ExecuteReader(); if (odr.Read()) { booktv.BeginUpdate(); booktv.Nodes.Clear(); TreeNode rootNode1 = new TreeNode("所借图书", 5, 5); booktv.Nodes.Add(rootNode1); TreeNode rootNode = new TreeNode("人员信息"); booktv.Nodes.Add(rootNode); s1 = odr.GetValue(1).ToString(); TreeNode tnBook1 = new TreeNode("姓名:" + odr.GetValue(1).ToString()); rootNode.Nodes.Add(tnBook1); TreeNode tnBook2 = new TreeNode("部门:" + odr.GetValue(7).ToString() + "-" + odr.GetValue(2).ToString() + "-" + odr.GetValue(3).ToString() + "-" + odr.GetValue(4).ToString()); rootNode.Nodes.Add(tnBook2); TreeNode tnBook3 = new TreeNode("电话:" + odr.GetValue(5).ToString() + " " + odr.GetValue(6).ToString()); rootNode.Nodes.Add(tnBook3); booktv.EndUpdate(); rootNode.Expand(); //sqldr.Close(); //sqlhrConn.Close(); odr.Close(); OracleConn.Close(); sqlComm.CommandText = "SELECT book.ID, book.书名, book.文种号, book.图书分类号, book.种次号, borrow.副本, borrow.借出时间, borrow.归还时间, borrow.续借次数, borrow.电话, borrow.Ecode AS ISO编号 FROM book INNER JOIN borrow ON book.文种号 = borrow.文种号 AND book.种次号 = borrow.种次号 AND book.图书分类号 = borrow.图书分类号 WHERE (borrow.Ecode = '" + isoTB.Text.Trim() + "') AND (borrow.实际归还时间 IS NULL) AND (归还时间<'" + System.DateTime.Now.ToString() + "')"; sqlDataAdap.SelectCommand = sqlComm; sqlDataAdap.Fill(bookdSet, "book"); bookDG.CaptionText = "查询人员:(" + isoTB.Text.Trim().ToUpper() + ")"; dv.Table = bookdSet.Tables["book"]; this.bookDG.DataSource = dv; } else { MessageBox.Show("没有该人员!"); odr.Close(); OracleConn.Close(); } }
public static DataTable GetTable(this DataTableCollection tables, string tblName) { return(tables != null && tables.Contains(tblName) ? tables[tblName] : null); }
/// <summary> /// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"/> contains a specific value. /// </summary> /// <returns> /// true if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. /// </returns> /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param> public bool Contains(FeatureDataTable item) { return(_dataTables.Contains(item.TableName, item.Namespace)); }
private void maturebtn_Click_1(object sender, System.EventArgs e) { int rowCnt, i; DataTable bookTable; DataRow row; string s1; DataTableCollection tablesCol = bookdSet.Tables; if (tablesCol.Contains("book") && tablesCol.CanRemove(tablesCol["book"])) { tablesCol.Remove("book"); } booktv.BeginUpdate(); booktv.Nodes.Clear(); booktv.EndUpdate(); sqlComm.CommandText = "SELECT book.ID, book.书名, book.文种号, book.图书分类号, book.种次号,borrow.副本, borrow.借出时间,borrow.归还时间,borrow.续借次数 ,borrow.电话, borrow.Ecode AS ISO编号, borrow.中文姓名 FROM book INNER JOIN borrow ON book.文种号 = borrow.文种号 AND book.种次号 = borrow.种次号 AND book.图书分类号 = borrow.图书分类号 WHERE (borrow.实际归还时间 IS NULL) AND (borrow.归还时间 < '" + System.DateTime.Now.ToString() + "') ORDER BY borrow.借出时间"; sqlDataAdap.SelectCommand = sqlComm; sqlDataAdap.Fill(bookdSet, "book"); bookDG.CaptionText = "查询所有未还图书"; dv.Table = bookdSet.Tables["book"]; dv.Table.Columns.Add("姓名"); dv.Table.Columns.Add("部门"); for (rowCnt = 0; rowCnt < dv.Table.Rows.Count; rowCnt++) { row = dv.Table.Rows[rowCnt]; s1 = row["ISO编号"].ToString().Trim(); if (s1 != "0") { //sqlhrComm.CommandText="SELECT employees.ecode, employees.ecname, codeorgs.cdptname FROM employees INNER JOIN codeorgs ON employees.dept = codeorgs.dptno WHERE (employees.ecode = '"+s1+"')"; //sqlhrConn.Open(); //sqldr=sqlhrComm.ExecuteReader(); //sqldr.Read(); //if(sqldr.HasRows) //{ // row["姓名"]=sqldr.GetValue(1).ToString(); // row["部门"]=sqldr.GetValue(2).ToString(); //} //sqlhrConn.Close(); //sqldr.Close(); OracleComm.CommandText = "select v_sys_psn.psncode, v_sys_psn.psnname, v_sys_dept.first_deptname, v_sys_dept.second_deptname, v_sys_dept.third_deptname, v_sys_psn.mobile, v_sys_psn.officephone, v_sys_corp.UNITNAME from v_sys_psn LEFT OUTER JOIN V_SYS_DEPT ON v_sys_psn.pk_deptdoc = v_sys_dept.pk_fourtdept LEFT OUTER JOIN v_sys_corp ON v_sys_psn.PK_CORP=v_sys_corp.PK_CORP where v_sys_psn.psncode=N'" + s1.PadLeft(5, '0') + "' ";//写好想执行的Sql语句 OracleConn.Open(); odr = OracleComm.ExecuteReader(); if (odr.HasRows) { odr.Read(); row["姓名"] = odr.GetValue(1).ToString(); row["部门"] = odr.GetValue(7).ToString() + "-" + odr.GetValue(2).ToString() + "-" + odr.GetValue(3).ToString() + "-" + odr.GetValue(4).ToString(); } odr.Close(); OracleConn.Close(); } } this.bookDG.DataSource = dv; }
private void bmbtn_Click(object sender, System.EventArgs e) { int rowCnt, i; DataTable bookTable; DataRow row; string s1; if (wzhTB.Text.Trim() == "" || tsflhTB.Text.Trim() == "" || zchTB.Text.Trim() == "") { return; } DataTableCollection tablesCol = bookdSet.Tables; if (tablesCol.Contains("book") && tablesCol.CanRemove(tablesCol["book"])) { tablesCol.Remove("book"); } sqlComm.CommandText = "SELECT ID, 书名, 第一责任者, 出版者, 借出书量, 借出次数, 馆藏量 FROM book WHERE (文种号 = N'" + wzhTB.Text.Trim().ToUpper() + "') AND (图书分类号 = N'" + tsflhTB.Text.Trim().ToUpper() + "') AND (种次号 = N'" + zchTB.Text.Trim().ToUpper() + "')"; sqlConn.Open(); sqldr = sqlComm.ExecuteReader(); if (sqldr.Read()) { booktv.BeginUpdate(); booktv.Nodes.Clear(); TreeNode rootNode = new TreeNode("图书信息"); booktv.Nodes.Add(rootNode); TreeNode tnBook1 = new TreeNode("书名:" + sqldr.GetValue(1).ToString()); rootNode.Nodes.Add(tnBook1); TreeNode tnBook2 = new TreeNode("第一责任者:" + sqldr.GetValue(2).ToString()); rootNode.Nodes.Add(tnBook2); TreeNode tnBook3 = new TreeNode("出版者:" + sqldr.GetValue(3).ToString()); rootNode.Nodes.Add(tnBook3); TreeNode tnBook4 = new TreeNode("借出书量:" + sqldr.GetValue(4).ToString() + " 借出次数:" + sqldr.GetValue(5).ToString() + " 馆藏量:" + sqldr.GetValue(6).ToString()); rootNode.Nodes.Add(tnBook4); booktv.EndUpdate(); rootNode.Expand(); sqldr.Close(); sqlConn.Close(); sqlComm.CommandText = "SELECT 借出时间, 归还时间,续借次数, 电话, Ecode AS ISO编号,副本,中文姓名 FROM borrow WHERE (文种号 = N'" + wzhTB.Text.Trim().ToUpper() + "') AND (图书分类号 = N'" + tsflhTB.Text.Trim().ToUpper() + "') AND (种次号 = N'" + zchTB.Text.Trim().ToUpper() + "') AND (实际归还时间 IS NULL) AND (归还时间<'" + System.DateTime.Now.ToString() + "')"; sqlDataAdap.SelectCommand = sqlComm; sqlDataAdap.Fill(bookdSet, "book"); bookDG.CaptionText = "查询图书:(" + wzhTB.Text.Trim().ToUpper() + " " + tsflhTB.Text.Trim().ToUpper() + " " + zchTB.Text.Trim().ToUpper() + ")"; dv.Table = bookdSet.Tables["book"]; dv.Table.Columns.Add("姓名"); dv.Table.Columns.Add("部门"); for (rowCnt = 0; rowCnt < dv.Table.Rows.Count; rowCnt++) { row = dv.Table.Rows[rowCnt]; s1 = row["ISO编号"].ToString().Trim(); if (s1 != "0") { //sqlhrComm.CommandText="SELECT employees.ecode, employees.ecname, codeorgs.cdptname FROM employees INNER JOIN codeorgs ON employees.dept = codeorgs.dptno WHERE (employees.ecode = '"+s1+"')"; //sqlhrConn.Open(); //sqldr=sqlhrComm.ExecuteReader(); //sqldr.Read(); //if(sqldr.HasRows) //{ // row["姓名"]=sqldr.GetValue(1).ToString(); // row["部门"]=sqldr.GetValue(2).ToString(); //} //sqlhrConn.Close(); //sqldr.Close(); OracleComm.CommandText = "select v_sys_psn.psncode, v_sys_psn.psnname, v_sys_dept.first_deptname, v_sys_dept.second_deptname, v_sys_dept.third_deptname, v_sys_psn.mobile, v_sys_psn.officephone, v_sys_corp.UNITNAME from v_sys_psn LEFT OUTER JOIN V_SYS_DEPT ON v_sys_psn.pk_deptdoc = v_sys_dept.pk_fourtdept LEFT OUTER JOIN v_sys_corp ON v_sys_psn.PK_CORP=v_sys_corp.PK_CORP where v_sys_psn.psncode=N'" + s1.PadLeft(5, '0') + "' ";//写好想执行的Sql语句 OracleConn.Open(); odr = OracleComm.ExecuteReader(); if (odr.HasRows) { odr.Read(); row["姓名"] = odr.GetValue(1).ToString(); row["部门"] = odr.GetValue(7).ToString() + "-" + odr.GetValue(2).ToString() + "-" + odr.GetValue(3).ToString() + "-" + odr.GetValue(4).ToString(); } odr.Close(); OracleConn.Close(); } } this.bookDG.DataSource = dv; } else { MessageBox.Show("没有该图书!"); sqlConn.Close(); } }
/// <summary> /// Search data source meta-data for a target. /// </summary> /// <param name="request">Search target.</param> /// <param name="cancellationToken">Cancellation token.</param> public virtual Task <string[]> Search(Target request, CancellationToken cancellationToken) { string target = request.target == "select metric" ? "" : request.target; // Attempt to parse an expression that has SQL SELECT syntax bool parseSelectExpression(string selectExpression, out string tableName, out string[] fieldNames, out string expression, out string sortField, out int topCount) { tableName = null; fieldNames = null; expression = null; sortField = null; topCount = 0; if (string.IsNullOrWhiteSpace(selectExpression)) { return(false); } // RegEx instance used to parse meta-data for target search queries using a reduced SQL SELECT statement syntax if (s_selectExpression is null) { s_selectExpression = new Regex(@"(SELECT\s+(TOP\s+(?<MaxRows>\d+)\s+)?(\s*(?<FieldName>\w+)(\s*,\s*(?<FieldName>\w+))*)?\s*FROM\s+(?<TableName>\w+)\s+WHERE\s+(?<Expression>.+)\s+ORDER\s+BY\s+(?<SortField>\w+))|(SELECT\s+(TOP\s+(?<MaxRows>\d+)\s+)?(\s*(?<FieldName>\w+)(\s*,\s*(?<FieldName>\w+))*)?\s*FROM\s+(?<TableName>\w+)\s+WHERE\s+(?<Expression>.+))|(SELECT\s+(TOP\s+(?<MaxRows>\d+)\s+)?(\s*(?<FieldName>\w+)(\s*,\s*(?<FieldName>\w+))*)?\s*FROM\s+(?<TableName>\w+))", RegexOptions.Compiled | RegexOptions.IgnoreCase); } Match match = s_selectExpression.Match(selectExpression.ReplaceControlCharacters()); if (!match.Success) { return(false); } tableName = match.Result("${TableName}").Trim(); fieldNames = match.Groups["FieldName"].Captures.Cast <Capture>().Select(capture => capture.Value).ToArray(); expression = match.Result("${Expression}").Trim(); sortField = match.Result("${SortField}").Trim(); string maxRows = match.Result("${MaxRows}").Trim(); if (string.IsNullOrEmpty(maxRows) || !int.TryParse(maxRows, out topCount)) { topCount = int.MaxValue; } return(true); } return(Task.Factory.StartNew(() => { return TargetCache <string[]> .GetOrAdd($"search!{target}", () => { if (!(request.target is null)) { // Attempt to parse search target as a SQL SELECT statement that will operate as a filter for in memory metadata (not a database query) if (parseSelectExpression(request.target.Trim(), out string tableName, out string[] fieldNames, out string expression, out string sortField, out int takeCount)) { DataTableCollection tables = Metadata.Tables; List <string> results = new List <string>(); if (tables.Contains(tableName)) { DataTable table = tables[tableName]; List <string> validFieldNames = new List <string>(); for (int i = 0; i < fieldNames?.Length; i++) { string fieldName = fieldNames[i].Trim(); if (table.Columns.Contains(fieldName)) { validFieldNames.Add(fieldName); } } fieldNames = validFieldNames.ToArray(); if (fieldNames.Length == 0) { fieldNames = table.Columns.Cast <DataColumn>().Select(column => column.ColumnName).ToArray(); } // If no filter expression or take count was specified, limit search target results - user can // still request larger results sets by specifying desired TOP count. if (takeCount == int.MaxValue && string.IsNullOrWhiteSpace(expression)) { takeCount = MaximumSearchTargetsPerRequest; } void executeSelect(IEnumerable <DataRow> queryOperation) { results.AddRange(queryOperation.Take(takeCount).Select(row => string.Join(",", fieldNames.Select(fieldName => row[fieldName].ToString())))); } if (string.IsNullOrWhiteSpace(expression)) { if (string.IsNullOrWhiteSpace(sortField)) { executeSelect(table.Select()); } else { if (Common.IsNumericType(table.Columns[sortField].DataType)) { decimal parseAsNumeric(DataRow row) { decimal.TryParse(row[sortField].ToString(), out decimal result); return result; } executeSelect(table.Select().OrderBy(parseAsNumeric)); } else { executeSelect(table.Select().OrderBy(row => row[sortField].ToString())); } } } else { executeSelect(table.Select(expression, sortField)); } foreach (DataRow row in table.Select(expression, sortField).Take(takeCount)) { results.Add(string.Join(",", fieldNames.Select(fieldName => row[fieldName].ToString()))); } } return results.ToArray(); } } // Non "SELECT" style expressions default to searches on ActiveMeasurements meta-data table return Metadata.Tables["ActiveMeasurements"].Select($"ID LIKE '{InstanceName}:%' AND PointTag LIKE '%{target}%'").Take(MaximumSearchTargetsPerRequest).Select(row => $"{row["PointTag"]}").ToArray(); }); }, cancellationToken));