Exemple #1
0
        /// <summary>
        /// Format structure for output to SDFile
        /// </summary>
        /// <param name="molid"></param>

        void FormatSdfileStructure(
            MoleculeMx cs)
        {
            string molFile, cid;

            if (SS.I.RemoveLeadingZerosFromCids)             // normal formatting
            {
                cid = CompoundId.Format(CurrentKey);
            }
            else
            {
                cid = CurrentKey;              // just use internal formatting
            }
            cs      = cs.Convert(Rf.StructureFlags | MoleculeTransformationFlags.RemoveStructureCaption, cid);
            molFile = cs.GetMolfileString();

            if (molFile.IndexOf("\r") < 0)             // add carriage returns to molfile if it doesn't contain them
            {
                molFile = molFile.Replace("\n", "\r\n");
            }

            SdfLine = molFile;

            return;
        }
Exemple #2
0
        /// <summary>
        /// Update the list of related compounds
        /// </summary>
        /// <param name="mt"></param>
        /// <param name="cid"></param>
        /// <param name="str"></param>

        private void UpdateRelatedCidsDisplayOld(
            MetaTable mt,
            string cid,
            MoleculeMx str)
        {
            if (SS.I.AllowGroupingBySalts)             // build list of salts & send
            {
                List <string> salts = MoleculeUtil.GetAllSaltForms(Cid);
                if (salts == null || salts.Count == 0)                 // nothing related
                {
                    OtherCidsList.Visible = false;                     // hide list
                }
                else
                {
                    OtherCidsList.Properties.Items.Clear();
                    foreach (string s in salts)
                    {
                        string extCid = CompoundId.Format(s);
                        OtherCidsList.Properties.Items.Add(extCid);
                    }
                    string listHeader = salts.Count.ToString() + " Other Match";
                    if (salts.Count > 1)
                    {
                        listHeader += "es";                              // use proper grammar
                    }
                    OtherCidsList.Text    = listHeader;                  // select first item
                    OtherCidsList.Visible = true;
                }
            }

            else
            {
                OtherCidsList.Visible = false;              // hide list
            }
        }
Exemple #3
0
        private void InsertSaltsForAllCompounds_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DisplayStatusMsg("Inserting Salts, wait please...");
            GetNormalizedListFromControl(CidList);
            List <string> al = MoleculeUtil.InsertSalts(CidList.ToStringList());

            CidList newList = new CidList(al);

            newList.UserObject = CidList.UserObject;
            StringBuilder listBuild = new StringBuilder(newList.Count * 12 + 32);             // build formatted list here

            foreach (CidListElement cle in newList.List)
            {             // build formatted list with added items marked
                listBuild.Append(CompoundId.Format(cle.Cid, RootTable));
                if (!CidList.Contains(cle.Cid))
                {
                    listBuild.Append(" (+)");
                }
                listBuild.Append("\r\n");
            }

            CidList         = newList;
            CidListCtl.Text = listBuild.ToString();
            DisplayStatusMsg("");
            return;
        }
Exemple #4
0
        private void InsertSaltsForCurrentCompound_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string cid = GetCurrentCid(false);

            if (cid.Trim().Length == 0)
            {
                return;
            }
            List <string> al = MoleculeUtil.GetAllSaltForms(cid);

            if (al == null || al.Count == 0)
            {
                DisplayStatusMsg("No salts for " + CompoundId.Format(cid, RootTable));
                SystemUtil.Beep();
                return;
            }

            StringBuilder listBuild = new StringBuilder();

            foreach (string s in al)
            {             // build formatted list with added items marked
                if (s == cid)
                {
                    continue;                           // don't add self
                }
                listBuild.Append(CompoundId.Format(s, RootTable));
                listBuild.Append(" (+)");
                listBuild.Append("\r\n");
            }
            InsertCidListText(listBuild.ToString());
            return;
        }
Exemple #5
0
/// <summary>
/// Display the structure and other basic data for the supplied cid
/// </summary>
/// <param name="cidArg"></param>

        void DisplayCidData(string cidArg)
        {
            MoleculeMx str = null;
            string     mwTxt = "", mfTxt = "", haTxt = "", tok;

            string intCid = CompoundId.Normalize(cidArg, RootTable);
            string extCid = CompoundId.Format(intCid, RootTable);

            CidCtl.Text = extCid;

            if (RootTable == null || RootTable.KeyMetaColumn.DataType == MetaColumnType.CompoundId)
            {
                str = MoleculeUtil.SelectMoleculeForCid(intCid, RootTable);
            }

            if (Lex.IsDefined(str?.PrimaryValue))             // have a structure with at least one atom
            {
                if (str.PrimaryDisplayFormat == MoleculeRendererType.Chemistry)
                {
                    int ha = str.HeavyAtomCount;
                    if (ha > 0)
                    {
                        haTxt = ha.ToString();
                    }

                    double mw = str.MolWeight;
                    if (mw >= 0)
                    {
                        mwTxt = String.Format("{0:f3}", mw);
                    }
                    HeavyAtoms.Text = "";
                    Weight.Text     = mwTxt;

                    string mf = str.MolFormula;
                    HeavyAtoms.Text = "";
                    Formula.Text    = mf;
                }

                else
                {
                }                        // biopolymer, don't calc structure props (too slow for now)

                HeavyAtoms.Text = haTxt;
                Weight.Text     = mwTxt;
                Formula.Text    = mfTxt;

                MolCtl.Molecule = str;

                return;
            }

            else             // no structure
            {
                HeavyAtoms.Text = "";
                Weight.Text     = "";
                Formula.Text    = "";
                MolCtl.ClearMolecule();
                return;
            }
        }
Exemple #6
0
/// <summary>
/// Format list for display
/// </summary>
/// <param name="rootTable"></param>
/// <returns></returns>

        string FormatList()
        {
            string formattedCid;

            StringBuilder listBuild = new StringBuilder(CidList.Count * 12 + 32);             // allocate expected length

            for (int li = 0; li < CidList.Count; li++)
            {
                if (listBuild.Length > 0)
                {
                    listBuild.Append("\r\n");
                }
                string cid = CidList[li].Cid;
                if (SS.I.RemoveLeadingZerosFromCids)                 // normal formatting
                {
                    formattedCid = CompoundId.Format(cid, RootTable);
                }
                else
                {
                    formattedCid = cid;                  // just use internal formatting
                }
                listBuild.Append(formattedCid);
            }

            return(listBuild.ToString());
        }
Exemple #7
0
/// <summary>
/// ShowImmediate
/// </summary>
/// <param name="singleCorpId"></param>

        void ShowPopup(string singleCorpId)
        {
            KeyQc          = QueryTable.GetDefaultRootQueryTable()?.KeyQueryColumn;
            KeyQc.Criteria = KeyQc.MetaColumnName + " = " + singleCorpId;

            //Tso = new TargetSummaryOptions();
            //Tso.CidCriteria = "= " + singleCorpId;

            string title = "Spotfire View of Data for Compound Id " + CompoundId.Format(singleCorpId);

            BuildQuery(title);
            QbUtil.RunPopupQuery(Query, title, OutputDest.WinForms);
            return;
        }
Exemple #8
0
/// <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;
            }
        }
Exemple #9
0
        /// <summary>
/// Setup the form with existing criteria
/// </summary>
/// <param name="qc"></param>

        void Setup(
            QueryColumn qc)
        {
            MetaTable mt = null;
            string    listName, mcName, tok, tok1, tok2, tok3, txt;
            int       i1;

            if (qc != null && qc.QueryTable != null)
            {
                mt = qc.QueryTable.MetaTable;
            }

            Text        = qc.ActiveLabel + " Criteria";
            Prompt.Text =
                "Choose one of the following " + qc.ActiveLabel + " criteria options.";

            Cid.Text            = "";
            CidListDisplay.Text = "";
            ListName.Text       = "";
            SavedListUo         = null;
            CidLo.Text          = "";
            CidHi.Text          = "";

            TempListName.Properties.Items.Clear();             // build dropdown of available temp list names
            foreach (TempCidList tl0 in SS.I.TempCidLists)
            {
                TempListName.Properties.Items.Add(tl0.Name);
            }
            TempListName.Text = "Current";

            Lex lex = new Lex();

            lex.OpenString(qc.Criteria);
            mcName = lex.GetUpper();               // metacolumn name
            if (Lex.Ne(mcName, qc.MetaColumnName)) // check if col name is first token
            {                                      // if not assume it's simply missing and that the operator is the first token
                lex.Backup();
                mcName = qc.MetaColumnName;
            }

            tok  = lex.GetUpper();            // operator
            tok1 = lex.GetUpper();            // following tokens */
            tok2 = lex.GetUpper();
            tok3 = lex.GetUpper();

            if (tok == "=" || tok == "")
            {
                tok1       = CompoundId.Format(tok1, mt);
                Cid.Text   = tok1;
                EQ.Checked = true;
            }

            else if (tok == "IN" && tok1.StartsWith("("))             // list saved with query only
            {
                InList.Checked = true;

                CidListString = qc.Criteria;
                i1            = CidListString.IndexOf("(");      // just get the list itself if parenthesized
                if (i1 >= 0)
                {
                    CidListString = CidListString.Substring(i1 + 1);
                }
                if (CidListString.EndsWith(")"))
                {
                    CidListString = CidListString.Substring(0, CidListString.Length - 1);
                }

                SetCidListDisplay();
            }

            else if (tok == "IN" && (Lex.Eq(Lex.RemoveAllQuotes(tok2), "CURRENT") ||
                                     Lex.StartsWith(tok2, UserObject.TempFolderNameQualified)))
            {             // temp list
                if (Lex.StartsWith(tok2, UserObject.TempFolderNameQualified))
                {
                    tok2 = tok2.Substring(UserObject.TempFolderNameQualified.Length);
                }
                TempListName.Text = tok2;
                TempList.Checked  = true;
            }

            else if (tok == "IN")             // saved list
            {
                SavedListUo = QueryEngine.ResolveCnListReference(tok2);
                if (SavedListUo != null)
                {
                    listName = SavedListUo.Name;
                }

                else
                {
                    listName = "Nonexistant list";                  // list deleted
                }
                ListName.Text     = listName;
                SavedList.Checked = true;
            }

            else if (tok == "BETWEEN")
            {
                tok1            = CompoundId.Format(tok1);
                CidLo.Text      = tok1;
                tok3            = CompoundId.Format(tok3);
                CidHi.Text      = tok3;
                Between.Checked = true;
            }
        }
Exemple #10
0
        private void OK_Click(object sender, EventArgs e)
        {
            int    CnCount;
            string listName, listText, errMsg = "", tok, cidLo, cidHi, cid = null, cid2 = null;

            QueryColumn qc = Qc;
            MetaColumn  mc = qc.MetaColumn;
            MetaTable   mt = mc.MetaTable;

            // Perform validity check on form

            // Equality

            if (EQ.Checked)
            {
                tok = Cid.Text.ToUpper();

                if (tok == "")
                {
                    XtraMessageBox.Show("Single compound value is missing", UmlautMobius.String, MessageBoxButtons.OK, MessageBoxIcon.None);
                    Cid.Focus();
                    return;
                }

                if (SS.I.ValidateCompoundIds)
                {
                    if (tok == "")
                    {
                        errMsg = "You must supply a " + qc.ActiveLabel;
                    }

                    else if (RootTable.IsStructureDatabaseRootTable(mt.Root))
                    {
                        if (!CompoundId.IsValidForDatabase(tok, mt))
                        {
                            errMsg = tok + " is not a valid " + qc.ActiveLabel;
                        }

                        else
                        {
                            cid    = CompoundId.Normalize(tok, mt);
                            tok    = CompoundId.Format(cid, mt);
                            errMsg = "";
                        }
                    }

                    else
                    {
                        cid    = tok;                      // use as is
                        errMsg = "";                       // no error
                    }

                    if (errMsg != "")
                    {
                        MessageBoxMx.Show(errMsg, UmlautMobius.String, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                }
                qc.CriteriaDisplay = "= " + tok;
                qc.Criteria        = mc.Name + " = " + Lex.AddSingleQuotes(cid);
                CnCount            = 1;
            }

// List

            else if (InList.Checked)
            {
                listText = CidListString.Trim();
                if (listText == "")
                {
                    XtraMessageBox.Show("The list must contain one or more items", UmlautMobius.String, MessageBoxButtons.OK, MessageBoxIcon.None);
                    if (CidListDisplayIsEditable())
                    {
                        CidListDisplay.Focus();
                    }
                    return;
                }

                qc.CriteriaDisplay = CidList.FormatAbbreviatedCidListForDisplay(qc, listText);

                qc.Criteria = mc.Name + " IN (" + listText + ")";
            }

// Current list

            else if (TempList.Checked)
            {
                qc.CriteriaDisplay = "In temporary list: " + TempListName.Text;
                qc.Criteria        = mc.Name + " IN LIST " + UserObject.TempFolderNameQualified + TempListName.Text;
                CnCount            = SessionManager.CurrentResultKeysCount;
            }

// Saved list

            else if (SavedList.Checked)
            {
                if (ListName.Text.Trim() == "")
                {
                    XtraMessageBox.Show("A list name must be supplied", UmlautMobius.String, MessageBoxButtons.OK, MessageBoxIcon.None);
                    ListName.Focus();
                    return;
                }

                string internalName = ResolveSavedListUo();
                if (internalName == null)
                {
                    return;
                }

                qc.CriteriaDisplay = "In list: " + SavedListUo.Name;
                qc.Criteria        = mc.Name + " IN LIST " + Lex.AddSingleQuotes("CNLIST_" + SavedListUo.Id.ToString()); // quote list name
                CnCount            = 1;                                                                                  // may be larger
            }

// Between

            else if (Between.Checked)
            {
                cidLo = CidLo.Text.Trim();
                cidHi = CidHi.Text.Trim();
                if (cidLo == "" || cidHi == "")
                {
                    XtraMessageBox.Show("Between value is missing", UmlautMobius.String, MessageBoxButtons.OK, MessageBoxIcon.None);
                    if (CidLo.Text.Trim() == "")
                    {
                        CidLo.Focus();
                    }
                    else if (CidHi.Text.Trim() == "")
                    {
                        CidHi.Focus();
                    }
                    return;
                }

                if (SS.I.ValidateCompoundIds)
                {
                    errMsg = "";
                    if (cidLo == "")
                    {
                        errMsg = "You must supply a " + qc.ActiveLabel;
                    }

                    else
                    {
                        if (!CompoundId.IsValidForDatabase(cidLo, mt))
                        {
                            errMsg = cidLo + " is not a valid " + qc.ActiveLabel;
                        }
                        else
                        {
                            cid   = CompoundId.Normalize(cidLo, mt);
                            cidLo = CompoundId.Format(cid);
                        }
                    }
                    if (errMsg != "")
                    {
                        MessageBoxMx.Show(errMsg, UmlautMobius.String, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                }

                else
                {
                    cid = cidLo;                  // use as is
                }
                if (SS.I.ValidateCompoundIds)
                {
                    errMsg = "";
                    if (cidHi == "")
                    {
                        errMsg = "You must supply a " + qc.ActiveLabel;
                    }

                    else
                    {
                        if (!CompoundId.IsValidForDatabase(cidHi, mt))
                        {
                            errMsg = cidHi + " is not a valid " + qc.ActiveLabel;
                        }
                        else
                        {
                            cid2  = CompoundId.Normalize(cidHi, mt);
                            cidHi = CompoundId.Format(cid2);
                        }
                    }

                    if (errMsg != "")
                    {
                        MessageBoxMx.Show(errMsg, UmlautMobius.String, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                }

                else
                {
                    cid2 = cidHi;                  // use as is
                }
                qc.CriteriaDisplay = "Between " + cidLo + " and " + cidHi;
                qc.Criteria        = mc.Name + " BETWEEN " + Lex.AddSingleQuotes(cid) + " AND " + Lex.AddSingleQuotes(cid2);
            }

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

            DialogResult = DialogResult.OK;
//			this.Hide();
        }
Exemple #11
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;
        }
Exemple #12
0
        /// <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;
        }
Exemple #13
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);
            }
        }
Exemple #14
0
        /// <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);
        }