Exemple #1
0
/// <summary>
/// Initialize the Preview Query and associated QueryManager and Grid View
/// </summary>

        public void InitializeView()
        {
            if (SwQuery != null)
            {
                return;
            }

            SwQuery = BuildStructureSearchQuery();
            DataTableMx dt = DataTableManager.BuildDataTable(SwQuery);

            Qm = ToolHelper.SetupQueryManager(SwQuery, dt);

            MoleculeGridPageControl mgpc = MoleculeGridPageControl;

            ToolHelper.SetupGridPanelForDisplay(Qm, mgpc.MoleculeGridPanel);

            MoleculeGridControl grid = mgpc.MoleculeGrid;

            if (grid != null && grid.GV != null)
            {
                grid.GV.IndicatorWidth = 40;                 // narrow indicator col a bit
            }
            ClearDataAndGrid();

            return;
        }
Exemple #2
0
        /// <summary>
        /// Build the Query, QueryManager and DataTable for the matching structure display
        /// </summary>

        public void BuildStructureDisplayQuery()
        {
            MetaTable mt = MetaTableCollection.Get("QuickSearchRelatedStructures");

            if (mt == null)
            {
                DebugLog.Message("QuickSearchRelatedStructures MetaTable not found");
                RSC.MoleculeGridPageControl.Visible = false;
                return;
            }

            Query      q  = ToolHelper.InitEmbeddedDataToolQuery(mt);
            QueryTable qt = q.Tables[0];

            q.UserObject.Name     = qt.MetaTable.Label;
            StructureDisplayQuery = q;

            QueryColumn qc = qt.FirstStructureQueryColumn;

            if (qc != null)             // setup dummy criteria
            {
                ParsedStructureCriteria pssc = new ParsedStructureCriteria();
                pssc.SearchType = StructureSearchType.FullStructure;                 // just full structure search for now
                pssc.Molecule   = new MoleculeMx(MoleculeFormat.Smiles, "C");        // placeholder structure
                pssc.ConvertToQueryColumnCriteria(qc);

                qc.DisplayFormatString = "Highlight=true;Align=true";
            }

            string title = "Related Structures";

            qt.Label = title;

            DataTableMx dt = q.ResultsDataTable as DataTableMx;

            Qm = ToolHelper.SetupQueryManager(q, dt);

            MoleculeGridPageControl mgpc = RSC.MoleculeGridPageControl;
            MoleculeGridPanel       gp   = mgpc.MoleculeGridPanel;

            mgpc.Width  = RSC.Width - 3;            // be sure we have page control correctly sized
            mgpc.Height = RSC.Height - mgpc.Top - 3;

            ToolHelper.SetupGridPanelForDisplay(Qm, mgpc.MoleculeGridPanel, true, true);

            MoleculeGridControl grid = mgpc.MoleculeGrid;

            if (grid != null && grid.GV != null)
            {
                grid.GV.IndicatorWidth = 40;                 // narrow indicator a bit
            }
            //ToolHelper.DisplayData // build and display empty grid for query with columns scaled to fit the grid
            //		(q, dt, RSC.MoleculeGridPageControl.MoleculeGridPanel, true, true);

            return;
        }
Exemple #3
0
        private void DatabaseComboBox_Click(object sender, EventArgs e)
        {
            string response = ToolHelper.GetCheckedListBoxDialog("SmallWorldDatabases", DatabaseComboBox.Text, "SmallWorld databases");

            if (response != null)
            {
                DatabaseComboBox.Text = response;
                EditValueChanged();
            }
        }
Exemple #4
0
        public void ClearGrid()
        {
            DataTableMx dt = Qm.DataTable;

            dt.Clear();
            ToolHelper.RefreshDataDisplay(Qm);

            string title = "Related Structures";

            Qm.MoleculeGrid.SetTableHeaderCaption(0, title);

            return;
        }
Exemple #5
0
        /// <summary>
        /// Show dialog for initial view setup
        /// </summary>
        /// <returns></returns>

        public override DialogResult ShowInitialViewSetupDialog()
        {
            DialogResult dr;

            QueryColumn qc = null;

            if (SubQueryId < 0)
            {
                QueryViewSelectorDialog qvsd = new QueryViewSelectorDialog();
                qvsd.QuerySelectorControl.ShowCurrentQueryMenuItem = false;

                dr = qvsd.ShowDialog(this.SubQuery, "");
                if (dr == DialogResult.Cancel)
                {
                    return(DialogResult.Cancel);
                }

                SubQuery = qvsd.SelectedQuery;
                if (SubQuery == null)
                {
                    return(DialogResult.Cancel);
                }

                SubQuerySelectedView = qvsd.SelectedView;
                if (SubQuerySelectedView == null)
                {
                    return(DialogResult.Cancel);
                }

                SubQueryId             = SubQuery.UserObject.Id;
                SubQuerySelectedViewId = SubQuerySelectedView.Id;
            }

            if (SubQuerySelectedView == null)
            {
                RealizeSubQueryView();
            }
            if (SubQuerySelectedView == null)
            {
                return(DialogResult.Cancel);                                          // no view realized
            }
            string defaultViewTitle = ResultsViewProps.GetViewTypeLabel(SubQuerySelectedView.ViewType);

            // Setup done here, realization of query results and the view happens in ConfigureRenderingControl

            dr = ToolHelper.InvokeToolBasedInitialViewSetupDialog(SubQuery, BaseQuery);
            return(dr);
        }
Exemple #6
0
/// <summary>
/// ClearDataAndGrid
/// </summary>

        public void ClearDataAndGrid()
        {
            if (Qm == null || Qm.DataTable == null)
            {
                return;
            }

            DataTableMx dt = Qm.DataTable;

            dt.Clear();
            ToolHelper.RefreshDataDisplay(Qm);

            SearchStatusLabel.Appearance.ForeColor = Color.Black;
            SearchStatusLabel.Text = "Matching Structures: 0";

            //string title = "Matching Structures";
            //Qm.MoleculeGrid.SetTableHeaderCaption(0, title);
            return;
        }
Exemple #7
0
        /// <summary>
        /// Do Generic display of a list of structures
        /// </summary>
        /// <param name="title"></param>
        /// <param name="cidLabel"></param>
        /// <param name="structLabel"></param>
        /// <param name="structures"></param>

        public static void DisplayStructures(
            string title,
            string cidLabel,
            string structLabel,
            List <MoleculeMx> structures,
            MoleculeGridPanel gridPanel,
            bool embedDataInQuery)
        {
            QueryManager qm = null;

            MetaTable mt = MetaTableCollection.GetWithException("Generic_Structure_Table");

            mt.MetaBrokerType = MetaBrokerType.NoSql;

            Query      q  = ToolHelper.InitEmbeddedDataToolQuery(mt);
            QueryTable qt = q.Tables[0];

            qt.Label = title;
            qt.GetQueryColumnByName("CompoundId").Label = cidLabel;
            qt.GetQueryColumnByName("Structure").Label  = structLabel;

            DataTableMx dt = q.ResultsDataTable as DataTableMx;

            for (int mi = 0; mi < structures.Count; mi++)
            {
                MoleculeMx cs  = structures[mi];
                DataRowMx  dr  = dt.NewRow();
                string     cid = cs.Id;
                if (Lex.IsUndefined(cid))
                {
                    cid = (mi + 1).ToString();
                }
                dr[qt.Alias + ".CompoundId"] = new CompoundId(cid);
                dr[qt.Alias + ".Structure"]  = cs;
                dt.Rows.Add(dr);
            }

            DisplayData(q, dt, gridPanel, embedDataInQuery);

            return;
        }
Exemple #8
0
/// <summary>
/// If sim options are undefined then initialize with default values
/// </summary>
/// <param name="psc"></param>

        public static void InitSimOptionsIfUndefined(ParsedStructureCriteria psc)
        {
            if (psc.SimilarityType == SimilaritySearchType.Unknown)             // get any default if unknown
            {
                string simType, minSimTok, maxHitsTok;
                ToolHelper.GetDefaultSimMethod(out simType, out minSimTok, out maxHitsTok);

                psc.SimilarityType = SimilaritySearchType.Normal;
                try { psc.SimilarityType = (SimilaritySearchType)Enum.Parse(typeof(SimilaritySearchType), simType, true); }
                catch { }

                double.TryParse(minSimTok, out psc.MinimumSimilarity);
                int.TryParse(maxHitsTok, out psc.MaxSimHits);
            }

            if (psc.MinimumSimilarity > 10)
            {
                psc.MinimumSimilarity = psc.MinimumSimilarity / 10;                                         // convert 1-100 range to 0.0 - 1.0
            }
            if (psc.MinimumSimilarity < 0 || psc.MinimumSimilarity > 1.0)
            {
                psc.MinimumSimilarity = .75;
            }
        }
Exemple #9
0
/// Edit criteria for a query column
/// </summary>
/// <param name="qc"></param>
/// <returns>True if criteria has been successfully edited</returns>

        public static bool EditCriteria(
            QueryColumn qc)
        {
            MetaColumn mc    = qc.MetaColumn;
            Query      Query = qc.QueryTable.Query;
            bool       sameQ = Query == QueriesControl.Instance.CurrentQuery;       // debug

            if (Lex.Contains(qc.MetaColumn.ColumnMap, ToolUtil.ToolParametersColumnMapValue))
            {
                DialogResult dr = ToolHelper.InvokeToolCriteriaEditor(qc);
                return(dr == DialogResult.OK);
            }

            try
            {
                if (!mc.IsSearchable)
                {
                    MessageBoxMx.ShowError("The " + qc.ActiveLabel + " data item is not currently searchable.");
                    return(false);
                }

                if (mc.IsKey)                              // edit key criteria
                {
                    qc.CopyCriteriaFromQueryKeyCriteria(); // be sure qc is in sync with Query.KeyCriteria
                    if (!CriteriaCompoundId.Edit(qc))
                    {
                        return(false);
                    }

                    qc.CopyCriteriaToQueryKeyCritera();                     // update Query.KeyCriteria
                    return(true);
                }

                switch (mc.DataType)
                {
                // Compound Number criteria

                case MetaColumnType.CompoundId:

                    if (!CriteriaCompoundId.Edit(qc))
                    {
                        return(false);
                    }
                    else
                    {
                        break;
                    }

                // Structure criteria

                case MetaColumnType.Structure:
                    if (!CriteriaStructure.Edit(qc))
                    {
                        return(false);
                    }
                    break;

                // Mol. formula criteria

                case MetaColumnType.MolFormula:
                    if (!CriteriaMolFormula.Edit(qc))
                    {
                        return(false);
                    }
                    break;


                // General criteria

                case MetaColumnType.Integer:
                case MetaColumnType.Number:
                case MetaColumnType.QualifiedNo:
                case MetaColumnType.String:
                case MetaColumnType.Date:
                case MetaColumnType.DictionaryId:

                    if (!CriteriaDialog.Edit(qc))
                    {
                        return(false);
                    }
                    else
                    {
                        break;
                    }

                default:
                    MessageBoxMx.ShowError("The " + qc.ActiveLabel + " data item is not currently searchable.");
                    return(false);
                }

                return(true);
            }

            catch (Exception ex)
            {
                string msg = "Unexpected error editing criteria: \r\n\r\n" +
                             DebugLog.FormatExceptionMessage(ex);
                ServicesLog.Message(msg);
                MessageBoxMx.ShowError(msg);
                return(false);
            }
        }
Exemple #10
0
        /// <summary>
        /// Create an annotation table from a DataTable
        /// </summary>
        /// <param name="fullyQualifiedName">Fully qualified name to assign to table</param>
        /// <param name="dataTable">DataTable containing table definition & data</param>
        /// <param name="showProgress">Display dialog box showing progress of creation</param>
        /// <returns>Internal name assigned to annotation table (ANNOTATION_12345)</returns>

        public static MetaTable CreateAnnotationTable(
            string fullyQualifiedName,
            DataTable dataTable,
            bool showProgress)
        {
            List <AnnotationVo> voList = new List <AnnotationVo>();
            AnnotationVo        avo;

            if (dataTable == null)
            {
                DebugMx.ArgException("DataTable is null");
            }
            if (dataTable.Columns.Count == 0)
            {
                DebugMx.ArgException("No DataColumns are defined");
            }
            if (dataTable.Columns[0].DataType != typeof(CompoundId))
            {
                DebugMx.ArgException("The first column must be of type CompoundId");
            }

            if (showProgress)
            {
                Progress.Show("Creating annotation table...");
            }

            AnnotationDao aDao = new AnnotationDao();
            UserObject    auo  = UserObjectUtil.ParseInternalUserObjectName(fullyQualifiedName);

            auo.Type = UserObjectType.Annotation;
            UserObjectTree.GetValidUserObjectTypeFolder(auo);
            UserObject auo2  = UserObjectDao.Read(auo);            // see if there already
            MetaTable  oldMt = null;

            if (auo2 == null)                       // get new identifier
            {
                auo.Id = UserObjectDao.GetNextId(); // id to store table under
            }
            else                                    // reuse identifier
            {
                auo.Id = auo2.Id;                   // copy it over
                aDao.DeleteTable(auo.Id);           // delete any existing data
                string oldMtName = "ANNOTATION_" + auo2.Id;
                oldMt = MetaTableCollection.Get(oldMtName);
            }

            MetaTable mt = new MetaTable();

            mt.MetaBrokerType = MetaBrokerType.Annotation;
            mt.Name           = "ANNOTATION_" + auo.Id; // name table by uo
            mt.Label          = auo.Name;
            mt.Code           = auo.Id.ToString();      // code for the metatable
            int mtCode = auo.Id;

            if (dataTable.ExtendedProperties.ContainsKey("ParentTableName"))
            {
                mt.Parent = MetaTableCollection.Get((string)dataTable.ExtendedProperties["ParentTableName"]);
            }

            foreach (DataColumn dc in dataTable.Columns)
            {
                MetaColumn mc = new MetaColumn();
                mc.MetaTable = mt;
                mc.Name      = dc.ColumnName;
                MetaColumn oldMc = null;
                if (oldMt != null)
                {
                    oldMc = oldMt.GetMetaColumnByName(mc.Name);              // see if column name exists
                }
                if (oldMc != null && oldMc.ResultCode != "")                 // use any existing code
                {
                    mc.ResultCode = oldMc.ResultCode;
                }
                else
                {
                    mc.ResultCode = aDao.GetNextIdLong().ToString();
                }

                if (dc.Caption != null)
                {
                    mc.Label = dc.Caption;
                }
                else
                {
                    mc.Label = mc.Name;
                }
                if (dc.DataType == typeof(CompoundId))
                {
                    mc.DataType = MetaColumnType.CompoundId;
                    if (dc.ExtendedProperties.ContainsKey("StorageType") && dc.ExtendedProperties["StorageType"] is MetaColumnType &&
                        ((MetaColumnType)dc.ExtendedProperties["StorageType"]) == MetaColumnType.String)
                    {
                        mc.ColumnMap = "EXT_CMPND_ID_TXT";                         // text column
                    }
                    else
                    {
                        mc.ColumnMap = "EXT_CMPND_ID_NBR";                      // numeric column otherwise
                    }
                }
                else if (dc.DataType == typeof(int) || dc.DataType == typeof(Int16) || dc.DataType == typeof(Int32))
                {
                    mc.DataType = MetaColumnType.Integer;
                }
                else if (dc.DataType == typeof(float) || dc.DataType == typeof(double))
                {
                    mc.DataType = MetaColumnType.Number;
                }
                else if (dc.DataType == typeof(QualifiedNumber))
                {
                    mc.DataType = MetaColumnType.QualifiedNo;
                }
                else if (dc.DataType == typeof(string))
                {
                    mc.DataType = MetaColumnType.String;
                }
                else if (dc.DataType == typeof(DateTime))
                {
                    mc.DataType = MetaColumnType.Date;
                }
                else if (dc.DataType == typeof(MoleculeMx))
                {
                    mc.DataType = MetaColumnType.Structure;
                }
                else
                {
                    throw new Exception("Invalid data type " + dc.DataType.ToString());
                }

                if (dc.ExtendedProperties.ContainsKey("DisplayLevel"))
                {
                    mc.InitialSelection = (ColumnSelectionEnum)dc.ExtendedProperties["DisplayLevel"];
                }
                if (dc.ExtendedProperties.ContainsKey("DisplayWidth"))
                {
                    mc.Width = (float)dc.ExtendedProperties["DisplayWidth"];
                }
                if (dc.ExtendedProperties.ContainsKey("DisplayFormat"))
                {
                    mc.Format = (ColumnFormatEnum)dc.ExtendedProperties["DisplayFormat"];
                }
                if (dc.ExtendedProperties.ContainsKey("Decimals"))
                {
                    mc.Decimals = (int)dc.ExtendedProperties["Decimals"];
                }

                mt.MetaColumns.Add(mc);
            }

            ToolHelper.CreateAnnotationTable(mt, auo);

            aDao.BeginTransaction();             // insert all data in single transaction

            if (showProgress)
            {
                Progress.Show("Writing data to annotation table...");
            }
            int t1         = TimeOfDay.Milliseconds();
            int writeCount = 0;

            foreach (DataRow dr in dataTable.Rows)
            {
                if (dr.IsNull(0))
                {
                    continue;                               // shouldn't happen
                }
                string key = dr[0].ToString();
                key = CompoundId.NormalizeForDatabase(key, mt.Root);
                long rslt_grp_id = aDao.GetNextIdLong();

                for (int ci = 1; ci < dataTable.Columns.Count; ci++)                 // do columns after key
                {
                    if (dr.IsNull(ci))
                    {
                        continue;
                    }
                    DataColumn dc     = dataTable.Columns[ci];
                    MetaColumn mc     = mt.MetaColumns[ci];
                    int        mcCode = Int32.Parse(mc.ResultCode);
                    avo             = new AnnotationVo();
                    avo.rslt_grp_id = rslt_grp_id;                     // keep row together

                    if (dc.DataType == typeof(CompoundId))             // shouldn't happen since key processed already
                    {
                        avo.rslt_val_txt = dr[ci].ToString();
                    }

                    else if (dc.DataType == typeof(int) || dc.DataType == typeof(Int16) || dc.DataType == typeof(Int32) ||
                             dc.DataType == typeof(float) || dc.DataType == typeof(double))
                    {
                        avo.rslt_val_nbr = (double)dr[ci];
                    }

                    else if (dc.DataType == typeof(QualifiedNumber))
                    {
                        QualifiedNumber qn = (QualifiedNumber)dr[ci];
                        avo.rslt_val_nbr      = qn.NumberValue;
                        avo.rslt_val_prfx_txt = qn.Qualifier;
                        avo.rslt_val_txt      = qn.TextValue;
                        avo.dc_lnk            = qn.Hyperlink;
                    }

                    else if (dc.DataType == typeof(string))
                    {
                        avo.rslt_val_txt = dr[ci].ToString();
                    }

                    else if (dc.DataType == typeof(DateTime))
                    {
                        avo.rslt_val_dt = (DateTime)dr[ci];
                    }

                    else if (dc.DataType == typeof(MoleculeMx))
                    {
                        avo.rslt_val_txt = dr[ci].ToString();
                    }

                    AddAnnotationVoToList(avo, key, mtCode, mcCode, voList);
                }

                writeCount++;

                if (Progress.CancelRequested)                 // check for cancel
                {
                    aDao.Commit();
                    aDao.Insert(voList);
                    voList.Clear();
                    aDao.Commit();
                    aDao.Dispose();
                    if (showProgress)
                    {
                        Progress.Hide();
                    }
                    MessageBoxMx.ShowError("Writing of annotation table cancelled.");
                    return(null);
                }

                int t2 = TimeOfDay.Milliseconds();
                if (showProgress && t2 - t1 >= 1000)
                {
                    t1 = t2;
                    Progress.Show("Writing data to annotation table " + writeCount.ToString() +
                                  " of " + dataTable.Rows.Count.ToString() + " ...");
                    aDao.Insert(voList);
                    voList.Clear();
                    aDao.Commit();
                }
            }

            aDao.Insert(voList);
            voList.Clear();
            aDao.Commit();
            aDao.Dispose();

            if (showProgress)
            {
                Progress.Hide();
            }
            return(mt);            // return metatable name
        }
Exemple #11
0
        /// <summary>
        /// Update the match counts panel and structure view based on a set of structures and filter values
        /// </summary>
        /// <param name="excludeCurrentHitList"></param>
        /// <param name="rssrs"></param>

        public void DisplayRelatedStructures(
            List <StructSearchMatch> fml)
        {
            MoleculeMx cs;

            if (fml == null || fml.Count == 0)
            {
                DisplayEmptyStructureGrid();
                return;
            }

            if (StructureDisplayQuery == null)
            {
                BuildStructureDisplayQuery();                                            // initial setup
            }
            Query               q    = StructureDisplayQuery;
            QueryTable          qt   = q.Tables[0];
            DataTableMx         dt   = Qm.DataTable;
            MoleculeGridControl grid = Qm.MoleculeGrid;

            grid.BeginUpdate();

            dt.Clear();             // filter table

            HashSet <string> cidSet = new HashSet <string>();

            for (int mi = 0; mi < fml.Count; mi++)             // build and add the rows to the datatable of structures
            {
                StructSearchMatch ssm = fml[mi];
                DataRowMx         dr  = dt.NewRow();
                dr[qt.Alias + ".CompoundId"] = ssm.SrcCid;

                cs = new MoleculeMx(ssm.MolStringFormat, ssm.MolString);
                if (Lex.IsDefined(ssm.SrcCid))
                {
                    cs.SetMolComments("CorpId=" + ssm.SrcCid);                    // Attach CorpId to Molfile so it will be rendered correctly
                }
                if (ssm.SearchType == StructureSearchType.SmallWorld && Lex.IsDefined(ssm.GraphicsString))
                {
                    cs.SvgString = ssm.GraphicsString;
                }

                dr[qt.Alias + ".Structure"]  = cs;
                dr[qt.Alias + ".MatchType"]  = ssm.SearchTypeName;
                dr[qt.Alias + ".MatchScore"] = ssm.MatchScore;
                dr[qt.Alias + ".Database"]   = ssm.SrcName;
                dt.Rows.Add(dr);

                cidSet.Add(ssm.SrcCid);
            }

            Qm.DataTableManager.InitializeRowAttributes();

            string title = "Related Structures - Matches: " + fml.Count + ", Compound Ids: " + cidSet.Count;

            Qm.MoleculeGrid.SetTableHeaderCaption(0, title);

            if (!RSC.MoleculeGridPageControl.Visible)
            {
                RSC.MoleculeGridPageControl.Visible = true;
            }

            grid.EndUpdate();
            ToolHelper.RefreshDataDisplay(Qm);

            return;
        }
Exemple #12
0
/// <summary>
/// Create and execute the drill down query
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>

        void BuildAndRunDrillDownQuery(object sender, PivotCellEventArgs e)
        {
            object o;

            PivotDrillDownDataSource ds = e.CreateDrillDownDataSource();

            if (ds.RowCount <= 0)
            {
                return;                               // no data
            }
            Query q2 = Qm.Query.Clone();

            q2.ShowGridCheckBoxes = false;

// Build name for drilldown from row and column fields values

            string txt = "";

            PivotGridField[] rf = e.GetRowFields();
            PivotGridField[] ca = e.GetColumnFields();
            Array.Resize(ref rf, rf.Length + ca.Length);
            Array.Copy(ca, 0, rf, rf.Length - ca.Length, ca.Length);

            foreach (PivotGridField f in rf)
            {
                o = e.GetFieldValue(f);
                if (o != null && o.ToString() != "")
                {
                    if (txt != "")
                    {
                        txt += ", ";
                    }
                    txt += o.ToString();
                }
            }

            if (e.ColumnValueType == PivotGridValueType.GrandTotal ||
                e.RowValueType == PivotGridValueType.GrandTotal)
            {
                txt += " Grand Total";
            }

            else if (e.ColumnValueType == PivotGridValueType.Total ||
                     e.RowValueType == PivotGridValueType.Total)
            {
                txt += " Total";
            }

            q2.UserObject.Name = txt;

// Create DataTable containing drill down data

            DataTableMx dt2 = DataTableManager.BuildDataTable(q2);

            for (int ri = 0; ri < ds.RowCount; ri++)
            {                                     // copy rows over
                DataRowMx dr2 = dt2.NewRow();
                object[]  vo  = dr2.ItemArrayRef; // get ref to the item array
                for (int ci = 0; ci < dt2.Columns.Count; ci++)
                {
                    //if (ci == 14) ci = ci; // debug
                    vo[ci] = ds.GetValue(ri, ci);                     // direct copy into ItemArray
                }

                dt2.Rows.Add(dr2);
            }

            QueryManager qm2 = ToolHelper.SetupQueryManager(q2, dt2);

            qm2.ResultsFormat.OutputFormContext = OutputFormContext.Popup;

            PopupGrid pug = new PopupGrid(qm2);

            MoleculeGridPanel.ConfigureAndShow(qm2, pug);
            return;
        }
Exemple #13
0
        /// <summary>
        /// Run Query & return any error message
        /// </summary>
        /// <param name="query"></param>
        /// <param name="rf"></param>
        /// <param name="browseExistingResults">If true browse existing results</param>
        /// <returns>Command command or an error message</command></returns>

        public static string RunQuery2(
            Query query,
            ResultsFormat rf,
            bool browseExistingResults = false)
        {
            QueryManager     qm = null;
            DataTableMx      dt;
            QueryTable       qt = null;
            QueryColumn      qc;
            MetaTable        mt;
            MetaColumn       mc;
            QueryExec        qex;
            ResultsFormatter rfmtr;
            Query            modifiedQuery = null;
            DialogResult     dr;
            bool             success;
            int ti, ci, count;

            if (query == null)
            {
                throw new Exception("Null Query");
            }


            qm = query.QueryManager as QueryManager;

            if (qm == null || !qm.ContainsRenderedResults())
            {
                browseExistingResults = false;
            }

            if (ToolHelper.IsOldToolQuery(query) && !browseExistingResults)
            {
                return(ToolHelper.RunOldToolQuery(query));
            }

            //if (query.FirstView == null)
            //{
            ResultsViewType tableViewType = ResultsViewType.Table;

            if (rf.OutputDestination == OutputDest.Html)
            {
                tableViewType = ResultsViewType.HtmlTable;
            }

            //}

            //CheckForConnectionLeaks(); // do routine check for connection leaks (disabled for now)

// Build/update the QueryManager as needed (including the QueryExec) if running the query rather than just browsing existing results

            if (!browseExistingResults)                       // initialize QueryManager
            {
                query.SetupQueryPagesAndViews(tableViewType); // adjust views as necessary to match query
                qm = BuildQueryManager(query, rf);
            }

// Attempt to display already retrieved data in memory or in cached results file

            else
            {
                if (qm != null)
                {
                    if (qm.QueryExec == null)                     // create QueryExec if not defined
                    {
                        qex = new QueryExec(qm);
                    }

                    if (qm.ResultsFormatter == null)                     // create ResultsFormatter if not defined
                    {
                        rfmtr = new ResultsFormatter(qm);
                    }
                }

                else
                {
                    qm = BuildQueryManager(query, rf);
                }

                if (Lex.IsDefined(query.ResultsDataTableFileName))                 // get data from file
                {
                    DataTableManager.LoadDataTableFromFile(query);
                }

                else                 // should have data in DataTable already
                {
                    DataTableManager.ValidateExistingDataTable(query);
                }

                if (qm.DataTableManager != null && qm.QueryExec != null)
                {
                    qm.QueryExec.ResultsKeys = qm.DataTableManager.ResultsKeys;                     // have data in memory already
                }
            }

            if (rf.OutputDestination == OutputDest.WinForms && rf.SessionOutputFormContext)
            {                                                       // save qm and query if this is a runquery from the main window
                QueriesControl.Instance.CurrentBrowseQuery = query; // save ref to the query being browsed
            }

            if (rf.SessionOutputFormContext)             // if not a popup then update main status bar
            {
                qm.StatusBarManager = SessionManager.Instance.StatusBarManager;
            }

            LastQEx = qm.QueryExec;             // keep track of last QueryExec

SetupRunQuery:

            bool saveHitList = (rf.SessionOutputFormContext && !browseExistingResults);             // if popup or browsing existing results don't change hitlist

            qex = qm.QueryExec;
            string response = qex.RunQuery3(rf, saveHitList, browseExistingResults); // run the query

            if (qex.ResultsKeys != null && qex.ResultsKeys.Count > 0 &&              // save in history list if normal query that resulted in hits
                !query.Preview && !MqlUtil.SingleStepExecution(query) && !browseExistingResults &&
                rf.OutputDestination == OutputDest.WinForms)
            {
                CidList keyList = new CidList(qex.ResultsKeys);
                AddToHistoryList(query, keyList);                 // use original query
            }

            if (response != "" && !response.ToLower().StartsWith("command"))
            {
                return(response);
            }

            else if (Lex.EndsWith(response, "refetch")) // data to be retrieved has changed, redo fetch part of query
            {
                if (!query.Preview)                     // use current keys if not preview
                {
                    query.ResultKeys = qex.QueryEngine.GetKeys();
                }
                goto SetupRunQuery;
            }

            //else if (response == "") response = "Command EditQuery";

            //if (rf.OutputDestination == OutputDest.Grid)
            //{
            //  QbUtil.SetMode(QueryMode.Build); // back to build mode
            //  QbUtil.RenderQuery(QbUtil.Qt);
            //}

            return(response);
        }