Example #1
0
        /// <summary>
        /// Get a simple comma separated list of allowed values for the column
        /// </summary>
        /// <param name="colname"></param>
        /// <returns></returns>

        static string GetListFromColCriteria(
            QueryTable qt,
            string colName)
        {
            string      list = "";
            QueryColumn qc   = qt.GetQueryColumnByName(colName);

            if (qc == null || Lex.IsNullOrEmpty(qc.Criteria))
            {
                return("");
            }
            ParsedSingleCriteria psc = MqlUtil.ParseSingleCriteria(qc.Criteria);

            if (psc.ValueList == null)
            {
                return("");
            }
            foreach (string s in psc.ValueList)
            {
                if (list != "")
                {
                    list += ", ";
                }
                list += s;
            }

            return(list);
        }
Example #2
0
/// <summary>
/// Add a query to the window list, make it current & render
/// </summary>
/// <param name="label"></param>
/// <param name="mql"></param>

        public static void AddQueryToWindowList(
            string label,
            string mql,
            bool convertToSimpleCriteria)
        {
            Query q = MqlUtil.ConvertMqlToQuery(mql);

            if (convertToSimpleCriteria)
            {
                MqlUtil.ConvertComplexCriteriaToQueryColumnCriteria(q, QueryLogicType.And);
            }
            q.UserObject.Name = label;

            int wi = QbUtil.GetQueryIndex(label);

            if (wi >= 0)             // replace existing query
            {
                Document mwt = (Document)QbUtil.DocumentList[wi];
                mwt.Type    = DocumentType.Query;
                mwt.Content = q;
                QbUtil.SelectQuery(wi);
            }

            else
            {
                QbUtil.AddQueryAndRender(q, false);              // new query
            }
        }
Example #3
0
        /// <summary>
        /// Add cid criteria to the derived query to get set of compounds desired
        /// </summary>
        /// <param name="q"></param>
        /// <param name="cidList"></param>

        void ModifyQueryForCidSearch(
            Query q,
            List <string> cidList)
        {
            QueryTable  qt    = q.Tables[0];
            QueryColumn keyQc = qt.KeyQueryColumn;

            ParsedSingleCriteria psc = new ParsedSingleCriteria();

            psc.QueryColumn = keyQc;

            if (cidList.Count == 1)
            {
                psc.Op    = "=";
                psc.Value = cidList[0];
            }

            else
            {
                psc.Op        = "in";
                psc.ValueList = cidList;
            }

            MqlUtil.ConvertParsedSingleCriteriaToQueryColumnCriteria(psc, keyQc, false);
            keyQc.CopyCriteriaToQueryKeyCritera(q);
            return;
        }
Example #4
0
/// <summary>
/// Build the query that is executed to retrieve the summarized target data and optional structure data
/// </summary>
/// <returns></returns>

        void BuildQuery(string title)
        {
            int qid = SS.I.ServicesIniFile.ReadInt("SpillTheBeansToolModelQuery", -1);

            if (qid < 0)
            {
                throw new Exception("SpillTheBeansToolModelQuery not defined");
            }

            Query q = QbUtil.ReadQuery(qid);

            if (q == null)
            {
                throw new Exception("Failed to read SpillTheBeansToolModelQuery: " + qid);
            }

            AssertMx.IsDefined(KeyQc?.Criteria, "KeyQc.Criteria");

            ParsedSingleCriteria psc = MqlUtil.ParseSingleCriteria(KeyQc?.Criteria);             // parse key criteria

            KeyQc.CopyCriteriaToQueryKeyCritera(q);
            Query = q;             // save for later use

            return;
        }
Example #5
0
        public void Setup(ColumnInfo colInfo)
        {
            bool check;

            InSetup = true;
            ColInfo = colInfo;                                                                    // save ref to colInfo

            ParsedSingleCriteria psc = MqlUtil.ParseSingleCriteria(ColInfo.Qc.SecondaryCriteria); // parse criteria

            if (psc == null)
            {
                StructureRenditor.MolfileString = "";
            }
            else
            {
                MoleculeMx cs = new MoleculeMx(MoleculeFormat.Chime, psc.Value);
                MoleculeMx.SetRendererStructure(StructureRenditor, cs);
            }

            Timer.Enabled    = true;
            StructureChanged = false;

            InSetup = false;
            return;
        }
Example #6
0
        public string GetTarget(string pdbUrl, string tableName, string pdbColumnName)
        {
            string target = null;

            string mql = "select primary_gene_name_alias from " + tableName + " where " + pdbColumnName + " = '" + pdbUrl + "'";

            Query query = MqlUtil.ConvertMqlToQuery(mql);

            query.SingleStepExecution = true;
            QueryEngine qe = new QueryEngine();

            qe.ExecuteQuery(query);

            object[] vo = qe.NextRow();

            if (vo != null)
            {
                if (vo[2] != null)
                {
                    target = vo[2].ToString();
                }
            }

            return(target);
        }
Example #7
0
/// <summary>
/// Get any existing target summary options from option column
/// </summary>
/// <param name="qt"></param>
/// <returns></returns>

        public static TargetSummaryOptions GetFromMdbAssayOptionsColumn(
            QueryTable qt)
        {
            TargetSummaryOptions tso = null;

            if (qt == null)
            {
                return(null);
            }
            QueryColumn qc = qt.GetQueryColumnByName(MultiDbAssayDataNames.MultiDbViewOptions);

            if (qc == null)
            {
                return(null);
            }

            ParsedSingleCriteria psc = MqlUtil.ParseSingleCriteria(qc.Criteria);

            if (psc == null)
            {
                return(null);
            }
            string tsoString = Lex.RemoveSingleQuotes(psc.Value);

            if (Lex.IsNullOrEmpty(tsoString))
            {
                return(null);
            }

            tso = TargetSummaryOptions.Deserialize(tsoString);
            return(tso);
        }
Example #8
0
        /// <summary>
        /// Get subset of query state information necessary to determine if alert needs to be reset
        /// </summary>
        /// <param name="q"></param>
        /// <returns></returns>
        ///
        public static string GetAlertQueryCriteria(
            Query q)
        {
            string state = MqlUtil.GetCriteriaString(q);             // just criteria for now since non-criteria tables are not checked

            if (state.Length > 2000)
            {
                state = state.Substring(0, 2000);                                  // limit size for persistance into UserObject.Description
            }
            return(state);
        }
Example #9
0
        public void Setup(ColumnInfo colInfo)
        {
            MobiusDataType mdtLow, mdtHigh;

            InSetup = true;

            ColInfo = colInfo;             // save ref to colInfo

            Stats = colInfo.Rfld.GetStats();
            ItemFilter.Properties.Minimum = 0;
            ItemFilter.Properties.Maximum = Stats.DistinctValueList.Count + 2 - 1;                // (All) on left, (Blanks) on right

            ParsedSingleCriteria psc = MqlUtil.ParseSingleCriteria(ColInfo.Qc.SecondaryCriteria); // parse criteria

            ItemFilter.Value = 0;
            ValueLabel.Text  = "(All)";
            if (psc != null && psc.OpEnum == CompareOp.Eq && Stats.DistinctValueList.Count > 0)
            {
                MetaColumnType type    = ColInfo.Mc.DataType;
                MobiusDataType lowVal  = MobiusDataType.New(type, psc.Value);
                MobiusDataType highVal = MobiusDataType.New(type, psc.Value);

                if (MetaColumn.IsDecimalMetaColumnType(type))
                {                 // adjust decimal comparison values by an epsilon
                    double e = MobiusDataType.GetEpsilon(Stats.MaxValue.FormattedText);
                    lowVal.NumericValue  -= e;
                    highVal.NumericValue += e;
                }

                for (int i1 = 0; i1 < Stats.DistinctValueList.Count; i1++)
                {
                    MobiusDataType mdt  = Stats.DistinctValueList[i1];
                    string         fTxt = mdt.FormattedText;

                    if (Lex.Eq(psc.Value, fTxt) ||
                        (mdt.CompareTo(lowVal) >= 0 && mdt.CompareTo(highVal) <= 0))
                    {
                        ItemFilter.Value = i1 + 1;
                        ValueLabel.Text  = Stats.DistinctValueList[i1].FormattedText;
                        break;
                    }
                }
            }

            else if (psc != null && psc.OpEnum == CompareOp.IsNull)             // (Blanks)
            {
                ItemFilter.Value = Stats.DistinctValueList.Count + 1;
                ValueLabel.Text  = "(Blanks)";
            }

            ItemFilter.Focus();
            InSetup = false;
            return;
        }
Example #10
0
        /// <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);
        }
Example #11
0
        /// <summary>
        /// Initialize subquery based on which columns are selected, have criteria, etc in the
        /// top-level qt
        /// and
        /// </summary>
        /// <param name="qt"></param>
        /// <returns></returns>

        Query InitializeSubQuery(
            QueryTable qt)
        {
            QueryColumn qc, qc2;

            Query q2 = GetUnderlyingTables(qt);             // initialize subquery

            foreach (QueryColumn qc0 in qt.QueryColumns)
            {
                if (qc0.IsKey)
                {
                    continue;
                }

                if (!qc0.Is_Selected_or_Criteria_or_GroupBy_or_Sorted)
                {
                    continue;
                }

                string colMap = qc0.MetaColumn.ColumnMap;
                if (Lex.IsUndefined(colMap))
                {
                    throw new Exception("ColumnMap not defined for: " + qc0.MetaTable.Name + "." + qc0.MetaColumnName);
                }

                List <MqlToken> toks = MqlUtil.ParseComplexCriteria(colMap, q2);

                for (int ti = 0; ti < toks.Count; ti++)
                {
                    MqlToken tok = toks[ti];
                    qc = tok.Qc;
                    if (qc != null)
                    {
                        qc.Selected = true;
                    }
                }
            }

            List <QueryTable> qtList2 = new List <QueryTable>();

            foreach (QueryTable qt0 in q2.Tables)
            {
                if (qt0.SelectedCount > 1)
                {
                    qtList2.Add(qt0);
                }
            }

            q2.Tables = qtList2;

            return(q2);
        }
Example #12
0
        /// <summary>
        /// Read a query & return with metatables embedded in the query for UserObject
        /// </summary>
        /// <param name="uo"></param>
        /// <returns>The requested user object or null if no matching user object is found.</returns>

        public static UserObject ReadQueryWithMetaTables(UserObject uo)
        {
            Query q, q2;

            uo = UserObjectDao.Read(uo);
            if (uo == null)
            {
                return(null);
            }

            // Sharing a query implicitly shares any underlying annotations, calc fields & lists.
            // Mark these objects as readable within the context of this query even if they are not shared.

            Permissions.AllowTemporaryPublicReadAccessToAllUserObjects = true;
            q = Query.Deserialize(uo.Content);

            foreach (QueryTable qt in q.Tables)
            {             // mark any saved lists in criteria as temporarily readable since the query is readable
                foreach (QueryColumn qc in qt.QueryColumns)
                {
                    if (qc.MetaColumn.DataType == MetaColumnType.CompoundId &&
                        Lex.Contains(qc.Criteria, "IN LIST"))
                    {
                        int    id;
                        string criteria          = qc.MetaColumn.Name + " " + qc.Criteria;
                        ParsedSingleCriteria psc = MqlUtil.ParseSingleCriteria(criteria);
                        if (psc == null)
                        {
                            continue;
                        }

                        psc.Value = Lex.RemoveAllQuotes(psc.Value);
                        if (Lex.IsUndefined(psc.Value))
                        {
                            continue;
                        }

                        if (UserObject.TryParseObjectIdFromInternalName(psc.Value, out id) && id > 0)
                        {
                            Permissions.TemporaryPublicReadAccessUserObjects[id] = null;
                        }
                    }
                }
            }

            Permissions.AllowTemporaryPublicReadAccessToAllUserObjects = false;

            uo.Content = q.Serialize(true);             // serialize with metatables
            return(uo);
        }
Example #13
0
/// <summary>
/// Get the MQL for a saved query
/// </summary>
/// <param name="queryId"></param>
/// <returns></returns>
///
        public static string GetSavedQueryMQL(
            int queryId, bool mobileQuery = false)
        {
            UserObject uo = UserObjectDao.Read(queryId);

            if (uo == null)
            {
                return(null);
            }
            Query  q   = Query.Deserialize(uo.Content);
            string mql = MqlUtil.ConvertQueryToMql(q, mobileQuery);            // to mql

            return(mql);
        }
Example #14
0
        void ChangeLogicType(QueryLogicType newType)
        {
            if (newType == Query.LogicType)
            {
                return;
            }

            if (Query.LogicType == QueryLogicType.Complex)             // turning off complex logic
            {
                string logicTypeString = "And";
                if (newType == QueryLogicType.Or)
                {
                    logicTypeString = "Or";
                }
                if (XtraMessageBox.Show(
                        "Switching from \"Advanced\" to \"" + logicTypeString + "\" logic may cause the loss of some criteria logic.\n" +
                        "Do you want to continue?",
                        UmlautMobius.String, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    != DialogResult.Yes)
                {                 // set back to advanced
                    CtUseComplexLogic.Checked = true;
                    return;
                }

                else                 // switching to And or Or logic
                {
                    if (newType == QueryLogicType.And)
                    {
                        MqlUtil.ConvertComplexCriteriaToQueryColumnCriteria(Query, QueryLogicType.And);
                    }

                    else
                    {
                        MqlUtil.ConvertComplexCriteriaToQueryColumnCriteria(Query, QueryLogicType.Or);
                    }
                }
            }

            else if (newType == QueryLogicType.Complex)             // turning on complex logic
            {
                MqlUtil.ConvertQueryColumnCriteriaToComplexCriteria(Query);
                Query.ClearAllQueryColumnCriteria();
            }

            Query.LogicType = newType;
            Render();
            return;
        }
Example #15
0
        public string GetXray2DensityMapUrl(string pdbUrl, string tableName, string pdbColumnName)
        {
            string mapUrl    = null;
            string mapColumn = null;

            if (pdbColumnName == "ALIGNED_SPLIT_COMPLEX_URL")
            {
                mapColumn = "ALIGNED_SPLIT_MAP_URL";
            }
            else if (pdbColumnName == "ALIGNED_FULL_COMPLEX_URL")
            {
                mapColumn = "ALIGNED_FULL_MAP_URL";
            }
            else if (pdbColumnName == "ORIGINAL_PDB_URL")
            {
                mapColumn = "ORIGINAL_MAP_URL";
            }

            if (mapColumn == null)
            {
                return(null);
            }

            string mql = "select " + mapColumn + " from " + tableName + " where " + pdbColumnName + " = '" + pdbUrl + "'";

            Query query = MqlUtil.ConvertMqlToQuery(mql);

            query.SingleStepExecution = true;
            QueryEngine qe = new QueryEngine();

            qe.ExecuteQuery(query);

            object[] vo = qe.NextRow();

            if (vo != null)
            {
                if (vo[2] != null)
                {
                    mapUrl = vo[2].ToString();
                }
            }
            return(mapUrl);
        }
Example #16
0
        /// <summary>
        /// Get the list of databases from any DbSet column in the underlying source table
        /// </summary>
        /// <returns></returns>

        List <string> GetDbSetList()
        {
            List <string> defaultDbList = new List <string>();

            defaultDbList.Add(SmallWorldPredefinedParameters.DefaultDatabase);             // initial database

            QueryColumn qc = Psc.QueryColumn;

            if (qc == null)
            {
                return(defaultDbList);
            }

            MetaTable mt = qc.MetaColumn.MetaTable;

            MetaColumn dbSetMc = mt.DatabaseListMetaColumn;

            if (dbSetMc == null)
            {
                return(defaultDbList);
            }

            QueryColumn dbSetQc = qc.QueryTable.GetQueryColumnByName(dbSetMc.Name);

            if (!Lex.IsDefined(dbSetQc.Criteria))
            {
                return(defaultDbList);
            }

            ParsedSingleCriteria sc = MqlUtil.ParseQueryColumnCriteria(dbSetQc);

            if (sc != null)
            {
                return(sc.ValueList);
            }

            else             // some problem with criteria
            {
                return(defaultDbList);
            }
        }
Example #17
0
        /// <summary>
        /// Dialog to make multiple dictionary selections from checked list dialog box
        /// </summary>
        /// <param name="dictionaryName"></param>
        /// <param name="selections"></param>
        /// <param name="prompt"></param>
        /// <returns></returns>

        public static string GetCheckedListBoxDialog(
            string dictionaryName,
            string selections,
            string prompt)
        {
            MetaTable  mt = new MetaTable();            // create dummy table
            MetaColumn mc = mt.AddMetaColumn(dictionaryName, prompt, MetaColumnType.String);

            mc.Dictionary = dictionaryName;

            //if (selections.Contains(","))  { ... } (still have problem for single item)

            // split and reformat to properly handle unquoted items with spaces in them, e.g. "big cat, little dog"

            List <string> items = Csv.SplitCsvString(selections, false);

            selections = Csv.JoinCsvString(items);

            QueryTable  qt = new QueryTable(mt);
            QueryColumn qc = qt.QueryColumns[0];

            qc.Criteria = mc.Name + " in (" + selections + ")";
            bool success = CriteriaDictMultSelect.Edit(qc);

            if (!success)
            {
                return(null);
            }

            ParsedSingleCriteria psc = MqlUtil.ParseQueryColumnCriteria(qc);

            if (psc == null || psc.ValueList == null)
            {
                selections = "";
            }
            else
            {
                selections = MqlUtil.FormatValueListString(psc.ValueList, false);
            }
            return(selections);
        }
Example #18
0
        private void StructureSearch_Click(object sender, EventArgs e)
        {
            QueryColumn qc = new QueryColumn();
            MetaColumn  mc = new MetaColumn();            // create minimal metacolumn with structure type to assoc with qc

            mc.DataType   = MetaColumnType.Structure;
            qc.MetaColumn = mc;

            bool gotCriteria = CriteriaStructure.Edit(qc);

            if (!gotCriteria || qc.Criteria == "")
            {
                return;
            }
            string sid = "";

            for (int si = 1; ; si++)
            {
                sid = "S" + si.ToString();
                if (!LabeledCriteria.Structures.ContainsKey(sid.ToUpper()))
                {
                    break;
                }
            }

            string chime = MoleculeMx.MolfileStringToChimeString(qc.MolString); // get chime string

            LabeledCriteria.Structures[sid.ToUpper()] = chime;                  // store sid & associated chime string
            qc.MolString = chime;
            string sCriteria = MqlUtil.ConvertQueryColumnStructureCriteriaToMql(qc);

            sCriteria = sCriteria.Replace("(ctab,", "(structure_field,");         // required dummy field name
            sCriteria = sCriteria.Replace(chime, "[Edit Structure " + sid + "]"); // substitute surrogate for structure
            sCriteria = sCriteria.Replace("'[", "[");                             // hack fixup
            sCriteria = sCriteria.Replace("]'", "]");

            Instance.InsertCriteria(sCriteria);
        }
Example #19
0
        public string GetXray1DensityMapUrl(string pdbUrl, string tableName)
        {
            string mapUrl = null;
            string mql    = "select bsl_xray_edensity_url from " + tableName + " where BSL_XRAY_CMPLX_URL = '" + pdbUrl + "'";

            Query query = MqlUtil.ConvertMqlToQuery(mql);

            query.SingleStepExecution = true;
            QueryEngine qe = new QueryEngine();

            qe.ExecuteQuery(query);

            object[] vo = qe.NextRow();

            if (vo != null)
            {
                if (vo[2] != null)
                {
                    mapUrl = vo[2].ToString();
                }
            }
            return(mapUrl);
        }
Example #20
0
        string FormatCidListForDisplay(List <string> cidList)
        {
            string      txt;
            QueryColumn qc = null;

            int count = 0;

            if (cidList != null && cidList.Count > 0)
            {
                count = cidList.Count;
            }
            if (count > 0 && SourceQuery.Tables.Count > 0 && SourceQuery.Tables[0].KeyQueryColumn.MetaColumn.DataType == MetaColumnType.CompoundId)
            {
                qc = SourceQuery.Tables[0].KeyQueryColumn;
                string cidListString = MqlUtil.FormatValueListString(cidList, false);
                txt = CidList.FormatAbbreviatedCidListForDisplay(qc, cidListString);
                return(txt);
            }

            else
            {
                return(count.ToString());
            }
        }
Example #21
0
        /// <summary>
        /// Color criteria to highlight keywords, column names, constants, etc.
        /// </summary>
        /// <param name="criteria"></param>
        /// <param name="q"></param>
        /// <returns></returns>

        public static RichTextBox ColorCodeCriteria(
            string criteria,
            Query q)
        {
            bool inEditStructure = false;
            int  i1;

            RichTextBox rtb = new RichTextBox();

            rtb.Text            = criteria;
            rtb.SelectionStart  = 0;
            rtb.SelectionLength = rtb.Text.Length;
            rtb.SelectionFont   = new Font("Courier New", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);

            PositionedToken lastTok = null;
            Lex             lex     = new Lex();

            lex.SetDelimiters(" , ; ( ) < = > <= >= <> != !> !< [ ]");
            lex.OpenString(criteria);
            while (true)
            {
                PositionedToken tok = lex.GetPositionedToken();
                if (tok == null)
                {
                    break;
                }

                if (MqlUtil.IsKeyWord(tok.Text))
                {
                    rtb.SelectionStart  = tok.Position;
                    rtb.SelectionLength = tok.Text.Length;
                    rtb.SelectionColor  = Color.Blue;
                    continue;
                }

                QueryColumn qc = MqlUtil.GetQueryColumn(tok.Text, q);
                if (qc != null)
                {                 // labeled field name
                    rtb.SelectionStart  = tok.Position;
                    rtb.SelectionLength = tok.Text.Length;
                    rtb.SelectionColor  = Color.Cyan;
                    continue;
                }

                if (tok.Text.StartsWith("/*"))
                {                 // comment
                    rtb.SelectionStart  = tok.Position;
                    rtb.SelectionLength = tok.Text.Length;
                    rtb.SelectionColor  = Color.Green;
                    continue;
                }

                if (tok.Text.StartsWith("'") || Lex.IsDouble(tok.Text))
                {                 // constant
                    rtb.SelectionStart  = tok.Position;
                    rtb.SelectionLength = tok.Text.Length;
                    rtb.SelectionColor  = Color.Red;
                    continue;
                }

                if (tok.Text == "[")
                {
                    inEditStructure = true;          // color structure placeholder tokens
                }
                if (inEditStructure)                 // color the tokens in edit structure
                {
                    rtb.SelectionStart  = tok.Position;
                    rtb.SelectionLength = tok.Text.Length;
                    rtb.SelectionColor  = Color.Red;
                    if (tok.Text == "]")
                    {
                        inEditStructure = false;
                    }
                    continue;
                }
            }

            return(rtb);
        }
Example #22
0
        /// <summary>
        /// Translate a labeled column reference to a normal named reference
        /// </summary>
        /// <param name="pTok"></param>
        /// <returns></returns>

        static string TranslateLabeledColumnName(
            PositionedToken pTok,
            Query q,
            RichTextBox complexCriteriaCtl)
        {
            QueryColumn qc = null;
            int         qti, qci;

            string tok = pTok.Text;

            tok = Lex.RemoveDoubleQuotes(tok);
            string tName, cName;

            MqlUtil.ParseColumnIdentifier(tok, out tName, out cName);

            QueryTable qt = q.Tables[0];             // default to first table

            if (tName != "")
            {
                for (qti = 0; qti < q.Tables.Count; qti++)
                {
                    qt = q.Tables[qti];
                    if (Lex.Eq(qt.Alias, tName))
                    {
                        break;
                    }
                }
                if (qti >= q.Tables.Count)
                {
                    ConvertLabeledCriteriaError("Invalid table name or alias", pTok, complexCriteriaCtl);
                }
            }

            for (qci = 0; qci < qt.QueryColumns.Count; qci++)
            {
                qc = qt.QueryColumns[qci];
                if (qc.MetaColumn == null)
                {
                    continue;
                }
                if (!qc.MetaColumn.IsSearchable)
                {
                    continue;
                }

                string label = GetUniqueColumnLabel(qc);
                if (Lex.Eq(label, cName))
                {
                    break;
                }
            }

            if (qci >= qt.QueryColumns.Count)
            {
                qc = MqlUtil.GetQueryColumn(tok, q);                 // see if metacolumn name
                if (qc == null)
                {
                    ConvertLabeledCriteriaError("Unrecognized query element: \"" + pTok.Text + "\"", pTok, complexCriteriaCtl);
                    return(null);
                }
            }

            string colName = qc.MetaColumn.Name;

            if (tName != "")
            {
                colName = tName + "." + colName;                          // include table name or alias if exists
            }
            return(colName);
        }
Example #23
0
        /// <summary>
        /// Convert labeled criteria to complex checking for errors
        /// </summary>
        /// <param name="criteria"></param>
        /// <param name="q"></param>
        /// <param name="complexCriteriaCtl"></param>

        public static bool ConvertEditableCriteriaToComplex(
            LabeledCriteria labeledCriteria,
            Query q,
            RichTextBox complexCriteriaCtl)
        {
            QueryTable  qt;
            QueryColumn qc;

            Lex lex = new Lex();

            lex.SetDelimiters(" , ; ( ) < = > <= >= <> != !> !< [ ]");
            lex.OpenString(labeledCriteria.Text);
            StringBuilder   sb      = new StringBuilder();
            PositionedToken lastTok = null;

            List <PositionedToken> tokens = new List <PositionedToken>();           // list of tokens seen

            int parenDepth = 0;

            while (true)
            {
                PositionedToken pTok = lex.GetPositionedToken();
                if (pTok == null)
                {
                    break;
                }

                tokens.Add(pTok);

                if (lastTok != null)
                {                 // include same white space between tokens
                    int wsBeg = lastTok.Position + lastTok.Text.Length;
                    sb.Append(labeledCriteria.Text.Substring(wsBeg, pTok.Position - wsBeg));
                }

                string tok = pTok.Text;

                if (MqlUtil.IsKeyWord(pTok.Text))                 // ok if keyword, operator, etc
                {
                    if (pTok.Text == "(")
                    {
                        parenDepth++;
                    }
                    else if (pTok.Text == ")")
                    {
                        parenDepth--;
                    }
                }

                else if (pTok.Text.StartsWith("'"))                 // string constant
                {
                    if (tokens.Count >= 3 && Lex.Eq(tokens[tokens.Count - 2].Text, "In") &&
                        Lex.Eq(tokens[tokens.Count - 1].Text, "List"))
                    {                     // saved list reference
                        UserObject uo = QueryEngine.ResolveCnListReference(tok);
                        if (uo != null)
                        {
                            tok = "CNLIST_" + uo.Id.ToString();
                        }
                        else
                        {
                            tok = "Nonexistant list";
                        }
                        tok = Lex.AddSingleQuotes(tok);
                    }
                }

                else if (Lex.IsDouble(pTok.Text))
                {
                }                                                     // numeric constant

                else if (tok == "[")
                {                 // translate editable structure reference
                    pTok = lex.GetPositionedToken();
                    if (!MatchToken(pTok, "Edit", complexCriteriaCtl))
                    {
                        return(false);
                    }

                    pTok = lex.GetPositionedToken();
                    if (!MatchToken(pTok, "Structure", complexCriteriaCtl))
                    {
                        return(false);
                    }

                    pTok = lex.GetPositionedToken();
                    tok  = Lex.RemoveSingleQuotes(pTok.Text.ToUpper());
                    if (!labeledCriteria.Structures.ContainsKey(tok))
                    {
                        ConvertLabeledCriteriaError("Structure \"" + pTok.Text + "\" not defined", pTok, complexCriteriaCtl);
                        return(false);
                    }
                    tok = Lex.AddSingleQuotes(labeledCriteria.Structures[tok]);                     // replace with chime

                    pTok = lex.GetPositionedToken();
                    if (!MatchToken(pTok, "]", complexCriteriaCtl))
                    {
                        return(false);
                    }
                }

                else if (Lex.Eq(pTok.Text, "structure_field"))
                {                 // check for user failing to define structure_field in structure search criteria
                    ConvertLabeledCriteriaError("\"Structure_field\" must be replaced with a real field name", pTok, complexCriteriaCtl);
                    return(false);
                }

                else              // must be a column reference or invalid token
                {                 // translate labeled column name
                    tok = TranslateLabeledColumnName(pTok, q, complexCriteriaCtl);
                    if (tok == null)
                    {
                        return(false);
                    }
                }

                sb.Append(tok);
                lastTok = pTok;
            }

            tokens = tokens;             // debug

            if (parenDepth != 0)         // parens balance?
            {
                if (parenDepth > 0)
                {
                    MessageBoxMx.ShowError("Unbalanced parentheses: left parentheses exceed right by " + parenDepth.ToString());
                }

                else
                {
                    MessageBoxMx.ShowError("Unbalanced parentheses: right parentheses exceed left by " + (-parenDepth).ToString());
                }

                if (complexCriteriaCtl != null)
                {
                    complexCriteriaCtl.Focus();
                }
                return(false);
            }

            q.ComplexCriteria = sb.ToString();             // store back in query
            return(true);
        }
Example #24
0
        /// <summary>
        /// Convert complex criteria to labeled form suitable for editing in complex criteria editor
        /// </summary>
        /// <param name="q"></param>
        /// <param name="structures">Dictionary of structure names & connection tables</param>

        public static LabeledCriteria ConvertComplexCriteriaToEditable(
            Query q,
            bool includeEditButtons)
        {
            bool insertBreaks = false;

            if (q.ComplexCriteria.IndexOf("\n") < 0)
            {
                insertBreaks = true;
            }

            Dictionary <string, string> tAliasMap = GetAliasMap(q);

            if (tAliasMap != null && !includeEditButtons)
            {             // fixup aliases properly first using editable criteria
                ConvertComplexCriteriaToEditable(q, true);
                tAliasMap = null;
            }

            Lex lex = new Lex();

            lex.SetDelimiters(" , ; ( ) < = > <= >= <> != !> !<");
            string criteria = q.ComplexCriteria;

            lex.OpenString(criteria);
            StringBuilder   sb      = new StringBuilder();
            PositionedToken lastTok = null;

            List <PositionedToken> tokens = new List <PositionedToken>();           // list of tokens seen

            LabeledCriteria lc = new LabeledCriteria();

            lc.Structures = new Dictionary <string, string>();

            while (true)
            {
                PositionedToken tok = lex.GetPositionedToken();
                if (tok == null)
                {
                    break;
                }

                tokens.Add(tok);

                if (lastTok != null)
                {                 // include same white space between tokens
                    int wsBeg = lastTok.Position + lastTok.Text.Length;
                    sb.Append(criteria.Substring(wsBeg, tok.Position - wsBeg));
                }

                QueryColumn qc = MqlUtil.GetQueryColumn(tok.Text, q); // see if token is column ref
                if (qc != null)
                {                                                     //query column, map to labeled columns
                    string label = GetUniqueColumnLabel(qc);

                    QueryTable qt = qc.QueryTable;
                    string     tName, cName;
                    MqlUtil.ParseColumnIdentifier(tok.Text, out tName, out cName);
                    if (tName != null && tName != "")                     // any table name supplied?
                    {
                        if (tAliasMap != null && tAliasMap.ContainsKey(tName.ToUpper()))
                        {
                            tName = tAliasMap[tName.ToUpper()];
                        }
                        label = tName + "." + label;
                    }

                    sb.Append(Lex.Dq(label));
                }

                else
                {                 // not a query column reference
                    string tokText = tok.Text;

                    string txt = Lex.RemoveSingleQuotes(tokText).ToUpper();
                    if (UserObject.IsCompoundIdListName(txt))
                    {
                        string     listName = null;
                        int        objectId = int.Parse(txt.Substring(7));
                        UserObject uo       = UserObjectDao.ReadHeader(objectId);
                        if (uo != null)
                        {
                            listName = uo.InternalName;
                        }
                        else
                        {
                            listName = "Unknown";
                        }
                        tokText = Lex.AddSingleQuotes(listName);
                    }

                    if (tokens.Count >= 5)
                    {                     // see if this is a chime string
                        string sFuncCand = tokens[tokens.Count - 5].Text.ToLower();
                        if ((Lex.Eq(sFuncCand, "SSS") || Lex.Eq(sFuncCand, "FSS") || Lex.Eq(sFuncCand, "MolSim")) &&
                            tokText.StartsWith("'") && tokText.EndsWith("'"))                             // single-quoted chime?
                        {
                            string sAlias = "S" + (lc.Structures.Count + 1).ToString();
                            lc.Structures[sAlias] = Lex.RemoveSingleQuotes(tokText);                             // save structure in dictionary
                            if (includeEditButtons)
                            {
                                tokText = "[Edit Structure " + sAlias + "]";                                 // use alias in labeled query
                            }
                            else
                            {
                                tokText = Lex.AddSingleQuotes(sAlias);
                            }
                        }
                    }

                    if ((Lex.Eq(tokText, "And") || Lex.Eq(tokText, "Or")) &&
                        tokens.Count >= 3 && !Lex.Eq(tokens[tokens.Count - 3].Text, "Between") &&
                        insertBreaks)
                    {
                        sb.Append("\n");                    // start new line for each and/or
                    }
                    sb.Append(tokText);                     // not query column identifier
                }

                lastTok = tok;
            }

            sb.Append(" ");             // include final space so additional text is black, also to get correct font
            lc.Text = sb.ToString();

            // If a table alias changes then update aliases & complex criteria but only if going
            // to editable text since ConvertEditableCriteriaToComplex fails otherwise.

            if (tAliasMap != null)
            {
                for (int qti = 0; qti < q.Tables.Count; qti++)
                {                 // set new table aliases
                    QueryTable qt    = q.Tables[qti];
                    string     alias = "T" + (qti + 1).ToString();
                    qt.Alias = alias;
                }

                ConvertEditableCriteriaToComplex(lc, q, null);                 // update q.ComplexCriteria also
            }

            return(lc);
        }
Example #25
0
        /// <summary>
        /// See if a ClickFunction command & process if so
        /// </summary>
        /// <param name="command"></param>
        /// <param name="qm"></param>
        /// <param name="cInf"></param>

        public static void Process(
            string command,
            QueryManager qm,
            CellInfo cInf = null)
        {
            QueryTable    rootQt, qt;
            QueryColumn   qc;
            MetaTable     mt;
            MetaColumn    mc;
            Query         q2;
            string        dbName = "", mtName = "", mcName = "";
            List <string> args0, args;
            string        funcName, arg1, arg2, arg3, arg4, arg5;
            string        value = "", keyValue = "";

            int ai;

            try
            {
                // Parse click function arguments stripping all single quotes.
                // Arguments may be defined in the clickfunction definition including col values
                // indicated by field.Value in the metacolumn clickfunction definition.
                // If no args are defined in the clickfunction definition then a field value
                // argument will be added by default or the keyValue if [keyvalue] appears in the
                // ClickFunction definition

                CurrentClickQueryManager = qm;
                args0 = Lex.ParseAllExcludingDelimiters(command, "( , )", false);
                args  = new List <string>();
                for (ai = 0; ai < args0.Count; ai++)                 // strip all single quotes
                {
                    string arg = args0[ai];
                    if (arg.StartsWith("'"))
                    {
                        arg = Lex.RemoveSingleQuotes(arg);
                    }

                    //if (Lex.Eq(arg, "[rowcol]") && cInf!= null)
                    //{ // pass grid row & col
                    //  args.Add(cInf.GridRowHandle.ToString());
                    //  args.Add(cInf.GridColAbsoluteIndex.ToString());
                    //}
                    //else

                    args.Add(arg);
                }

                funcName = args[0];
                arg1     = (args.Count >= 2 ? args[1] : "");             // get other args
                arg2     = (args.Count >= 3 ? args[2] : "");
                arg3     = (args.Count >= 4 ? args[3] : "");
                arg4     = (args.Count >= 5 ? args[4] : "");
                arg5     = (args.Count >= 6 ? args[5] : "");

                if (Lex.Eq(funcName, "DisplayAllData"))
                {                 // do all data display for supplied root table and key, i.e. DisplayAllData(TableName, KeyColName, KeyValue)
                    ParseMetaTableMetaColumn(arg1, out mt, arg2, out mc);
                    string extKey = arg3;
                    string intKey = CompoundId.Normalize(extKey, mt);

                    Progress.Show("Building Query...");
                    _query = QueryEngine.GetSelectAllDataQuery(mt.Name, intKey);
                    Progress.Show("Retrieving data...");                     // put up progress dialog since this may take a while
                    QbUtil.RunPopupQuery(_query, mt.KeyMetaColumn.Name + " " + extKey);
                    Progress.Hide();
                    return;
                }

                else if (Lex.Eq(funcName, "DisplayAllDataUsingDbName"))
                {                 // display all data for supplied database synonym & key value, i.e. DisplayAllData2(DataBaseSynonym, KeyValue)
                    mtName = null;
                    dbName = arg1;
                    RootTable rti = RootTable.GetFromTableLabel(dbName);
                    if (rti != null)
                    {
                        mtName = rti.MetaTableName;
                    }
                    else                     // try synonyms
                    {
                        DictionaryMx dict = DictionaryMx.Get("Database_Synonyms");
                        if (dict != null)
                        {
                            mtName = dict.LookupDefinition(dbName);
                        }
                    }

                    if (String.IsNullOrEmpty(mtName))
                    {
                        MessageBoxMx.ShowError("Unrecognized database: " + dbName);
                        return;
                    }

                    mt = MetaTableCollection.Get(mtName);
                    if (mt == null)
                    {
                        MessageBoxMx.ShowError("Can't find key metatable " + mtName + " for database " + dbName);
                        return;
                    }

                    string extKey = arg2;
                    string intKey = CompoundId.Normalize(extKey, mt);

                    Progress.Show("Building Query...");
                    _query = QueryEngine.GetSelectAllDataQuery(mt.Name, intKey);
                    Progress.Show("Retrieving data...");                     // put up progress dialog since this may take a while
                    QbUtil.RunPopupQuery(_query, mt.KeyMetaColumn.Name + " " + extKey);
                    return;
                }

                // Run a query displaying results to a grid or web page and substituting a parameter value

                else if (Lex.Eq(funcName, "RunHtmlQuery") || Lex.Eq(funcName, "RunGridQuery"))
                {                 // command to display to grid or html
                    if (arg1.StartsWith("MetaTreeNode=", StringComparison.OrdinalIgnoreCase))
                    {             // query based on metatables under a tree node
                        string nodeName = arg1.Substring("MetaTreeNode=".Length).Trim();
                        _cid = arg2;

                        MetaTreeNode mtn = MetaTree.GetNode(nodeName);
                        if (mtn == null)
                        {
                            MessageBoxMx.ShowError("Can't find tree node referenced in ClickFunction: " + nodeName);
                            return;
                        }

                        _query = new Query();
                        MetaTable rootMt = null;
                        foreach (MetaTreeNode mtn_ in mtn.Nodes)
                        {
                            if (!mtn_.IsDataTableType)
                            {
                                continue;
                            }
                            mt = MetaTableCollection.Get(mtn_.Target);
                            if (mt == null)
                            {
                                continue;
                            }
                            if (rootMt == null)
                            {
                                rootMt = mt.Root;
                                rootQt = new QueryTable(_query, rootMt);
                            }

                            if (mt == rootMt)
                            {
                                continue;
                            }
                            qt = new QueryTable(_query, mt);
                        }

                        if (_query.Tables.Count == 0)
                        {
                            MessageBoxMx.ShowError("No valid data tables found: " + nodeName);
                            return;
                        }

                        _query.KeyCriteria = "= " + _cid;
                        _title             = mtn.Label + " for " + _query.Tables[0].MetaTable.MetaColumns[0].Label + " " + CompoundId.Format(_cid);
                    }

                    else if (arg1.StartsWith("Query=", StringComparison.OrdinalIgnoreCase))
                    {                     // query based on saved query
                        string qIdString = arg1.Substring("Query=".Length).Trim();
                        if (qIdString.StartsWith("Query_", StringComparison.OrdinalIgnoreCase))
                        {
                            qIdString = qIdString.Substring("Query_".Length).Trim();
                        }
                        int qId = int.Parse(qIdString);

                        _query = QbUtil.ReadQuery(qId);

                        _cid = arg2;
                        _query.KeyCriteria = "= " + _cid;
                        _title             = _query.UserObject.Name + " for " + _query.Tables[0].MetaTable.MetaColumns[0].Label + " " + CompoundId.Format(_cid);
                    }

                    else                     // explicit mql string to execute
                    {
                        _mql = arg1;         // mql to execute
                        if (Lex.IsUndefined(_mql))
                        {
                            throw new Exception("Expected MQL query not found: " + command);
                        }

                        mt = null;
                        mc = null;

                        if (Lex.IsDefined(arg2) && Lex.IsDefined(arg3))
                        {
                            mtName   = arg2;
                            mcName   = arg3;
                            value    = arg4;                          // value to plug in to mql
                            keyValue = value;
                            ParseMetaTableMetaColumn(arg2, out mt, arg3, out mc);
                        }

                        else if (cInf != null)
                        {
                            mt       = cInf.Mt;
                            mc       = cInf.Mc;
                            value    = cInf?.DataValue?.ToString();
                            keyValue = qm?.DataTableManager?.GetRowKey(cInf.DataRowIndex);
                        }

                        if (mt == null || mc == null)
                        {
                            throw new Exception("Invalid MetaTable or MetaColumn name(s): " + command);
                        }

                        if (!mc.IsNumeric)
                        {
                            value = Lex.AddSingleQuotes(value);                             // quote if not numeric
                        }
                        int i1 = _mql.ToLower().IndexOf("[value]");                         // see if a value parameter
                        if (i1 >= 0)
                        {
                            string value2 = value;
                            _mql   = _mql.Replace(_mql.Substring(i1, 7), value);
                            _title = mc.Label + " " + value;
                        }

                        i1 = _mql.ToLower().IndexOf("[keyvalue]");                         // see if a key value parameter
                        if (i1 >= 0)
                        {
                            _mql   = _mql.Replace(_mql.Substring(i1, 10), keyValue);
                            _title = mt.KeyMetaColumn.Label + " " + keyValue;
                        }

                        try { _query = MqlUtil.ConvertMqlToQuery(_mql); }
                        catch (Exception ex)
                        {
                            MessageBoxMx.ShowError("Error converting Mql to query: " + ex.Message);
                            return;
                        }
                    }

                    if (Lex.Eq(funcName, "RunHtmlQuery"))
                    {
                        QbUtil.RunPopupQuery(_query, _title, OutputDest.Html);
                    }

                    else                     // output to grid
                    {
                        QbUtil.RunPopupQuery(_query, _title, OutputDest.WinForms);
                    }

                    //else // create new grid query & run (will lose results for current query)
                    //{
                    //	QbUtil.NewQuery(_title); // show in query builder
                    //	QbUtil.SetCurrentQueryInstance(_query);
                    //	QbUtil.RenderQuery();
                    //	string nextCommand = QueryExec.RunQuery(_query, OutputDest.Grid);
                    //}

                    return;
                }

                // Open a URL, normally substituting parameter value

                else if (Lex.Eq(funcName, "OpenUrl"))
                {
                    string url = arg1;                    // url to execute
                    value = arg2;                         // value to plug in to url

                    int i1 = Lex.IndexOf(url, "[value]"); // fill in one of the value place holders
                    if (i1 >= 0)
                    {
                        string value2 = value;
                        url = url.Replace(url.Substring(i1, 7), value);
                    }

                    else                     // check to see if we are matching on key
                    {
                        i1 = Lex.IndexOf(url, "[keyvalue]");
                        if (i1 >= 0)
                        {
                            url = url.Replace(url.Substring(i1, 10), value);
                        }
                    }

                    SystemUtil.StartProcess(url);
                    return;
                }

                else if (Lex.Eq(funcName, "OpenUrlFromSmallWorldCid"))
                {
                    SmallWorldDepictions.OpenUrlFromSmallWorldCid(arg1);
                    return;
                }

                else if (Lex.Eq(funcName, "ShowProjectDescription"))
                {
                    string projName = arg1;
                    QbUtil.ShowProjectDescription(projName);
                    return;
                }

                else if (Lex.Eq(funcName, "ShowTableDescription"))
                {
                    mtName = arg1;
                    QbUtil.ShowTableDescription(mtName);
                    return;
                }

                else if (Lex.Eq(funcName, "DisplayDrilldownDetail"))
                {                           // drill down into a result value
                    mtName = arg1;          // table
                    mcName = arg2;          // column
                    int    level    = Int32.Parse(arg3);
                    string resultId = arg4; // quoted resultId to get
                    q2 = QueryEngine.GetSummarizationDetailQuery(mtName, mcName, level, resultId);
                    if (q2 == null)
                    {
                        throw new Exception("Unable to build drill-down query for: " + mtName + "." + mcName);
                    }
                    bool success = QbUtil.RunPopupQuery(q2, "Result Detail", OutputDest.WinForms);
                    return;
                }

                //else if (Lex.Eq(funcName, "PopupSmilesStructure")) // display structure for a Smiles string (still needs some work...)
                //{
                //	string molString = arg1.ToString();
                //	ChemicalStructure cs = new ChemicalStructure(StructureFormat.Smiles, molString);
                //	ToolHelper.DisplayStructureInPopupGrid("Title...", "Smiles", "Structure", cs);
                //}

                //else if (Lex.Eq(funcName, "PopupChimeStructure")) // display structure for a Chime string
                //{
                //	string molString = arg1.ToString();
                //	ChemicalStructure cs = new ChemicalStructure(StructureFormat.Smiles, molString);
                //	ToolHelper.DisplayStructureInPopupGrid("Title...", "Smiles", "Structure", cs);
                //}

                else if (Lex.Eq(funcName, "DisplayWebPage"))
                {                 // substitute a field value into a url & display associated web page
                    string url = arg1;

                    ParseMetaTableMetaColumn(arg2, out mt, arg3, out mc);
                    value = arg4;                     // value to plug in to mql

                    //				value = "{6E9C28EF-407E-44A0-9007-5FFB735A5C6C}"; // debug
                    //				value = "{0AC17903-E551-445E-BFAA-860023D2884F}"; // debug
                    //				value = "{63EE71F9-15BA-42FB-AFDC-C399103707B1}"; // debug
                    //				value = "{80591183-B7BA-4669-8C5F-7E7F53D981CE}";

                    //lex.OpenString(mc.ClickFunction); // reparse url to get proper case
                    //funcName = lex.GetNonDelimiter();
                    //url = Lex.RemoveAllQuotes(lex.GetNonDelimiter());

                    _title = mc.Label + " " + value;
                    int i1 = url.ToLower().IndexOf("[value]");                     // fill in one of the value place holders
                    if (i1 >= 0)
                    {
                        url = url.Replace(url.Substring(i1, 7), value);
                    }

                    else                     // check to see if we are matching on key
                    {
                        i1 = url.ToLower().IndexOf("[keyvalue]");
                        if (i1 >= 0)
                        {
                            url    = url.Replace(url.Substring(i1, 10), value);
                            _title = mt.KeyMetaColumn.Label + " " + value;
                        }
                    }

                    UIMisc.ShowHtmlPopupFormDocument(url, _title);
                    return;
                }

                else if (Lex.Eq(funcName, "DisplayOracleBlobDocument")) // display a document contained in an Oracle blob column
                {                                                       // Syntax: DisplayOracleBlobDocument(<table-to-lookup>, <value_match_column>, <file-name-or-type-col>, <content-column>)
                    string table      = arg1;
                    string matchCol   = arg2;
                    string typeCol    = arg3;
                    string contentCol = arg4;
                    string matchVal   = arg5;                   // value to match

                    try
                    {
                        string typeName;
                        byte[] ba;
                        UalUtil.SelectOracleBlob(table, matchCol, typeCol, contentCol, matchVal, out typeName, out ba);
                        if (ba == null || ba.Length == 0)
                        {
                            return;
                        }

                        UIMisc.SaveAndOpenBinaryDocument(typeName, ba);
                    }

                    catch (Exception ex)
                    {
                        MessageBoxMx.ShowError("Error retrieving document: " + ex.Message);
                        return;
                    }

                    return;
                }

                else if (Lex.Eq(funcName, "DisplayOracleClobDocument")) // display a document contained in an Oracle clob column
                {                                                       // Syntax: DisplayOracleBlobDocument(<table-to-lookup>, <value_match_column>, <file-name-or-type-col>, <content-column>)
                    string table      = arg1;
                    string matchCol   = arg2;
                    string typeCol    = arg3;
                    string contentCol = arg4;
                    string matchVal   = arg5;                   // value to match

                    try
                    {
                        string typeName, clobString;
                        UalUtil.SelectOracleClob(table, matchCol, typeCol, contentCol, matchVal, out typeName, out clobString);
                        if (Lex.IsUndefined(clobString))
                        {
                            return;
                        }

                        UIMisc.SaveAndOpenBase64BinaryStringDocument(typeName, clobString);                         // assume clob string is a Base64Binary string
                    }

                    catch (Exception ex)
                    {
                        MessageBoxMx.ShowError("Error retrieving document: " + ex.Message);
                        return;
                    }

                    return;
                }

                else if (Plugins.IsMethodExtensionPoint(funcName))
                {
                    List <object> objArgs = new List <object>();
                    for (ai = 1; ai < args.Count; ai++)                     // build list of object arguments
                    {
                        objArgs.Add(args[ai]);
                    }
                    Plugins.CallStringExtensionPointMethod(funcName, objArgs);
                }

                else if (Lex.Eq(funcName, "None"))                 // dummy click function
                {
                    return;
                }

                else
                {
                    MessageBoxMx.ShowError("Unrecogized click function: " + funcName);
                    return;
                }
            }

            catch (Exception ex)
            {
                Exception ex2 = ex;
                if (ex.InnerException != null)
                {
                    ex2 = ex.InnerException;
                }
                string msg = "Error executing ClickFunction: " + command + "\r\n" +
                             DebugLog.FormatExceptionMessage(ex);
                MessageBoxMx.ShowError(msg);

                ServicesLog.Message(msg);
            }
        }
Example #26
0
        /// <summary>
        /// Initialize for any structure hilighting
        /// </summary>

        void InitializeStructureHilighting()
        {
            QueryColumn qc = null;

            if (StructureHighlightingInitialized)
            {
                return;
            }

            // Structure match hilighting / orienting

            try
            {
                do
                {
                    qc = Query.GetFirstStructureCriteriaColumn();
                    if (qc == null)
                    {
                        break;
                    }
                    if (Lex.IsUndefined(qc.Criteria))
                    {
                        break;
                    }

                    ParsedSingleCriteria psc = MqlUtil.ParseQueryColumnCriteria(qc);
                    if (psc == null || Lex.IsUndefined(psc.Value))
                    {
                        break;
                    }

                    ParsedStructureCriteria pssc = ParsedStructureCriteria.ConvertFromPscToPssc(psc);

                    StructureDisplayFormat sdf = StructureDisplayFormat.Deserialize(qc.DisplayFormatString);                     // get any hilighting info from format

                    if (pssc.SearchType == StructureSearchType.Substructure)
                    {
                        string chime = MoleculeMx.MolfileStringToChimeString(qc.MolString);
                        if (!String.IsNullOrEmpty(chime))
                        {
                            AlignStructureToQuery     = Lex.Contains(psc.Value2, "Orient") || Lex.Contains(psc.Value2, "Align=True");
                            HighlightStructureMatches = !(Lex.Contains(psc.Value2, "NoHighlight") || Lex.Contains(psc.Value2, "Highlight=false"));
                            MoleculeMx cs = new MoleculeMx(MoleculeFormat.Chime, chime);
                            StrMatcher = new StructureMatcher();
                            StrMatcher.SetSSSQueryMolecule(cs);                             // set query used for highlighting
                        }
                    }

                    else if (pssc.SearchType == StructureSearchType.SmallWorld && pssc.SmallWorldParameters != null)
                    {
                        SmallWorldPredefinedParameters swp = pssc.SmallWorldParameters;
                        HighlightStructureMatches = swp.Highlight;
                        AlignStructureToQuery     = swp.Align;
                        //SmallWorldDepictions = null; // depiction cache
                    }

                    else if (pssc.SearchType == StructureSearchType.Related)                     //
                    {
                        string chime = MoleculeMx.MolfileStringToChimeString(qc.MolString);
                        if (!String.IsNullOrEmpty(chime))
                        {
                            AlignStructureToQuery     = Lex.Contains(psc.Value2, "Orient") || Lex.Contains(psc.Value2, "Align=True");
                            HighlightStructureMatches = !(Lex.Contains(psc.Value2, "NoHighlight") || Lex.Contains(psc.Value2, "Highlight=false"));
                            MoleculeMx cs = new MoleculeMx(MoleculeFormat.Chime, chime);
                            StrMatcher = new StructureMatcher();
                            StrMatcher.SetSSSQueryMolecule(cs);                             // set query used for SSS highlighting
                        }
                    }

                    else if (sdf.Highlight || sdf.Align)                     // other cases
                    {
                        HighlightStructureMatches = sdf.Highlight;
                        AlignStructureToQuery     = sdf.Align;
                    }

                    else
                    {
                        break;                      // no hilighting / orienting
                    }
                    StructureHighlightQc   = qc;
                    StructureHighlightPssc = pssc;
                } while (false);
            }

            catch (Exception ex)             // log & ignore any errors
            {
                string msg = DebugLog.FormatExceptionMessage(ex);
                if (qc != null)
                {
                    msg += "\r\n" +
                           "Criteria: " + qc.Criteria + "\r\n" +
                           "Molstring: " + qc.MolString;
                }

                DebugLog.Message(msg);
                return;
            }

            // Atom number display (not currently used)

            SS.I.DisplayAtomNumbers = (int)AtomNumberDisplayMode.None;             // see if need to display atom numbers
            for (int ti = 1; ti < Rf.Tables.Count; ti++)
            {
                ResultsTable rt = Rf.Tables[ti];
                MetaTable    mt = rt.MetaTable;
                if (mt.Name.IndexOf("todo: table that needs atom number display") >= 0)
                {
                    SS.I.DisplayAtomNumbers = (int)AtomNumberDisplayMode.All;
                    break;
                }
            }

            StructureHighlightingInitialized = true;
            return;
        }
Example #27
0
        public static bool Edit(
            QueryColumn qc)
        {
            AssertMx.IsNotNull(qc, "qc");
            MetaColumn mc = qc.MetaColumn;

            if (Instance == null)
            {
                Instance = new CriteriaYesNo();
            }

            new JupyterGuiConverter().ConvertFormOrUserControl(Instance);

            Instance.Text        = "Search criteria for " + qc.ActiveLabel;
            Instance.Prompt.Text = "Select a search option for " + qc.ActiveLabel + " from the list below.";

            ParsedSingleCriteria psc = MqlUtil.ParseSingleCriteria(qc.Criteria);

            if (psc == null)
            {
                psc = new ParsedSingleCriteria();                          // no criteria
            }
            if (Lex.Eq(psc.Value, "Y"))
            {
                Instance.YesCheckEdit.Checked = true;
            }

            else if (Lex.Eq(psc.Value, "N"))
            {
                Instance.NoCheckEdit.Checked = true;
            }

            else
            {
                Instance.None.Checked = true;
            }

            DialogResult dr = Instance.ShowDialog(SessionManager.ActiveForm);

            if (dr == DialogResult.OK)
            {
                if (Instance.YesCheckEdit.Checked)
                {
                    qc.CriteriaDisplay = "= Y";
                    qc.Criteria        = mc.Name + " = 'Y'";
                }

                else if (Instance.NoCheckEdit.Checked)
                {
                    qc.CriteriaDisplay = "= N";
                    qc.Criteria        = mc.Name + " = 'N'";
                }

                else if (Instance.None.Checked)
                {
                    qc.CriteriaDisplay = "";
                    qc.Criteria        = "";
                }

                return(true);
            }

            else
            {
                return(false);
            }
        }
Example #28
0
        public void Setup(ColumnInfo colInfo)
        {
            bool   check;
            string s;

            InSetup = true;
            ColInfo = colInfo;             // save ref to colInfo
            QueryColumn qc = colInfo.Qc;

            ParsedSingleCriteria psc = MqlUtil.ParseSingleCriteria(ColInfo.Qc.SecondaryCriteria);             // parse criteria

            Dictionary <string, object> listDict = new Dictionary <string, object>();

            if (psc != null && psc.OpEnum != CompareOp.In)
            {
                psc = null;                 // switching from other criteria type
            }
            if (psc != null && Lex.Contains(qc.SecondaryCriteria, "(All)"))
            {
                psc = null;              // rebuild if "all" items
            }
            if (psc != null)             // list of previously selected items
            {
                foreach (string vs in psc.ValueList)
                {
                    if (qc.MetaColumn.DataType == MetaColumnType.CompoundId)
                    {
                        s = CompoundId.Format(vs);
                    }
                    else if (qc.MetaColumn.DataType == MetaColumnType.Date)
                    {
                        s = DateTimeMx.Format(vs);
                    }
                    else
                    {
                        s = vs;
                    }
                    listDict[s.ToUpper()] = null;
                }
            }

            else             // setup default criteria
            {
                qc.SecondaryCriteria        = qc.MetaColumn.Name + " in ('(All)')";
                qc.SecondaryCriteriaDisplay = qc.ActiveLabel + " in list (All)";
            }

            ColumnStatistics             stats = colInfo.Rfld.GetStats();
            CheckedListBoxItemCollection items = ItemList.Items;

            items.Clear();
            check = (psc == null || listDict.ContainsKey("(All)".ToUpper()) || listDict.ContainsKey("All".ToUpper()));
            AddItem("(All)", check);

            if (stats.NullsExist || Math.Abs(1) == 1)
            {             // always include blank/nonblank since there may be null rows because other tables have more rows for key
                check     = (psc == null || listDict.ContainsKey("(Blanks)".ToUpper()) || listDict.ContainsKey("Blanks".ToUpper()));
                BlanksPos = items.Count;
                AddItem("(Blanks)", check);

                check        = (psc == null || listDict.ContainsKey("(Non blanks)".ToUpper()) || listDict.ContainsKey("Nonblanks".ToUpper()));
                NonBlanksPos = items.Count;
                AddItem("(Non blanks)", check);
            }

            else
            {
                BlanksPos = NonBlanksPos = -1;
            }

            foreach (MobiusDataType mdt in stats.DistinctValueList)
            {
                s     = mdt.FormattedText;
                check = (psc == null || listDict.ContainsKey(s.ToUpper()));
                AddItem(s, check);
                if (items.Count >= 100)
                {
                    AddItem("...", check);
                    break;
                }
            }

            int itemHeight = 18;                                                   // height of single item (really 17 but add a bit extra)
            int fullHeight = ItemList.Top + 6 + ItemList.Items.Count * itemHeight; // full height of control

            if (fullHeight < this.Height)
            {
                this.Height = fullHeight;
            }

            InSetup = false;
            return;
        }
Example #29
0
        /// <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);
            }
        }
Example #30
0
        /// <summary>
        /// Select structures for a list of compound ids using a single SQL cursor.
        /// </summary>
        /// <param name="notInCache"></param>
        /// <param name="mt"></param>
        /// <param name="strMc"></param>

        static Dictionary <string, MoleculeMx> SelectChemicalStructuresForCorpIdList(
            List <string> cidList,
            MetaTable mt)
        {
            List <string> notInCacheKeyList;
            Dictionary <Int64, string> intKeyToStringKey;
            DbType     parmType;
            MoleculeMx cs;
            Int64      intCid;
            string     cid;
            int        li;

            Stopwatch sw = Stopwatch.StartNew();

            Dictionary <string, MoleculeMx> csDict = new Dictionary <string, MoleculeMx>();
            List <string> notInCacheList           = new List <string>();

            // Get structures already in the cache

            for (li = 0; li < cidList.Count; li++)
            {
                cid = cidList[li];

                if (RestrictedDatabaseView.KeyIsRetricted(cid))
                {
                    continue;
                }

                cid = CompoundId.Normalize(cid, mt);
                if (!Int64.TryParse(cid, out intCid))
                {
                    continue;                                    // make sure an integer
                }
                if (MoleculeCache.Contains(cid))                 // see if in cache
                {
                    csDict[cid] = MoleculeCache.Get(cid);
                    continue;
                }

                else
                {
                    notInCacheList.Add(cid);
                }
            }

            // Retrieve structures from the database for those not in cache

            if (notInCacheList.Count == 0)
            {
                return(csDict);
            }

            MetaColumn strMc = mt.GetMetaColumnByName("molstructure");

            if (strMc == null)
            {
                return(null);
            }

            string tableMap = mt.GetTableMapWithAliasAppendedIfNeeded();             // some SQL (e.g. Postgres) requires an alias for subqueries)

            string keyColName = mt.KeyMetaColumn.ColumnMap;

            if (Lex.IsUndefined(keyColName))
            {
                keyColName = mt.KeyMetaColumn.Name;
            }

            string 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
            }

            string sql =
                "select " + keyColName + ", " + strColExpr + " " +
                "from " + tableMap + " " +
                "where " + keyColName + " in (<list>)";

            DbCommandMx drd = new DbCommandMx();

            bool isNumericKey = (mt.KeyMetaColumn.IsNumeric);
            bool isStringKey  = !isNumericKey;

            if (isStringKey)
            {
                parmType = DbType.String;
            }
            else
            {
                parmType = DbType.Int64;
            }

            try
            {
                drd.PrepareListReader(sql, parmType);
                drd.ExecuteListReader(notInCacheList);
                while (drd.Read())
                {
                    if (drd.Rdr.IsDBNull(0))
                    {
                        continue;
                    }

                    if (isNumericKey)
                    {
                        intCid = drd.GetLong(0);
                        cid    = intCid.ToString();
                    }

                    else                     // string cid
                    {
                        cid = drd.GetString(0);
                    }

                    cid = CompoundId.Normalize(cid, mt);

                    string molString = drd.GetString(1);

                    cs          = new MoleculeMx(MoleculeFormat.Chime, molString);
                    csDict[cid] = cs;

                    MoleculeCache.AddMolecule(cid, cs);
                }

                drd.Dispose();
                int msTime = (int)sw.ElapsedMilliseconds;
                return(csDict);
            }

            catch (Exception ex)
            {
                if (drd != null)
                {
                    drd.Dispose();
                }

                throw new Exception(
                          "SelectStructuresForCorpIdList, table: " + mt.Name + "\n" +
                          "sql: " + OracleMx.FormatSql(sql) + "\n");
            }
        }