Exemple #1
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;
        }
Exemple #2
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);
        }
Exemple #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;
        }
Exemple #4
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);
        }
Exemple #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;
        }
Exemple #6
0
        static SasMapParms GetParmsFromQueryColumnCriteria(
            QueryColumn qc)
        {
            if (Lex.IsUndefined(qc.Criteria))
            {
                return(new SasMapParms());
            }

            ParsedSingleCriteria psc = ParsedSingleCriteria.Parse(qc);

            if (Lex.IsUndefined(psc.Value))
            {
                return(new SasMapParms());
            }

            SasMapParms smp = SasMapParms.Deserialize(psc.Value);

            if (smp != null)
            {
                return(smp);
            }

            else
            {
                return(new SasMapParms());
            }
        }
Exemple #7
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;
        }
Exemple #8
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);
        }
Exemple #9
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);
            }
        }
Exemple #10
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);
        }
Exemple #11
0
        /// <summary>
        /// Update table usage stats
        /// </summary>
        /// <param name="query"></param>

        public static void UpdateTableUsageStatistics(
            Query query)
        {
            int         count, ti, ci;
            QueryTable  qt;
            QueryColumn qc;

            if (SS.I.QueryTestMode)
            {
                return;                                 // don't do if test mode
            }
            for (ti = 0; ti < query.Tables.Count; ti++) // update table usage stats
            {
                qt = query.Tables[ti];
                string mtName = qt.MetaTable.Name;
                if (SS.I.TableUsageStatistics.ContainsKey(mtName))
                {
                    count = SS.I.TableUsageStatistics[mtName];
                }
                else
                {
                    count = 0;
                }
                SS.I.TableUsageStatistics[qt.MetaTable.Name] = count + 1;

                for (ci = 0; ci < qt.QueryColumns.Count; ci++)                 // count structure search types
                {
                    qc = qt.QueryColumns[ci];
                    if (qc.MetaColumn == null)
                    {
                        continue;
                    }
                    if (qc.MetaColumn.DataType != MetaColumnType.Structure)
                    {
                        continue;
                    }
                    if (qc.Criteria == "")
                    {
                        continue;
                    }

                    ParsedSingleCriteria psc = MqlUtil.ParseSingleCriteria(qc.Criteria);
                    if (psc != null && psc.Op != null && psc.Op.Length >= 1)
                    {
                        string txt = psc.Op;
                        if (!Char.IsLetter(txt[0]))
                        {
                            txt = "FSS " + txt;
                        }
                        else if (Lex.Eq(txt, "msimilar"))                         // include type of
                        {
                            int i1 = psc.Value2.IndexOf(" ");
                            if (i1 >= 0)
                            {
                                psc.Value2 = psc.Value2.Substring(0, i1);
                            }
                            txt += " " + psc.Value2;
                        }
                        txt = "StrSrch " + txt;
                        UsageDao.LogEvent(txt);
                    }
                }
            }
        }
Exemple #12
0
        /// <summary>
        /// Do setup in preparation for decompose
        /// </summary>
        /// <param name="qt"></param>
        /// <param name="q"></param>

        public void PrepareForDecompose(
            QueryTable qt,
            Query q)
        {
            throw new NotImplementedException();
#if false
            Stopwatch sw = Stopwatch.StartNew();

            MetaTable mt = qt.MetaTable;

            QueryColumn qc = qt.GetQueryColumnByName("core");
            if (qc == null)
            {
                throw new UserQueryException("Core column not defined in rgroup_decomposition table");
            }
            string molfile = qc.MolString;
            if (molfile == null || molfile == "")
            {             // core not defined in Rgroup decomposition table, try to get from structure search in rest of query
                foreach (QueryTable qt3 in q.Tables)
                {
                    if (!qt3.MetaTable.IsRootTable)
                    {
                        continue;
                    }
                    MetaColumn mc3 = qt3.MetaTable.FirstStructureMetaColumn;
                    if (mc3 != null)
                    {
                        QueryColumn qc3 = qt3.GetQueryColumnByName(mc3.Name);
                        molfile = qc3.MolString;
                        break;
                    }
                }
            }

            if (molfile == null || molfile == "")
            {
                throw new UserQueryException("R-group decomposition core structure is not defined");
            }

            bool allowHydrogenSubstituents = true;
            qc = qt.GetQueryColumnByName("AllowHydrogenSubstituents");
            if (Lex.Contains(qc?.Criteria, "'N'"))
            {
                allowHydrogenSubstituents = false;                                                // set to false if "no" criteria specified
            }
            TerminateOptionString = "First mapping";
            bool allowMultipleCoreMappings = false;

            qc = qt.GetQueryColumnByName("Terminate_Option");
            if (qc != null && qc.Criteria != "")
            {
                ParsedSingleCriteria psc = MqlUtil.ParseSingleCriteria(qc.Criteria);
                TerminateOptionString     = psc.Value;
                allowMultipleCoreMappings = Lex.Contains(TerminateOptionString, "All");
            }

            MoleculeMx cs = new MoleculeMx(MoleculeFormat.Molfile, molfile);
            cs.GetCoreRGroupInfo(out RgCounts, out RgTotalCount);             // need to redefine these

            RGroupDecomp.Initialize();

            RGroupDecomp.SetAlignStructuresToCore(true);
            RGroupDecomp.SetAllowMultipleCoreMappings(allowMultipleCoreMappings);
            RGroupDecomp.SetIncludeHydrogenFragments(allowHydrogenSubstituents);

            if (DebugMx.True)             // debug
            {
                String  coreSmiles = "[R1]c1cn2c3c(c1= O)cc(c(c3SC(C2)[R4])[R3])[R2]";
                string  coreChime  = "CYAAFQwAUewQeV58YHemfM^EQqPRfIYlJGEkx6M7e4db95jjK5HrNFVP2e1qHphWPL98KvcvrsF7bP9bRcW4QH$si9PXkkuwre6Q5UkHZjciQqeAKVLSHNAeQTAMlkiXEBD$BePpbNQCPD3BkklFEaQqwokeI$FwUoS5cAixQXkMbLTWDaAK7t7cOkSmt3RhwQedbrba6OHKBq3OF4Dhlz$0BfLeKCUUo8ixle176M2aIzXUccTOU8Xy8ARwE3bTyMfjuI3UunZceJf4iZELvsj3PX2MHZG73baUvQGS4DaxUaBGps81PPiDljfvxwFv8OfdOyIRlOBeuEAvk2rT9SRT6oMZIV6UtLFvmCHdwKnu9WtrfV1rEctydNUVxW4qKVlV0rZtpK1oZXuKcv6WVdl6r2hrjVLxBhblTVKO7w1qGRoziquOnPQkKd9H4EQfV0rP6mzI8Au8ulti2fu3YKB94lPXftPGbwr5yA";
                IMolLib coreMol    = MolLibFactory.NewMolLib(MoleculeFormat.Molfile, molfile);
                coreChime = MoleculeMx.MolfileStringToChimeString(molfile);
                molfile   = coreMol.MolfileString;
            }

            CoreMolecule = CdkMol.Util.MolfileStringToMolecule(molfile);
            RGroupDecomp.SetCoreStructure(CoreMolecule, false);

            CoreChemicalStructure = new MoleculeMx(MoleculeFormat.Molfile, molfile);
            StrMatcher            = null;

            int msTime = (int)sw.ElapsedMilliseconds;
            if (RGroupDecomp.Debug)
            {
                DebugLog.Message("Time(ms): " + msTime);
            }

            return;
#endif
        }
Exemple #13
0
        /// <summary>
        /// Invoke the editor
        /// </summary>
        /// <param name="qc">QueryColumn to edit</param>
        /// <returns></returns>

        public static bool Edit(
            QueryColumn qc)
        {
            ParsedSingleCriteria psc;

            if (qc.MetaColumn.DictionaryMultipleSelect)
            {
                return(CriteriaDictMultSelect.Edit(qc));
            }

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

            if (qc.Criteria != "")
            {
                psc = MqlUtil.ParseQueryColumnCriteria(qc);
            }

            else
            {
                psc        = new ParsedSingleCriteria();
                psc.OpEnum = CompareOp.FormulaEqual;
            }

            Instance.Formula.Text = psc.Value;
            if (psc.OpEnum == CompareOp.FormulaEqual)
            {
                Instance.ExactMF.Checked = true;
            }
            else
            {
                Instance.PartialMF.Checked = true;
            }

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

            if (dr == DialogResult.Cancel)
            {
                return(false);
            }

            string val = Instance.Formula.Text.Trim();

            if (val == "")             // no criteria
            {
                qc.Criteria = qc.CriteriaDisplay = "";
                return(true);
            }

            if (Instance.ExactMF.Checked)
            {
                qc.Criteria        = qc.MetaColumn.Name + " fmla_eq " + Lex.AddSingleQuotes(val);;
                qc.CriteriaDisplay = "= " + val;
            }

            else
            {
                qc.Criteria        = qc.MetaColumn.Name + " fmla_like " + Lex.AddSingleQuotes(val);
                qc.CriteriaDisplay = "like " + val;
            }

            return(true);
        }
Exemple #14
0
        public void Setup(ColumnInfo colInfo)
        {
            InSetup = true;

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

            Stats = colInfo.Rfld.GetStats();
            RangeFilter.Properties.Minimum = 0;
            RangeFilter.Properties.Maximum = Stats.DistinctValueList.Count - 1;

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

            TrackBarRange tbr = new TrackBarRange(0, Stats.DistinctValueList.Count - 1);

            RangeFilter.Value = tbr;

            if (psc != null && psc.OpEnum == CompareOp.Between && Stats.DistinctValueList.Count > 0)             // setup prev value
            {
                MetaColumnType type    = ColInfo.Mc.DataType;
                MobiusDataType lowVal  = MobiusDataType.New(type, psc.Value);
                MobiusDataType highVal = MobiusDataType.New(type, psc.Value2);
                if (MetaColumn.IsDecimalMetaColumnType(type))
                {                 // adjust decimal comparison values by an epsilon
                    double e = MobiusDataType.GetEpsilon(Stats.MaxValue.FormattedText);
                    lowVal.NumericValue  += e;
                    highVal.NumericValue -= e;
                }

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

                    if (mdt.CompareTo(lowVal) <= 0 || Lex.Eq(fTxt, psc.Value))
                    {
                        lowPos = i1;
                    }
                    else
                    {
                        break;
                    }
                }

                int highPos = -1;
                for (int i1 = Stats.DistinctValueList.Count - 1; i1 >= 0; i1--)
                {
                    MobiusDataType mdt  = Stats.DistinctValueList[i1];
                    string         fTxt = mdt.FormattedText;

                    if (mdt.CompareTo(highVal) >= 0 || Lex.Eq(fTxt, psc.Value2))
                    {
                        highPos = i1;
                    }
                    else
                    {
                        break;
                    }
                }

                if (lowPos >= 0 && highPos >= 0)
                {
                    tbr = new TrackBarRange(lowPos, highPos);
                    RangeFilter.Value = tbr;
                }
            }

            UpdateLabels();

            RangeFilter.Focus();
            InSetup = false;
            return;
        }
Exemple #15
0
        /// <summary>
        /// Transform basic query to select all data for a compound number
        /// </summary>
        /// <param name="keyMt">Key metatable. If null then try to determine from key value</param>
        /// <param name="cn"></param>
        /// <returns></returns>

        public static Query TransformSelectAllDataQuery(
            Query originalQuery,
            QueryTable qt0,
            Query newQuery)
        {
            Query        q2 = null;
            MetaTable    mt;
            MetaColumn   mc;
            QueryTable   qt;
            QueryColumn  qc;
            MetaTreeNode mtn, tn;

            qc = qt0.GetQueryColumnByNameWithException("root_table");
            ParsedSingleCriteria psc = MqlUtil.ParseQueryColumnCriteria(qc);

            if (psc == null || Lex.IsUndefined(psc.Value))
            {
                throw new UserQueryException("Root table not defined");
            }
            string keyMtName = psc.Value;

            psc = MqlUtil.ParseSingleCriteria("cid " + originalQuery.KeyCriteria);
            if (psc == null || Lex.IsUndefined(psc.Value))
            {
                throw new UserQueryException("Compound Id not defined");
            }
            string cn = psc.Value;

            MetaTable keyMt = null;

            if (Lex.IsDefined(keyMtName))
            {
                keyMt = MetaTableCollection.Get(keyMtName);
            }

            if (keyMt != null && keyMt.Root.IsUserDatabaseStructureTable) // if root metatable is user database then normalize based on key
            {
                keyMt = keyMt.Root;                                       // be sure we have root
                cn    = CompoundId.Normalize(cn, keyMt);
            }

            else
            {
                cn    = CompoundId.Normalize(cn);
                keyMt = CompoundId.GetRootMetaTableFromCid(cn, keyMt);
                keyMt = keyMt.Root;                 // be sure we have root (may not be structure table)
            }

            if (keyMt == null)
            {
                throw new Exception("Failed to identify key MetaTable");
            }

            string allTableName = keyMt.Name + "_AllData";             // see if specific all-data tree node

            mtn = MetaTree.GetNode(allTableName);
            if (mtn == null)             // no special "_AllData" node, lookup in menu
            {
                foreach (MetaTreeNode parent in MetaTree.Nodes.Values)
                {
                    foreach (MetaTreeNode child in parent.Nodes)
                    {
                        if (Lex.Eq(child.Target, keyMt.Name))
                        {
                            mtn = parent;
                            break;
                        }
                    }
                }

                IUserObjectTree iuot = InterfaceRefs.IUserObjectTree;
                if (mtn == null && keyMt.IsUserDatabaseStructureTable && iuot != null)                 // see if user structure table & db
                {
                    int          userObjId  = UserObject.ParseObjectIdFromInternalName(keyMt.Name);
                    string       nodeItemId = "ANNOTATION_" + userObjId;
                    MetaTreeNode childMtn   = iuot.GetUserObjectNodeBytarget(nodeItemId);
                    if (childMtn != null && childMtn.Parent.Type == MetaTreeNodeType.Database)
                    {
                        mtn = childMtn.Parent;
                    }
                }
            }

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

            Query q = newQuery;

            for (int i1 = 0; i1 < mtn.Nodes.Count; i1++)
            {
                tn = (MetaTreeNode)mtn.Nodes[i1];
                if (!tn.IsDataTableType)
                {
                    continue;
                }

                mt = MetaTableCollection.Get(tn.Target);
                if (mt == null)
                {
                    continue;
                }
                if (mt.Root.Name != keyMt.Name)
                {
                    continue;                                             // must have same root
                }
                if (mt.MultiPivot && !mt.UseSummarizedData && mt.SummarizedExists)
                {
                    MetaTable mt2 = MetaTableCollection.Get(mt.Name + MetaTable.SummarySuffix);
                    if (mt2 != null)
                    {
                        mt = mt2;
                    }
                }

                //if (mt.RemapForRetrieval && mt.SummarizedExists) mt.UseSummarizedData = true; // get summarized multipivot data (not good, permanently changes the metatable)

                qt = new QueryTable(mt);
                //				if (Lex.Eq(mt.Name, "all_star_pivoted") || Lex.Eq(mt.Name, "all_annotation_pivoted")) mt = mt // debug;

                if (qt.SelectedCount > 0)                 // be sure something is selected
                {
                    q.AddQueryTable(qt);
                }
            }

            // See if a model query exists & use it or append to what we have already

            string fileName = ServicesDirs.ModelQueriesDir + @"\" + allTableName + ".qry";

            if (!ServerFile.GetLastWriteTime(fileName).Equals(DateTime.MinValue))             // model query file exist?
            {
                try
                {
                    string query2String = FileUtil.ReadFile(fileName);
                    q2 = Query.Deserialize(query2String);
                    q.MergeSubqueries(q2);                     // just use subquery
                }
                catch (Exception ex) { ex = ex; }
            }

            q.SetupQueryPagesAndViews(ResultsViewType.HtmlTable);             // be sure we have a default page & HTML view

            // Set key criteria

            q.KeyCriteria = " = " + cn;

            // Review tables (debug)

            //int tCnt = q.Tables.Count;
            //string tls = q.TableListString;
            //q.Tables.RemoveRange(23, 1);
            //q.Tables.RemoveRange(27, q.Tables.Count - 27);
            //q.Tables.RemoveRange(1, 25);

            // Get list of any inaccessible tables & remove from query

            q.InaccessableData = CheckDataSourceAccessibility(q);

            if (q.InaccessableData != null)
            {
                foreach (string schema in q.InaccessableData.Keys)
                {
                    foreach (string tName in q.InaccessableData[schema])
                    {
                        qt = q.GetQueryTableByName(tName);
                        if (qt != null && !qt.MetaTable.IsRootTable && q.Tables.Contains(qt))
                        {
                            q.RemoveQueryTable(qt);
                        }
                    }
                }

                //ShowUnavailableDataMessage(q);
                q.InaccessableData = null;
            }

            UsageDao.LogEvent("QueryAllData", "");

            //string mql = MqlUtil.ConvertQueryToMql(q); // debug

            return(q);
        }
Exemple #16
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 #17
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);
            }
        }
Exemple #18
0
		/// <summary>
		/// Execute query
		/// </summary>
		/// <param name="eqp"></param>

		public override void ExecuteQuery(
				ExecuteQueryParms eqp)
		{
			MetaTable mt;
			MetaColumn mc;
			Query q;
			QueryTable qt;
			QueryColumn qc;
			ResultsPage rp;
			ResultsViewProps view;
			CompoundStructureActivityData cd1, cd2;

			bool smallerIsbetter;
			double r1, r2, r3, r4;
			int di, di2, pdi, pdi2, i3;
			string tok;

			qt = eqp.QueryTable;
			qc = qt.GetQueryColumnByNameWithException(SasMapParms.ParametersMetaColumnName);
			AssertMx.IsDefined(qc.Criteria, qc.Label + " criteria not defined");

			if (Lex.Eq(qc.Criteria, LastCriteriaString)) // if same criteria as last time then use existing data
			{
				VoListPos = -1; // init list position
				return;
			}

			VoList = new List<object[]>();
			VoListPos = -1; // init list position

			LastCriteriaString = qc.Criteria;
			ParsedSingleCriteria psc = ParsedSingleCriteria.Parse(qc);
			SMP = SasMapParms.Deserialize(psc.Value);

			mc = SMP.EndpointMc;
			smallerIsbetter = mc.MultiPoint;

			List<CompoundStructureActivityData> ds1 = ReadData(SMP); // read in the data to analyze
			if (ds1 == null || ds1.Count == 0) return; //  throw new QueryException("No data retrieved");

			List<CompoundStructureActivityData> ds2 = ds1; // just one set for now

			// Calculate difference or ratio coefficents for each pair

			List<PairData> pd = new List<PairData>();
			int minCoef = -1; // index of minimum coefficent selected so far
			double molFactor = AssayAttributes.GetMolarConcFactor(SMP.EndpointMc);

			for (di = 0; di < ds1.Count; di++)
			{ // process all compounds in 1st set
				//		if (ds1[di].Nearest == 0) continue; // any data?
				if (ds2 == ds1) di2 = di + 1; // only do lower rt diagonal if one dataset
				else di2 = 0; // must do all compares, check for dups later

				for ( /* start at di2 */; di2 < ds2.Count; di2++)
				{
					//			if (ds2[di2].Nearest == 0) continue; // any data?
					if (ds1[di].Cid == ds2[di2].Cid) continue; // avoid self compare

					double sim = // similarity
					 CalculateSimilarity(ds1[di], ds2[di2]);
					//if (sim==1.0 && !stereo) // eliminate stereo pairs if requested
					// continue; // a more careful check may be needed

					if (sim < SMP.MinimumSimilarity) continue; // below cutoff value?

					double denom = 1 - sim; // denominator is 1 - sim
					if (denom == 0) denom = .00000000001f; // avoid divide by zero

					double actChange = 0;

					if (smallerIsbetter && ds1[di].Activity < ds2[di2].Activity)
					{
						cd1 = ds1[di];
						cd2 = ds2[di2];
					}

					else
					{
						cd1 = ds2[di2];
						cd2 = ds1[di];
					}

					double a1 = cd1.Activity;
					double a2 = cd2.Activity;

					if (a1 == NullValue.NullNumber || a2 == NullValue.NullNumber)
						actChange = 0;

					else switch (SMP.ActDiffCalcType)
						{
							case ActDiffCalcType.SimpleDifference: // activity difference
								{
									actChange = a1 - a2;
									break;
								}

							case ActDiffCalcType.NegativeLog:
								{
									actChange = -Math.Log10(a1) - -Math.Log10(a2);
									break;
								}

							case ActDiffCalcType.MolarNegativeLog:
								{
									actChange = (-Math.Log10(a1 * molFactor)) - (-Math.Log10(a2 * molFactor));
									break;
								}

							case ActDiffCalcType.Ratio: // activity ratio
								{
									r1 = a1;
									if (r1 == 0) r1 = .00000000001f;
									r2 = a2;
									if (r2 == 0) r2 = .00000000001f;
									r3 = r1 / r2;
									r4 = r2 / r1;

									actChange = r3;
									if (SMP.UseAbsoluteValue && r4 > r3) // take the max value
										actChange = r4;

									break;
								}

							case ActDiffCalcType.Advanced:
								{
									throw new InvalidOperationException("SarMapCalcType.Advanced");
								}

							default:
								throw new InvalidOperationException("SarMapCalcType: " + (int)SMP.ActDiffCalcType);
						}

					if (SMP.UseAbsoluteValue && SMP.ActDiffCalcType != ActDiffCalcType.Ratio)
						actChange = Math.Abs(actChange);

					double coef = actChange / denom;

					if (pd.Count < SMP.MaxPairCount)  // just add this pair to end
					{
						pdi = pd.Count;
						pd.Add(new PairData());
					}

					else
					{ // see if this value is greater than anything in list
						if (minCoef < 0)
						{ // find element with minimum coef
							minCoef = 0;
							for (i3 = 1; i3 < pd.Count; i3++)
							{
								if (pd[i3].Coef < pd[minCoef].Coef)
									minCoef = i3;
							}
						}
						if (coef <= pd[minCoef].Coef) continue; // if this one better?

						//if (ds1 != ds2)
						//{ // be sure not a duplicate of what we have in list
						//	for (i3 = 0; i3 < pd.Count; i3++)
						//	{ // check for pair in list already
						//		if ((di == pd[i3].CD1 && di2 == pd[i3].CD2) ||
						//				(di == pd[i3].CD2 && di2 == pd[i3].CD1)) break;
						//	}
						//	if (i3 < pd.Count) continue; // continue to next pair if found
						//}

						pdi = minCoef; // replace this item
						minCoef = -1; // reset to get new minimum next time
					}

					// Save data for the pair

					pd[pdi].CD1 = cd1;
					pd[pdi].CD2 = cd2;
					pd[pdi].Sim = sim;
					pd[pdi].ActChange = actChange;
					pd[pdi].Coef = coef;
				}
			}

			// Build the list of pair Vos

			int voLen = qt.SetSimpleVoPositions();

			PairData pdItem;
			for (pdi = 1; pdi < pd.Count; pdi++) // sort from max to min coef value
			{
				pdItem = pd[pdi];
				for (pdi2 = pdi - 1; pdi2 >= 0; pdi2--)
				{
					if (pdItem.Coef < pd[pdi2].Coef) break;
					pd[pdi2 + 1] = pd[pdi2];
				}
				pd[pdi2 + 1] = pdItem;
			}

			for (pdi = 0; pdi < pd.Count; pdi++)
			{
				pdItem = pd[pdi];
				cd1 = pdItem.CD1;
				cd2 = pdItem.CD2;

				object[] vo = new object[voLen];

				VoArray.SetVo(qt, "PAIR_ID", vo, new NumberMx(pdi + 1));
				VoArray.SetVo(qt, "COMPOUND1", vo, new StringMx(cd1.Cid));
				VoArray.SetVo(qt, "STRUCTURE1", vo, cd1.Structure);
				VoArray.SetVo(qt, "ACTIVITY1", vo, new NumberMx(cd1.Activity));

				VoArray.SetVo(qt, "COMPOUND2", vo, new StringMx(cd2.Cid));
				VoArray.SetVo(qt, "STRUCTURE2", vo, cd2.Structure);
				VoArray.SetVo(qt, "ACTIVITY2", vo, new NumberMx(cd2.Activity));

				VoArray.SetVo(qt, "SIMILARITY", vo, new NumberMx(pdItem.Sim));
				VoArray.SetVo(qt, "ACTIVITY_DIFF", vo, new NumberMx(pdItem.ActChange));
				VoArray.SetVo(qt, "ACT_SIM_COEF", vo, new NumberMx(pdItem.Coef));

				VoList.Add(vo);
			}

			VoListPos = -1; // init list position
			return;
		}
Exemple #19
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;
        }
Exemple #20
0
        internal void SetupCheckedListBoxFromDictionary(
            string dictName,
            string criteria)
        {
            List <string> vList       = new List <string>();
            List <string> excludeList = new List <string>();

            List <string> dictWords;
            bool          itemChecked;

            SearchText.Text = "";

            dictWords = DictionaryMx.GetWords(dictName, false);
            if (dictWords == null)
            {
                throw new Exception("Dictionary not found: " + dictName);
            }

            Insetup = true;

            ParsedSingleCriteria psc = MqlUtil.ParseSingleCriteria(criteria);

            if (psc != null)
            {
                if (psc.ValueList != null)
                {
                    vList = psc.ValueList;
                }
                else if (!Lex.IsNullOrEmpty(psc.Value))
                {
                    vList.Add(psc.Value);
                }
            }
            HashSet <string> hashSet = new HashSet <string>(vList);

            CheckList.Items.Clear();
            int si = -1;

            foreach (string key in dictWords)
            {
                if (Lex.Eq(dictName, "STRUCTURE_DATABASES") && Lex.Eq(key, "UserDatabase"))
                {
                    continue;                     // special-case fix - generalize later
                }
                CheckedListBoxItem clbi = new CheckedListBoxItem();
                clbi.Description = key;
                if (hashSet.Contains(key))
                {
                    clbi.CheckState = CheckState.Checked;
                    if (si < 0)
                    {
                        si = CheckList.Items.Count;
                    }
                }
                else
                {
                    clbi.CheckState = CheckState.Unchecked;
                }
                CheckList.Items.Add(clbi);
            }

            if (si >= 0)
            {
                CheckList.SelectedIndex = si;
                CheckedListBoxItem clbi = CheckList.Items[si];
                SearchText.Text = clbi.Description;
            }

            SelectedItemText.Text        =
                SelectedItemText.ToolTip = GetCheckedListItems();

            Insetup = false;
            return;
        }
Exemple #21
0
        /// <summary>
        /// Fill the grid of col defs
        /// </summary>
        /// <param name="mt"></param>
        /// <returns></returns>

        void FillItemDataTable()
        {
            MetaTreeNode mtn;
            string       txt = "", tok, name, label;

            ItemGridDataTable.Rows.Clear();

            List <string>        vList = new List <string>();
            ParsedSingleCriteria psc   = MqlUtil.ParseSingleCriteria(Qc.Criteria);

            if (psc != null)
            {
                if (psc.ValueList != null)
                {
                    vList = psc.ValueList;
                }
                else if (!Lex.IsNullOrEmpty(psc.Value))
                {
                    vList.Add(psc.Value);
                }
            }

            MetaTable  mt          = Qc.MetaColumn.MetaTable;
            MetaColumn mc          = Qc.MetaColumn;
            string     mcDict      = mc.Dictionary;
            bool       searchId    = Lex.EndsWith(mcDict, ".Id");
            bool       searchLabel = Lex.EndsWith(mcDict, ".Label");

            for (int si = 0; si < vList.Count; si++)
            {
                string s = vList[si];
                if (Lex.IsUndefined(s))
                {
                    continue;
                }

                name = label = "";
                if (searchId)                 // assume numeric ASSAY code for metatable for now
                {
                    name = "ASSAY_" + s;
                    mtn  = MetaTree.GetNode(name);                    // try to look up by internal name
                }

                else
                {
                    label = s;
                    mtn   = MetaTree.GetNodeByLabel(label);
                }

                if (mtn != null)
                {
                    name  = mtn.Target;
                    label = mtn.Label;
                }

                DataRow dr = ItemGridDataTable.NewRow();
                dr["LabelColumn"]        = label;
                dr["InternalNameColumn"] = name;

                ItemGridDataTable.Rows.Add(dr);
            }

            return;
        }
Exemple #22
0
/// <summary>
/// Initial setup or change in operator
/// </summary>
/// <param name="compOp"></param>

        void Setup(CompareOp compOp)
        {
            string txt;

            InSetup = true;

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

            if (psc == null)
            {
                psc = new ParsedSingleCriteria();
                if (compOp == CompareOp.Unknown)
                {
                    compOp = CompareOp.Like;                                              // if no existing or supplied op use "like"
                }
            }
            else if (compOp == CompareOp.Unknown)
            {
                compOp = psc.OpEnum;                                               // if no existing but defined in criteria then use criteria
            }
            psc.OpEnum = compOp;

            CompOp = compOp;
            int ctls = 1;

            if (compOp == CompareOp.Like)
            {
                txt = ContainsMenuItem.Text;
            }
            else if (compOp == CompareOp.Eq)
            {
                txt = EqMenuItem.Text;
            }
            else if (compOp == CompareOp.Ne)
            {
                txt = NotEqMenuItem.Text;
            }
            else if (compOp == CompareOp.Lt)
            {
                txt = LtMenuItem.Text;
            }
            else if (compOp == CompareOp.Le)
            {
                txt = LeMenuItem.Text;
            }
            else if (compOp == CompareOp.Gt)
            {
                txt = GtMenuItem.Text;
            }
            else if (compOp == CompareOp.Ge)
            {
                txt = GeMenuItem.Text;
            }
            else if (compOp == CompareOp.Between)
            {
                txt = BetweenMenuItem.Text; ctls = 2;
            }
            else if (compOp == CompareOp.IsNull)
            {
                txt = IsBlankMenuItem.Text; ctls = 0;
            }
            else if (compOp == CompareOp.IsNotNull)
            {
                txt = IsNotBlankMenuItem.Text; ctls = 0;
            }
            else
            {             // in case of non-match
                CompOp = CompareOp.Like;
                txt    = ContainsMenuItem.Text;
            }

            if (ctls == 0)
            {
                Value.Visible = Value2.Visible = false;
            }

            else if (ctls == 1)
            {
                Value.Visible  = true;
                Value2.Visible = false;
                Value.Width    = (Width - 4) - Value.Left;
                Value.Text     = FormatCriteriaForDisplay(compOp, psc.Value);
            }

            else
            {
                Value.Visible = Value2.Visible = true;
                ResizeValueControls();
                Value.Text  = FormatCriteriaForDisplay(compOp, psc.Value);
                Value2.Text = FormatCriteriaForDisplay(compOp, psc.Value2);
            }

            OpButton.Text = txt;
            if (Value.Visible)
            {
                Value.Focus();
            }

            InSetup = false;
            return;
        }
Exemple #23
0
/// <summary>
/// Setup the form with existing criteria
/// </summary>
/// <param name="qc"></param>

        void Setup(
            QueryColumn qc)
        {
            string    op, tok, val;
            CheckEdit option    = null;
            CheckEdit subOption = null;
            int       i1;

            MetaColumn mc = qc.MetaColumn;

            string prompt = "Select the search criteria that you want to apply to " + qc.ActiveLabel +
                            " from the list below and enter the limiting value(s).";

            bool removeDuplicates = mc.IgnoreCase;                                                             // remove dups if ignoring case

            UIMisc.SetListControlItemsFromDictionary(Value.Properties.Items, mc.Dictionary, removeDuplicates); // setup dropdown

            switch (mc.DataType)
            {
            case MetaColumnType.Integer:
            case MetaColumnType.Number:
            case MetaColumnType.QualifiedNo:
                Setup(true, true, false, false);
                break;

            case MetaColumnType.String:
                Setup(true, true, true, false);
                break;

            case MetaColumnType.Date:
                prompt += " Dates can be entered in the common standard ways: e.g. 12/31/2004 or 31-Dec-04.";
                Setup(true, true, false, true);
                break;

            case MetaColumnType.DictionaryId:
                Setup(false, false, false, false);
                break;
            }

            // Fill in the form with the current criteria

            Instance.Text        = "Search Criteria for " + qc.ActiveLabel;
            Instance.Prompt.Text = prompt;

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

            if (psc == null)
            {             // create default values
                psc    = new ParsedSingleCriteria();
                psc.Op = "=";
            }

            if (mc.DataType == MetaColumnType.Date && psc.OpEnum != CompareOp.Within)             // format dates for user if not within clause
            {
                if (psc.Value != "")
                {
                    psc.Value = DateTimeMx.Format(psc.Value);
                }
                if (psc.Value2 != "")
                {
                    psc.Value2 = DateTimeMx.Format(psc.Value2);
                }
                if (psc.ValueList != null)
                {
                    for (i1 = 0; i1 < psc.ValueList.Count; i1++)
                    {
                        tok = (string)psc.ValueList[i1];
                        if (tok != null && tok != "")
                        {
                            psc.ValueList[i1] = DateTimeMx.Format(tok);
                        }
                    }
                }
            }

            else if (mc.DataType == MetaColumnType.DictionaryId && psc.Value != "")
            {             // transform database value to dictionary value
                val = DictionaryMx.LookupWordByDefinition(mc.Dictionary, psc.Value);
                if (val != null && val != "")
                {
                    psc.Value = val;
                }
            }

            op = psc.Op;

            // Fill fields based on criteria types

            if (op == "" || op.IndexOf("=") >= 0 || op.IndexOf("<") >= 0 || op.IndexOf(">") >= 0)
            {
                option = BasicOp;
                if (op == "=" || op == "")
                {
                    BasicOpBut.Text = "Equals";
                }
                else if (op == "<")
                {
                    BasicOpBut.Text = "<";
                }
                else if (op == "<=")
                {
                    BasicOpBut.Text = UnicodeString.LessOrEqual;
                }
                else if (op == "<>")
                {
                    BasicOpBut.Text = UnicodeString.NotEqual;
                }
                else if (op == ">")
                {
                    BasicOpBut.Text = ">";
                }
                else if (op == ">=")
                {
                    BasicOpBut.Text = UnicodeString.GreaterOrEqual;
                }

                Value.Text = psc.Value;                 // put in current value
            }

            else if (Lex.Eq(op, "Between"))
            {
                option      = Between;
                Limit1.Text = psc.Value;
                Limit2.Text = psc.Value2;
            }

            else if (Lex.Eq(op, "In"))
            {
                option = InList;
                StringBuilder sb = new StringBuilder();
                for (i1 = 0; i1 < psc.ValueList.Count; i1++)
                {
                    if (i1 > 0)
                    {
                        sb.Append(", ");
                    }
                    sb.Append((string)psc.ValueList[i1]);
                }
                ValueList.Text = sb.ToString();                 // set value
            }

            else if (Lex.Eq(op, "Like"))
            {
                option         = Like;
                tok            = psc.Value.Replace("%", "");      // remove sql wildcard characters
                Substring.Text = tok;
            }

            else if (Lex.Eq(op, "Within"))
            {
                option           = Within;
                WithinValue.Text = psc.Value;

                string value2 = psc.Value2;

                if (Lex.Contains(value2, "Day"))                 // translate alternative values
                {
                    value2 = "Day(s)";
                }
                else if (Lex.Contains(value2, "Week"))
                {
                    value2 = "Week(s)";
                }
                else if (Lex.Contains(value2, "Month"))
                {
                    value2 = "Month(s)";
                }
                else if (Lex.Contains(value2, "Year"))
                {
                    value2 = "Year(s)";
                }

                WithinUnits.Text = value2;
            }

            else if (Lex.Eq(op, "is not null"))
            {
                option = IsNotNull;
            }

            else if (Lex.Eq(op, "is null"))
            {
                option = IsNull;
            }

            else if (Lex.Eq(op, "is not null or is null"))
            {
                option = All;
            }

            else             // oops
            {
                MessageBoxMx.ShowError("Unrecognized criteria type");
                qc.Criteria = qc.CriteriaDisplay = "";
                return;
            }

            option.Checked = true;

            return;
        }