/// <summary> /// Setup subquery with and QueryManger and execute the search step with the proper set of results keys from the parent query /// </summary> /// <param name="sq"></param> /// <param name="view"></param> /// <returns></returns> QueryManager SetupAndExecuteSecondaryQuery( Query sq, ResultsViewProps view) { //sq.ResultKeys = Qm.DataTableManager.ResultsKeys; //sq.UseResultKeys = true; QueryEngine qe = new QueryEngine(); Query nq; List <string> resultKeys = qe.TransformAndExecuteQuery(sq, out nq); if (nq != null) { sq = nq; // if modified then replace original query and QE with the new ones } QueryManager sqm = new QueryManager(); OutputDest outputDest = OutputDest.WinForms; QueryExec.InitializeQueryManager(sqm, sq, outputDest, qe, resultKeys); DataTableManager dtm = sqm.DataTableManager; sqm.QueryResultsControl = Qrc; // same query results control as us //sq.Parent = Qm.Query; // set parent of subQuery; return(sqm); }
/// <summary> /// Free resources linked to this instance /// </summary> public void Dispose() { try { DisposeOfControls(); if (Query != null) { Query.FreeControlReferences(); // just free control references } if (MoleculeGrid != null) { MoleculeGrid.Dispose(); } if (QueryEngine != null) { QueryEngine.Dispose(); } if (DataTableManager != null) { DataTableManager.Dispose(); } if (ResultsFormat != null) { ResultsFormat.QueryManager = null; } if (ResultsFormatter != null) { ResultsFormatter.QueryManager = null; } if (StatusBarManager != null) { StatusBarManager.QueryManager = null; } if (QueryExec != null) { QueryExec.QueryManager = null; } QueryResultsControl = null; Query = null; DataTableManager = null; DataTable = null; ResultsFormat = null; ResultsFormatter = null; StatusBarManager = null; MoleculeGrid = null; QueryExec = null; QueryEngine = null; } catch (Exception ex) { DebugLog.Message(DebugLog.FormatExceptionMessage(ex)); } }
/// <summary> /// Select the specified tab (e.g. query) /// </summary> /// <param name="tabIndex"></param> public void SelectQuery(int queryIndex) { if (queryIndex >= DocumentList.Count) { return; // shouldn't happen } SS.I.UISetupLevel++; CurrentQueryIndex = queryIndex; Document doc = DocumentList[queryIndex]; CurrentQuery = (Query)doc.Content; // restore query Query q = CurrentQuery; if (q.PresearchDerivedQuery != null) // restore any browse query { CurrentBrowseQuery = q.PresearchDerivedQuery; } else { CurrentBrowseQuery = q; } Tabs.TabPages[CurrentQueryIndex].Text = q.UserObject.Name; // make sure tab title is correct SessionManager.SetShellTitle(q.UserObject.Name); // set main window title Tabs.SelectedTabPageIndex = queryIndex; // select the tab if not done yet SS.I.UISetupLevel--; if (q.Mode == QueryMode.Unknown || q.Mode == QueryMode.Build) { QbUtil.SetMode(QueryMode.Build); // check & adjust build mode details Qtc.Render(q); SessionManager.DisplayCurrentCount(); } else // reenter browse mode { QbUtil.SetMode(QueryMode.Browse); // check & adjust build mode details QueryExec.RunQuery(q, OutputDest.WinForms, OutputFormContext.Session, browseExistingResults: true); SessionManager.DisplayFilterCountsAndString(); } }
/// <summary> /// Build a QueryManager from the supplied Query and ResultsFormat /// </summary> /// <param name="query"></param> /// <param name="rf"></param> static QueryManager BuildQueryManager( Query query, ResultsFormat rf) { query.ClearQueryManagers(); // clear any existing managers QueryManager qm = new QueryManager(); QueryExec qex = new QueryExec(qm); qm.Initialize(query, rf, null, null); rf = qm.ResultsFormat; if (rf.Query.ResultsDataTable != null) // if existing DataTable use it { qm.DataTable = rf.Query.ResultsDataTable as DataTableMx; } return(qm); }
/// <summary> /// This method runs in a background process and exports data to the specified destination /// </summary> /// <param name="objectIdString">Id of UserObject containing run parameters in a serialized ResultsFormat</param> /// <param name="templateFileName">Name of template file to use</param> /// <param name="emailResultsHtml">If true then send email otherwise just return html</param> /// <returns></returns> public static string RunBackgroundExport( string objectIdString, string templateFileName, bool emailResultsHtml, out bool copiedToDestinationFile, int alertId = 0) { ResultsFormat rf; Query q; string msg = ""; int objId; //if (ClientState.IsDeveloper) //{ // ServicesLog.Message(SS.I.UserName + ": BackgrounExport Debug"); // //DataTableManager.AllowCaching = false; // DataTableManager.DebugBasics = true; // DataTableManager.DebugCaching = true; //} if (String.IsNullOrEmpty(templateFileName)) { templateFileName = "MobiusBackgroundExportEmailTemplate.htm"; } ServicesLog.Message("RunBackgroundExport started: UserObject id = " + objectIdString); string emailSubject = UmlautMobius.String + " background export results"; copiedToDestinationFile = false; try { if (!int.TryParse(objectIdString, out objId)) { throw new Exception("Invalid UserObjectId"); } UserObject uo = UserObjectDao.Read(objId); if (uo == null) { throw new Exception("UserObject not found"); } QueryManager qm = new QueryManager(); rf = ResultsFormat.Deserialize(uo.Content); if (rf == null) { throw new Exception("Failed to deserialize ResultsFormat"); } string clientFile = rf.OutputFileName; // ultimate file we want to go to rf.OutputFileName = GetServerFileName(rf, objId); // get file name to export to on server & use here temporarily qm.ResultsFormat = rf; rf.QueryManager = qm; q = QbUtil.ReadQuery(rf.QueryId); if (q == null) { throw new Exception("Failed to read query: " + rf.QueryId); } q.IncludeRootTableAsNeeded(); qm.Query = q; q.QueryManager = qm; emailSubject += " for query " + Lex.Dq(q.UserObject.Name); // include query name in subject ResultsFormatFactory rff = new ResultsFormatFactory(rf); rff.Build(); ResultsFormatter fmtr = new ResultsFormatter(qm); DataTableManager dtm = new DataTableManager(qm); dtm.BeginCaching(); // allow caching of DataTable dtm.PurgeDataTableWithoutWritingToCacheFile = true; // skip actual writing of cache since it won't be read back in qm.DataTableManager = dtm; qm.DataTable = DataTableManager.BuildDataTable(rf.Query); // build data table to receive data QueryExec qex = new QueryExec(rf); msg = qex.RunQuery3(rf, false, false); // do the export int compoundCount = 0; int rowCount = 0; QueryEngine qe = qex.QueryEngine; if (qe != null) { compoundCount = qm.DataTableManager.KeyCount; rowCount = qm.DataTableManager.TotalRowsTransferredToDataTable; // use this for accurate row count } dtm.EndCaching(); // close cache file (note: resets key/row counts) if (compoundCount <= 0 || rowCount <= 0) // any results { msg = "Query " + Lex.Dq(q.UserObject.Name) + " returned no results."; Email.Send( null, SS.I.UserInfo.EmailAddress, emailSubject, msg); return(msg); } if (ServerFile.CanWriteFileFromServiceAccount(clientFile)) { // copy to dest file if possible try { FileUtil.CopyFile(rf.OutputFileName, clientFile); copiedToDestinationFile = true; rf.OutputFileName = clientFile; } catch (Exception ex) { ServicesLog.Message("Error copying file from service account: " + clientFile + "\n" + DebugLog.FormatExceptionMessage(ex)); } } string viewCmd = "Retrieve Background Export " + uo.Id; msg = "RunBackgroundExport ended: UserObjectId = " + objectIdString; if (emailResultsHtml) { MailBackgroundExportResults( q, clientFile, rowCount, compoundCount, copiedToDestinationFile, viewCmd, SS.I.UserInfo.EmailAddress, emailSubject, templateFileName); ServicesLog.Message(msg); return(msg); } else // just fill in values & return { string html = ReadTemplateFile(templateFileName); html = SubstituteBackgroundExportParameters( html, "", rf.OutputFileName, rowCount, compoundCount, copiedToDestinationFile, viewCmd); ServicesLog.Message(msg); return(html); } } catch (Exception ex) { if (alertId > 0) { msg += "Alert: " + alertId + " "; } msg += "RunBackgroundExport exception: BackgroundExportId = " + objectIdString + ",\r\n" + DebugLog.FormatExceptionMessage(ex); Email.Send( null, SS.I.UserInfo.EmailAddress, emailSubject, msg); ServicesLog.Message(msg); return(msg); } }
/// <summary> /// Method to run query in background and save the results for later retrieval /// </summary> /// <param name="q"></param> /// <param name="emailSubject">Send email if defined</param> /// <param name="templateName"></param> /// <returns></returns> public static string RunBackgroundQuery( Query q, string emailSubject, string templateName) { ResultsFormat rf; QueryManager qm; DataTableManager dtm; string msg = "", html = "", resultsFileName; string viewCmd = "View Background Query Results"; bool notifyUserByEmail = !Lex.IsNullOrEmpty(emailSubject); try // execute the query & read in all results { QbUtil.AddQueryAndRender(q, false); // add it to the query builder q.BrowseSavedResultsUponOpen = false; // be sure query is run rather than using existing results msg = QueryExec.RunQuery(q, OutputDest.WinForms); qm = q.QueryManager as QueryManager; dtm = qm.DataTableManager; DialogResult dr = dtm.CompleteRetrieval(); } catch (Exception ex) // some exceptions are normal, e.g. no criteria, others may be bugs { msg = "RunQueryInBackground could not complete due to an unexpected exception: " + DebugLog.FormatExceptionMessage(ex); ServicesLog.Message(msg); if (notifyUserByEmail) { Email.Send(null, SS.I.UserInfo.EmailAddress, emailSubject, msg); } return(msg); } if (dtm.KeyCount == 0) { msg = "Query " + Lex.Dq(q.UserObject.Name) + " returned no results."; if (notifyUserByEmail) { Email.Send(null, SS.I.UserInfo.EmailAddress, emailSubject, msg); } return(msg); } try { resultsFileName = q.ResultsDataTableFileName; // see if name supplied in query if (Lex.IsNullOrEmpty(resultsFileName)) { resultsFileName = "Query_" + q.UserObject.Id + "_Results.bin"; } resultsFileName = ServicesIniFile.Read("BackgroundExportDirectory") + @"\" + resultsFileName; dtm.WriteBinaryResultsFile(resultsFileName); // write the file UserObject cidListUo = SaveBackgroundQueryResultsReferenceObject(qm, "BkgrndQry", resultsFileName); if (!Lex.IsNullOrEmpty(templateName)) { html = ReadTemplateFile(templateName); } if (notifyUserByEmail) { AlertUtil.MailResultsAvailableMessage( // send the mail q, dtm.KeyCount, SS.I.UserInfo.EmailAddress, emailSubject, viewCmd, cidListUo.Id, null, html); } else { html = SubstituteBackgroundExportParameters(html, "", "", dtm.RowCount, dtm.KeyCount, false, ""); return(html); // return the html } } catch (Exception ex) { msg = "Error sending background query results: " + DebugLog.FormatExceptionMessage(ex); ServicesLog.Message(msg); } return(msg); }
/////////////////////////////////////////////////////////////// ////////////////////// Event code ///////////////////////// /////////////////////////////////////////////////////////////// //private void FormattingButton_Click(object sender, EventArgs e) //{ // QueryColumn qc = TableControlPrototype.CurrentQc; // if (TableControlPrototype.CurrentQc == null) // { // MessageBoxMx.Show( // "Before using this button to define formatting for a field\r\n" + // "you must select the row in the grid corresponding to the field\r\n" + // "that you want to define formatting for.\r\n\r\n" + // "You can also define formatting for a field by clicking on\r\n" + // "one of the small arrows in the Data Field column.", // UmlautMobius.String, MessageBoxButtons.OK, MessageBoxIcon.Warning); // return; // } // QueryTableControl.SetupColumnFormattingContextMenu(TableControlPrototype.ColumnFormattingContextMenu, qc, TableControlPrototype.UseNamedCfMenuItem_Click); // TableControlPrototype.ColumnFormattingContextMenu.Show(FormattingButton, // new System.Drawing.Point(0, FormattingButton.Height)); //} // RunQuery click & dropdown menu item clicks private void RunQueryButton_Click(object sender, EventArgs e) { SessionManager.LogCommandUsage("QueryTablesRunQuery"); QueryExec.RunQuery(Query, OutputDest.WinForms); }
/// <summary> /// Link in QueryManager member /// </summary> /// <param name="m"></param> public void LinkMember(QueryExec m) { QueryExec = m; m.QueryManager = this; }
/// <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); }