private void Timer1_Tick(object sender, EventArgs e) { if (ServiceFacade.ServiceFacade.InServiceCall) { return; // avoid multiplexing service calls that could cause problems } if (InTimer_Tick) { return; } InTimer_Tick = true; string currentCid = CidCtl.Text; if (currentCid == PreviousCid) { InTimer_Tick = false; return; } PreviousCid = currentCid; string cid = CompoundId.Normalize(currentCid, MetaTable); MetaTable mt = CompoundId.GetRootMetaTableFromCid(cid, MetaTable); MoleculeMx mol = MoleculeUtil.SelectMoleculeForCid(cid, mt); QuickStructure.SetupAndRenderMolecule(mol); InTimer_Tick = false; return; }
/// <summary> /// Select a list of chime strings ChemicalStructure object for a compound id /// </summary> /// <param name="cid"></param> /// <param name="mt">MetaTable used to get root table to select structures from</param> /// <returns></returns> public static Dictionary <string, MoleculeMx> SelectMoleculesForCidList( List <string> cidList, MetaTable mt = null) { MetaColumn strMc = null; MoleculeMx cs; KeyValuePair <string, string> kvp; string mtName = null, keyColName, strColExpr, chimeString, cid; int li; if (cidList == null || cidList.Count == 0) { return(null); } cid = cidList[0]; mt = mt?.Root; bool isUcdb = (mt != null && mt.Root.IsUserDatabaseStructureTable); // user compound database if (!isUcdb) { cid = CompoundId.Normalize(cid, mt); mt = CompoundId.GetRootMetaTableFromCid(cid, mt); if (mt == null) { return(null); } if (MqlUtil.IsCartridgeMetaTable(mt)) { return(SelectChemicalStructuresForCorpIdList(cidList, mt)); } } // Do one at a time Dictionary <string, MoleculeMx> csDict = new Dictionary <string, MoleculeMx>(); foreach (string cid0 in cidList) { cs = SelectMoleculeForCid(cid0, mt); if (cs != null) { csDict[cid0] = cs; } } return(csDict); }
/// <summary> /// Get query to select all data. /// It consists of a single QueryTable with the CID and key table name /// This keeps the initial query sent to the client small which helps /// response time for users not on the same local network as the server. /// </summary> /// <param name="keyMtName"></param> /// <param name="cn"></param> /// <returns></returns> public static Query GetSelectAllDataQuery( string keyMtName, string cn) { MetaTable mt = MetaTableCollection.GetWithException(MetaTable.AllDataQueryTable); Query q = new Query(); QueryTable qt = new QueryTable(mt); q.AddQueryTable(qt); MetaTable keyMt = null; if (Lex.IsDefined(keyMtName)) { keyMt = MetaTableCollection.Get(keyMtName); } if (keyMt != null && keyMt.Root.IsUserDatabaseStructureTable) // if root metatable is user database then normalize based on key { keyMt = keyMt.Root; // be sure we have root cn = CompoundId.Normalize(cn, keyMt); } else { cn = CompoundId.Normalize(cn); keyMt = CompoundId.GetRootMetaTableFromCid(cn, keyMt); keyMt = keyMt.Root; // be sure we have root (may not be structure table) } if (keyMt == null) { throw new Exception("Failed to identify key MetaTable"); } q.KeyCriteria = q.KeyCriteriaDisplay = " = " + cn; QueryColumn qc = qt.GetQueryColumnByNameWithException("root_table"); qc.Criteria = qc.CriteriaDisplay = qc.MetaColumn.Name + " = " + keyMt.Name; return(q); }
/// <summary> /// Show related structures for supplied CID /// </summary> /// <param name="initialCid"></param> /// <param name="queryType"></param> /// <param name="excludeCurrentCompounds"></param> public void ShowInstance( string initialCid, string queryType, bool excludeCurrentCompounds) { try { InSetup = true; MetaTable mt = CompoundId.GetRootMetaTableFromCid(initialCid); // set title string extCid = CompoundId.Format(initialCid, mt); string txt = extCid + " and Related Structures"; if (mt != null) { txt = mt.KeyMetaColumn.Label + " " + txt; } Text = txt; RelatedStructuresControl.MoleculeControl.ClearMolecule(); RelatedStructuresControl.SetupCheckmarks(); CompoundIdControl.Text = initialCid; // set cid to trigger start of search and UI update on next tick Left = PopupPos; // position Top = PopupPos; PopupPos += 125; if (PopupPos > InitialPopupPos + (5 * 125)) { PopupPos = InitialPopupPos; } Show(); // show (not modal) BringToFront(); return; } catch (Exception ex) { ex = ex; } finally { InSetup = false; } }
/// <summary> /// Select a Molecule object for a compound id /// </summary> /// <param name="cid"></param> /// <param name="mt"></param> /// <returns></returns> public static MoleculeMx SelectMoleculeForCid( string cid, MetaTable mt = null) { MetaColumn strMc = null; string mtName = null, keyColName, strColExpr, chimeString; MoleculeMx cs; if (cid == null || cid == "") { return(null); } if (RestrictedDatabaseView.KeyIsRetricted(cid)) { return(null); } //if (mt != null) mtName = mt.Name; // debug bool isUcdb = (mt != null && mt.Root.IsUserDatabaseStructureTable); // user compound database if (isUcdb) // if root metatable is user database then normalize based on key { mt = mt.Root; // be sure we have root cid = CompoundId.Normalize(cid, mt); } else { cid = CompoundId.Normalize(cid, mt); cs = MoleculeCache.Get(cid); // see if in cache if (cs != null) { return(cs); } mt = CompoundId.GetRootMetaTableFromCid(cid, mt); if (mt != null && Lex.Eq(mt.Name, "corp_structure") && MetaTableCollection.Get("corp_structure2") != null) { mt = MetaTableCollection.Get("corp_structure2"); // hack to search both small & large mols for Corp database } } if (mt == null) { return(null); } strMc = mt.FirstStructureMetaColumn; //.getmt.GetMetaColumnByName("molstructure"); if (strMc == null) { return(null); } cid = CompoundId.NormalizeForDatabase(cid, mt); if (String.IsNullOrEmpty(cid)) { return(null); } // Call external method to select structure if (strMc.ColumnMap.StartsWith("InternalMethod", StringComparison.OrdinalIgnoreCase) || strMc.ColumnMap.StartsWith("PluginMethod", StringComparison.OrdinalIgnoreCase)) { // call external method to get structure List <MetaColumn> selectList = new List <MetaColumn>(); selectList.Add(mt.KeyMetaColumn); selectList.Add(strMc); object[] vo = new object[2]; vo[0] = cid; try { GenericMetaBroker.CallLateBindMethodToFillVo(vo, 1, mt, selectList); } catch (Exception ex) { return(null); } if (vo[1] is MoleculeMx) { cs = (MoleculeMx)vo[1]; } else if (vo[1] is string) { cs = MoleculeMx.MolStringToMoleculeMx((string)vo[1]); } else { cs = null; } if (!isUcdb) { MoleculeCache.AddMolecule(cid, cs); } return(cs); } // Normal case //if (HelmEnabled) // temp till server back //{ // cs = new MoleculeMx(); // MoleculeMx.SetMoleculeToTestHelmString(cid, cs); // return cs; //} string tableMap = mt.GetTableMapWithAliasAppendedIfNeeded(); // some SQL (e.g. Postgres) requires an alias for subqueries) strColExpr = strMc.ColumnMap; if (strColExpr == "") { strColExpr = strMc.Name; } if (MqlUtil.IsCartridgeMetaTable(mt)) // selecting from Direct cartridge { if (!Lex.Contains(tableMap, "chime(")) // if no chime expression { strColExpr = "chime(ctab)"; // then create one (gets clob) } strColExpr += ", chime(ctab)"; // add 2nd column that gets clob in case first just gets first 4000 characters } keyColName = mt.KeyMetaColumn.ColumnMap; if (keyColName == "") { keyColName = mt.KeyMetaColumn.Name; } DbType parmType = DbType.String; object cidObj = cid; if (mt.KeyMetaColumn.IsNumeric) { if (!Lex.IsInteger(cid)) { return(null); // if numeric col be sure cid is numeric also } parmType = DbType.Int64; cidObj = Int64.Parse(cid); } string sql = "select " + strColExpr + " " + "from " + tableMap + " " + "where " + keyColName + " = :0"; DbCommandMx drd = new DbCommandMx(); try { drd.PrepareParameterized(sql, parmType); drd.ExecuteReader(cidObj); if (!drd.Read() || drd.Rdr.IsDBNull(0)) { drd.Dispose(); return(null); } string molString = drd.GetString(0); drd.Dispose(); MoleculeMx.TrySetStructureFormatPrefix(ref molString, strMc.DataTransform); // add molString type if indicated by data transform cs = MoleculeMx.MolStringToMoleculeMx(molString); cs.StoreKeyValueInMolComments(strMc, cid); if (!isUcdb) { MoleculeCache.AddMolecule(cid, cs); } //if (MoleculeMx.HelmEnabled == true && Lex.IsInteger(cid)) // MoleculeMx.SetMoleculeToTestHelmString(cid, cs); return(cs); } catch (Exception ex) { // just log message & return; DebugLog.Message("SelectMoleculeForCid Exception, Cid: " + cid + ", table: " + mt.Name + "\n" + "sql: " + OracleMx.FormatSql(sql) + "\n" + DebugLog.FormatExceptionMessage(ex)); if (drd != null) { drd.Dispose(); } return(null); } }
/// <summary> /// Display any structure and related compounds for input string or /// Matching database contents /// </summary> /// <param name="inputString"></param> /// <param name="showRelatedCompounds"></param> public void ShowQuickSearchPopup( string inputString, bool updateRelatedCompounds) { string extCid = "", tok, tok2; MRUEdit clc = CommandLineControl; // be sure popup is properly positioned if (clc.FindForm() == SessionManager.Instance.ShellForm) // slightly different position for Shell form that other forms { Left = clc.Left; Top = clc.Bottom; } else { Point p = clc.PointToScreen(new Point(0, clc.Bottom)); // get screen coord for upper left corner of popup Point p2 = this.Parent.PointToClient(p); // convert screen coord back to relative Left = p2.X; // position below input control Top = p2.Y; } // See if input matches structure Molecule = null; if (StructurePopupEnabled && !String.IsNullOrEmpty(inputString)) { Cid = CompoundId.Normalize(inputString); extCid = CompoundId.Format(Cid); CidMt = CompoundId.GetRootMetaTableFromCid(Cid); Molecule = MoleculeUtil.SelectMoleculeForCid(Cid, CidMt); RelatedDataButton.Enabled = (CidMt != null && Lex.Eq(CidMt.Root.Name, MetaTable.PrimaryRootTable)); AllDataButtonStb.Enabled = QbUtil.IsMdbAssayDataViewAvailable(CidMt); } if (Molecule != null) { string txt = extCid; if (CidMt != null) { txt = CidMt.KeyMetaColumn.Label + " " + txt; } if (Lex.IsUndefined(Molecule.Id)) { Molecule.Id = txt; } if (SS.I.FindRelatedCpdsInQuickSearch) { txt += " and Related Structures"; } StructurePanel.Text = txt; RelatedStructuresControl.MoleculeControl.Molecule = Molecule; if (SS.I.FindRelatedCpdsInQuickSearch) { Width = InitialStructurePanelWidth; // assure correct width } else { Width = InitialStructurePanelWidthWithoutRelatedStructureOptions; RSM.ClearSearchStatus(); } if (!StructurePanel.Visible) // if structure not showing then set height to initial height { Height = InitialStructurePanelHeight; } StructurePanel.Location = new Point(0, 0); StructurePanel.Visible = true; //Size = StructurePanel.Size; ListControl.Visible = false; Visible = true; RenderId++; if (updateRelatedCompounds) { UpdateRelatedCidsDisplay(CidMt, Cid, Molecule, RenderId); } return; } // See if input matches database contents tree else if (ContentsPopupEnabled) { DoQuickSearchAndDisplayOfContentsTree(inputString); return; } HideQuickSearchPopup(); return; }
/// <summary> /// Handle UI operations during tick of timer /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Timer_Tick(object sender, EventArgs e) { if (ServiceFacade.ServiceFacade.InServiceCall) { return; // avoid multiplexing service calls that could cause problems } if (InTimer_Tick) { return; } InTimer_Tick = true; try { string txt = CompoundIdControl.Text; if (txt == PreviousInput) { return; } if (DateTime.Now.Subtract(LastCompoundIdControlKeyDownTime).TotalSeconds < .5) { // wait for a pause in typing before doing retrieve //SystemUtil.Beep(); // debug return; } PreviousInput = txt; MetaTable mt = CompoundId.GetRootMetaTableFromCid(txt); string cid = CompoundId.Normalize(txt, mt); string mtName = mt.Name; MoleculeMx queryStruct = MoleculeUtil.SelectMoleculeForCid(cid, mt); RSM.StartSearchAndRetrievalOfRelatedStructures(mtName, cid, queryStruct, StructureSearchTypes); //Text = "Structures related to " + txt; // set form header InSetup = true; // set structure without triggering another search RelatedStructuresControl.MoleculeControl.Molecule = queryStruct; InSetup = false; } catch (Exception ex) { ex = ex; } finally { InTimer_Tick = false; } #if false // code to handle either CID or structure input bool userDefinedStructure = Lex.Eq(CurrentInput, "User Defined"); string mtName = ""; if (!userDefinedStructure) { CidMt = CompoundId.GetRootTableFromCid(CurrentInput); mtName = CidMt.Name; Cid = CompoundId.Normalize(CurrentInput, CidMt); QueryStruct = MoleculeUtil.SelectChemicalStructureFromCid(Cid, CidMt); InSetup = true; Text = "Structures related to " + CurrentInput; ChemicalStructure.SetRendererStructure(SQuery, QueryStruct); InSetup = false; } else // structure directly entered { if (!StructureChanged) { InTimer_Tick = false; return; } Cid = SearchId.ToString(); CidMt = null; mtName = "UserDefined"; QueryStruct = new ChemicalStructure(StructureFormat.MolFile, SQuery.MolfileString); StructureChanged = false; } #endif }
/// <summary> /// Setup the form for display /// </summary> /// <param name="cid"></param> /// <param name="qm"></param> /// <returns></returns> bool SetupForm( string cid, QueryManager qm) { AssertMx.IsDefined(cid, "Compound Id (CorpId)"); SelectedCid = cid; PreviousCid = cid; RootTable = CompoundId.GetRootMetaTableFromCid(cid); Qm = null; // no query context SourceQuery = null; CurrentBaseQueryCidHitList = null; if (qm != null) // if querymanager defined then base the related data query on the "current" query { Qm = qm; // setup query context SourceQuery = qm.Query; RootTable = qm.Query.RootMetaTable; if (qm.Query != null && qm.Query.Mode == QueryMode.Browse) // if browsing current base query results then get that cid list { CurrentBaseQueryCidHitList = Qm.DataTableManager.GetMostCompleteResultsKeyList(); } } //else throw new Exception("Parameters not defined"); //if (Lex.IsUndefined(SelectedCid) && // (Qm == null || Qm.MoleculeGrid == null || Qm.MoleculeGrid.Helpers == null)) // return false; SetupCheckmarks(); // Current Cid //if (Qm != null) // SelectedCid = Qm.MoleculeGrid.Helpers.GetCidForSelectedCell(); SelectedCid = CompoundId.Format(SelectedCid); CidCtl.Text = SelectedCid; //CidCtl.Focus(); // Marked cid count MarkedCidsList = null; if (Qm?.MoleculeGrid != null) { CidList cl = Qm.MoleculeGrid.GetMarkedList(); if (cl != null) { MarkedCidsList = cl.ToStringList(); } } int selCnt = (MarkedCidsList != null ? MarkedCidsList.Count : 0); MarkedCidsCheckEdit.Text = "Selected compound Ids (" + FormatCidListForDisplay(MarkedCidsList) + ")"; MarkedCidsCheckEdit.Enabled = (selCnt > 0); if (selCnt == 0 && MarkedCidsCheckEdit.Checked) { CurrentCidCheckEdit.Checked = true; } // All Cid count int allCnt = (CurrentBaseQueryCidHitList != null ? CurrentBaseQueryCidHitList.Count : 0); AllCidsCheckEdit.Text = "All Ids in the current result set (" + FormatCidListForDisplay(CurrentBaseQueryCidHitList) + ")"; AllCidsCheckEdit.Enabled = (allCnt > 0); if (selCnt == 0 && AllCidsCheckEdit.Checked) { CurrentCidCheckEdit.Checked = true; } // Structure MoleculeMx cs = new MoleculeMx(); if (Lex.IsDefined(SelectedCid)) { cs = MoleculeUtil.SelectMoleculeForCid(SelectedCid); } QueryMolCtl.SetupAndRenderMolecule(cs); // MRU list RenderMruList(); return(true); }
/// <summary> /// Transform basic query to select all data for a compound number /// </summary> /// <param name="keyMt">Key metatable. If null then try to determine from key value</param> /// <param name="cn"></param> /// <returns></returns> public static Query TransformSelectAllDataQuery( Query originalQuery, QueryTable qt0, Query newQuery) { Query q2 = null; MetaTable mt; MetaColumn mc; QueryTable qt; QueryColumn qc; MetaTreeNode mtn, tn; qc = qt0.GetQueryColumnByNameWithException("root_table"); ParsedSingleCriteria psc = MqlUtil.ParseQueryColumnCriteria(qc); if (psc == null || Lex.IsUndefined(psc.Value)) { throw new UserQueryException("Root table not defined"); } string keyMtName = psc.Value; psc = MqlUtil.ParseSingleCriteria("cid " + originalQuery.KeyCriteria); if (psc == null || Lex.IsUndefined(psc.Value)) { throw new UserQueryException("Compound Id not defined"); } string cn = psc.Value; MetaTable keyMt = null; if (Lex.IsDefined(keyMtName)) { keyMt = MetaTableCollection.Get(keyMtName); } if (keyMt != null && keyMt.Root.IsUserDatabaseStructureTable) // if root metatable is user database then normalize based on key { keyMt = keyMt.Root; // be sure we have root cn = CompoundId.Normalize(cn, keyMt); } else { cn = CompoundId.Normalize(cn); keyMt = CompoundId.GetRootMetaTableFromCid(cn, keyMt); keyMt = keyMt.Root; // be sure we have root (may not be structure table) } if (keyMt == null) { throw new Exception("Failed to identify key MetaTable"); } string allTableName = keyMt.Name + "_AllData"; // see if specific all-data tree node mtn = MetaTree.GetNode(allTableName); if (mtn == null) // no special "_AllData" node, lookup in menu { foreach (MetaTreeNode parent in MetaTree.Nodes.Values) { foreach (MetaTreeNode child in parent.Nodes) { if (Lex.Eq(child.Target, keyMt.Name)) { mtn = parent; break; } } } IUserObjectTree iuot = InterfaceRefs.IUserObjectTree; if (mtn == null && keyMt.IsUserDatabaseStructureTable && iuot != null) // see if user structure table & db { int userObjId = UserObject.ParseObjectIdFromInternalName(keyMt.Name); string nodeItemId = "ANNOTATION_" + userObjId; MetaTreeNode childMtn = iuot.GetUserObjectNodeBytarget(nodeItemId); if (childMtn != null && childMtn.Parent.Type == MetaTreeNodeType.Database) { mtn = childMtn.Parent; } } } if (mtn == null) { return(null); } Query q = newQuery; for (int i1 = 0; i1 < mtn.Nodes.Count; i1++) { tn = (MetaTreeNode)mtn.Nodes[i1]; if (!tn.IsDataTableType) { continue; } mt = MetaTableCollection.Get(tn.Target); if (mt == null) { continue; } if (mt.Root.Name != keyMt.Name) { continue; // must have same root } if (mt.MultiPivot && !mt.UseSummarizedData && mt.SummarizedExists) { MetaTable mt2 = MetaTableCollection.Get(mt.Name + MetaTable.SummarySuffix); if (mt2 != null) { mt = mt2; } } //if (mt.RemapForRetrieval && mt.SummarizedExists) mt.UseSummarizedData = true; // get summarized multipivot data (not good, permanently changes the metatable) qt = new QueryTable(mt); // if (Lex.Eq(mt.Name, "all_star_pivoted") || Lex.Eq(mt.Name, "all_annotation_pivoted")) mt = mt // debug; if (qt.SelectedCount > 0) // be sure something is selected { q.AddQueryTable(qt); } } // See if a model query exists & use it or append to what we have already string fileName = ServicesDirs.ModelQueriesDir + @"\" + allTableName + ".qry"; if (!ServerFile.GetLastWriteTime(fileName).Equals(DateTime.MinValue)) // model query file exist? { try { string query2String = FileUtil.ReadFile(fileName); q2 = Query.Deserialize(query2String); q.MergeSubqueries(q2); // just use subquery } catch (Exception ex) { ex = ex; } } q.SetupQueryPagesAndViews(ResultsViewType.HtmlTable); // be sure we have a default page & HTML view // Set key criteria q.KeyCriteria = " = " + cn; // Review tables (debug) //int tCnt = q.Tables.Count; //string tls = q.TableListString; //q.Tables.RemoveRange(23, 1); //q.Tables.RemoveRange(27, q.Tables.Count - 27); //q.Tables.RemoveRange(1, 25); // Get list of any inaccessible tables & remove from query q.InaccessableData = CheckDataSourceAccessibility(q); if (q.InaccessableData != null) { foreach (string schema in q.InaccessableData.Keys) { foreach (string tName in q.InaccessableData[schema]) { qt = q.GetQueryTableByName(tName); if (qt != null && !qt.MetaTable.IsRootTable && q.Tables.Contains(qt)) { q.RemoveQueryTable(qt); } } } //ShowUnavailableDataMessage(q); q.InaccessableData = null; } UsageDao.LogEvent("QueryAllData", ""); //string mql = MqlUtil.ConvertQueryToMql(q); // debug return(q); }
/// <summary> /// See if a compound id exists /// </summary> /// <param name="cid"></param> /// <param name="mt">MetaTable to check in or if null check based on prefix</param> /// <returns></returns> public static bool Exists( string cid, MetaTable mt) { DbDataReader dr = null; MetaTable keyMt; object obj; bool result; string table, prefix, suffix, cid2; int number; if (cid == null || cid == "") { return(false); } if (RestrictedDatabaseView.KeyIsRetricted(cid)) { return(false); } if (mt != null && mt.Root.IsUserDatabaseStructureTable) // if root metatable is user database then normalize based on key { keyMt = mt.Root; // be sure we have root cid = CompoundId.Normalize(cid, keyMt); } else // from non-user database, get key table based on prefix { cid = CompoundId.Normalize(cid, mt); keyMt = CompoundId.GetRootMetaTableFromCid(cid, mt); if (keyMt != null && Lex.Eq(keyMt.Name, "corp_structure") && MetaTableCollection.Get("corp_structure2") != null) { keyMt = MetaTableCollection.Get("corp_structure2"); // hack to search both small & large mols for Corp database } } if (keyMt == null) { return(false); } if (cid.StartsWith("pbchm", StringComparison.OrdinalIgnoreCase)) { return(true); // hack for pubchem until full set of compound ids available in Oracle } cid = CompoundId.NormalizeForDatabase(cid, keyMt); // get form that will match database if (cid == null) { return(false); } string keyCol = keyMt.KeyMetaColumn.ColumnMap; if (keyCol == "") { keyCol = keyMt.KeyMetaColumn.Name; } string sql = "select " + keyCol + " from " + keyMt.GetTableMapWithAliasAppendedIfNeeded() + " where " + keyCol + " = :0"; DbCommandMx drd = new DbCommandMx(); try { drd.PrepareMultipleParameter(sql, 1); dr = drd.ExecuteReader(cid); result = drd.Read(); } catch (Exception ex) { // Don't log error since usually because of invalid format number // DebugLog.Message("CompoundIdUtil.Exists - SQL Error:\n" + sql + "\n" + ex.Message); drd.Dispose(); return(false); } if (result == true) { obj = dr.GetValue(0); cid2 = CompoundId.Normalize(obj.ToString()); // need to normalize if number // if (cid2 != CompoundId.Normalize(cid)) result=false; } dr.Close(); // need to close cursor drd.Dispose(); return(result); }