/// <summary> /// If the file is a UNC name check to see if the services can write to it /// </summary> /// <param name="fileName"></param> public static DialogResult CanWriteFileFromServiceAccount( string fileName) { //if (DisplayedUncWarningMessage) return DialogResult.OK; if (!fileName.StartsWith(@"\\")) { return(DialogResult.OK); } ; Progress.Show("Checking Mobius background write privileges...", UmlautMobius.String, false); bool canWrite = ServerFile.CanWriteFileFromServiceAccount(fileName); Progress.Hide(); //canWrite = false; // debug if (canWrite) { return(DialogResult.OK); } DialogResult dr = MessageBoxMx.Show( "The specified file is in a shared Windows network folder.\n" + "Mobius can't currently perform a background export directly to this file.\n" + "However, if write access to this shared folder is granted to the <mobiusAccount>\n" + "account then Mobius will be able to export directly to the specified file.", "Mobius", MessageBoxButtons.OKCancel, MessageBoxIcon.Information); DisplayedUncWarningMessage = true; return(dr); }
/// <summary> /// Import a list /// </summary> /// <returns></returns> static string ImportList() { string filePath = SelectListFileDialog("List File to Import", ""); if (String.IsNullOrEmpty(filePath)) { return(""); } string fileName = Path.GetFileNameWithoutExtension(filePath); UserObject oListName = new UserObject(UserObjectType.CnList, SS.I.UserName, fileName); oListName = UserObjectSaveDialog.Show("Database List to Import Into", oListName); if (oListName == null) { return(""); } Progress.Show("Importing List..."); CidList list = CidList.ReadFromFile(filePath); // read file list Write(list, oListName); // write database list Progress.Hide(); return(list.Count.ToString() + " " + MetaTable.KeyMetaTable.KeyMetaColumn.Label + "s have been imported"); }
/// <summary> /// Run query using supplied OutputDest displaying any error message /// </summary> /// <param name="query"></param> /// <param name="outputDest"></param> /// <returns></returns> public static string RunQuery( Query query, OutputDest outputDest) { try { bool browseExistingResults = QbUtil.BrowseExistingDataTable(query); return(RunQuery(query, outputDest, OutputFormContext.Session, null, browseExistingResults)); } catch (UserQueryException ex) { // just show message Progress.Hide(); MessageBoxMx.ShowError(ex.Message); return(""); } catch (Exception ex) { // non-standard query exception, provide more detail Progress.Hide(); string msg = DebugLog.FormatExceptionMessage(ex); if (!Lex.Contains(msg, "QueryLogged:")) // exception & query { QueryEngine.LogExceptionAndSerializedQuery(msg, query); } else { ServicesLog.Message(msg); // just log exception } MessageBoxMx.ShowError("Unexpected Exception\n\n" + msg); return(""); } }
/// <summary> /// Show with up to 4 custom buttons /// </summary> /// <param name="message"></param> /// <param name="caption"></param> /// <param name="button1"></param> /// <param name="button2"></param> /// <param name="button3"></param> /// <param name="button4"></param> /// <param name="icon"></param> /// <returns>Value of 1 - 4 corresponding to button pressed </returns> public static int ShowWithCustomButtons( string message, string caption, string button1, string button2, string button3, string button4, MessageBoxIcon icon, int width = -1, int height = -1) { if (!SS.I.Attended) { ClientLog.Message("Show: " + message); return((int)DialogResult.OK); } Progress.Hide(); // hide any progress message MessageBoxMx mb = new MessageBoxMx(); if (JupyterGuiConverter.ConversionsEnabled) { MessageBoxMx2 mb2 = new MessageBoxMx2(); new JupyterGuiConverter().ConvertFormOrUserControl(mb2); } int rc = mb.ShowInstance(message, caption, button1, button2, button3, button4, icon, width, height); return(rc); }
public void SetupQueryResultsControlForResultsDisplay( QueryManager qm) { Progress.Hide(); // hide any progress so popup gets focus //string title = qm.Query.UserObject.Name; //PopupResults pr = new PopupResults(); //UIMisc.PositionPopupForm(pr); //pr.Text = title; QueryResultsControl qrc = QueryResultsControl; qm.LinkMember(qrc); Query q = qm.Query; if (SetupQueryResultsControlMethod != null) { SetupQueryResultsControlMethod(); // let parent know that we're setting up the QueryResultsControl } qrc.BuildResultsPagesTabs(q); if (q.ResultsPages.Pages.Count <= 1) // hide tabs if only one { qrc.ResultsLabel.Visible = qrc.Tabs.Visible = false; } //qrc.ConfigureResultsPage(0); // render the first page qrc.SelectPage(q.InitialBrowsePage); // show the initial browse page }
/// <summary> /// Export a list /// </summary> /// <returns></returns> static string ExportList() { CidList list; UserObject iListName = SelectListDialog("Database List to Export"); if (iListName == null) { return(""); } string initialName = iListName.Name + ".lst"; string fileName = UIMisc.GetSaveAsFilename("List File to Export Into", initialName, "Lists (*.lst)|*.lst|All files (*.*)|*.*", "LST"); if (fileName == "") { return(""); } Progress.Show("Exporting List..."); list = Read(iListName); // read database list if (list == null) { return("Error reading list from database"); } list.WriteToFile(fileName, SS.I.RemoveLeadingZerosFromCids); // write file list Progress.Hide(); return(list.Count.ToString() + " " + MetaTable.KeyMetaTable.KeyMetaColumn.Label + "s have been exported"); }
/// <summary> /// Create document with status update & cancel allowed (gets cross-thread exception) /// </summary> void CreateDocument() { try { Progress.Show("Formatting preview...", "Mobius", true); ThreadStart ts = new ThreadStart(CreateDocumentThreadMethod); Thread newThread = new Thread(ts); newThread.IsBackground = true; newThread.SetApartmentState(ApartmentState.STA); newThread.Start(); while (true) { Thread.Sleep(10000); if (!Ps.Document.IsCreating) { break; } Progress.Show("Formatting preview page " + (Ps.Document.PageCount + 1).ToString() + "..."); if (Progress.CancelRequested) { Ps.ExecCommand(PrintingSystemCommand.StopPageBuilding); Thread.Sleep(250); break; } } Progress.Hide(); } catch (Exception ex) { ex = ex; } }
/// <summary> /// Show a message box and return result /// </summary> /// <param name="messageText"></param> /// <param name="titleCaption"></param> /// <param name="buttons"></param> /// <param name="icon"></param> /// <returns></returns> /// public static DialogResult Show( string messageText, string titleCaption, MessageBoxButtons buttons, MessageBoxIcon icon, int width = -1, int height = -1) { DialogResult dr = DialogResult.OK; if (!Lex.IsNullOrEmpty(ScriptLog.FileName)) { ScriptLog.Message("> " + messageText); } if (!SS.I.Attended) { ClientLog.Message("Show: " + messageText); return(DialogResult.OK); } else if (SS.I.QueryTestMode) { QueryTest.LogMessage("Show: " + messageText); return(DialogResult.OK); } //DebugLog.Message(messageText += "\r\n" + new StackTrace(true)); // debug where message is called from" Progress.Hide(); // hide any progress message if (Lex.Contains(messageText, "<br>")) // replace "<br>" with newlines { messageText = messageText.Replace("<br>", "\r\n"); } if (Lex.CountLines(messageText) > 5) { if (width <= 0) { width = 650; } if (height <= 0) { height = 400; } dr = ShowWithCustomSize(messageText, titleCaption, buttons, icon, width, height); return(dr); } if (messageText.Length > 72 && !messageText.Contains("\r") && !messageText.Contains("\n")) { messageText = WrapText(messageText, 6000); } //icon = MessageBoxIcon.Information; dr = XtraMessageBox.Show(messageText, titleCaption, buttons, icon); return(dr); }
/// <summary> /// Hide progress from thread other than the UI thread /// </summary> public static void InvokeHide() { Progress.Hide(); //if (Instance != null) //{ // Instance.Invoke(new ProgressDelegates.HideDelegate(Hide)); //} }
/// <summary> /// Show the specified query in a new PopupResults form /// </summary> /// <param name="qm"></param> /// <param name="html"></param> /// <param name="title"></param> public static void ShowHtml( // navigate browser to a document QueryManager qm, string html, string title) { string uri; int pi; Progress.Hide(); // hide any progress so popup gets focus uri = ClientDirs.TempDir + @"\PopupResults" + "1" + ".htm"; StreamWriter sw = new StreamWriter(uri); sw.Write(html); sw.Close(); PopupResults pr = new PopupResults(); UIMisc.PositionPopupForm(pr); pr.Text = title; QueryResultsControl qrc = pr.QueryResultsControl; qm.LinkMember(qrc); Query q = qm.Query; qrc.BuildResultsPagesTabs(q); for (pi = 0; pi < q.ResultsPages.Pages.Count; pi++) { ResultsPage page = q.ResultsPages.Pages[pi]; for (int vi = 0; vi < page.Views.Count; vi++) { ResultsViewProps view = page.Views[vi]; if (view.ViewType == ResultsViewType.HtmlTable) { view.Title = title; view.ContentUri = uri; // plug in file name for uri } } } pr.Show(); qrc.ConfigureResultsPage(0); // render the first page UIMisc.BringFormToFront(pr); return; }
/// <summary> /// Build a Spotfire view for the QueryTable in the current query /// </summary> /// <param name="args"></param> /// <returns></returns> public static string StoreSpotfireQueryTableSql() { string sqlStmtName = QbUtil.Query.UserObject.Name; if (Lex.StartsWith(sqlStmtName, "SF_")) // trim the sf prefix { sqlStmtName = sqlStmtName.Substring(3); } while (true) { sqlStmtName = InputBoxMx.Show("Name to assign to stored SQL:", "Store Mobius QueryTable SQL for Use by Spotfire", sqlStmtName); if (Lex.IsUndefined(sqlStmtName)) { return(""); } string existingSql = QueryEngine.ReadSpotfireSql(sqlStmtName, 0); if (Lex.IsDefined(existingSql)) { DialogResult dr = MessageBoxMx.Show( "Sql statement " + sqlStmtName + " already exists.\r\n" + "Do you want to overwrite it?", "Confirm Overwrite", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (dr == DialogResult.No) { continue; // allow name reentry } else if (dr == DialogResult.Cancel) { return(""); } } break; } Progress.Show("Saving SQL..."); int id = QueryEngine.SaveSpotfireSql(sqlStmtName, QbUtil.Query); Progress.Hide(); string msg = "Sql statement " + sqlStmtName + " has been stored."; return(msg); }
/// <summary> /// Show popup results in a results window /// </summary> /// <param name="qm"></param> /// <param name="title"></param> public static void Show( QueryManager qm) { string uri; int pi, posDelta = 20; Progress.Hide(); // hide any progress so popup gets focus string title = qm.Query.UserObject.Name; PopupResults pr = new PopupResults(); UIMisc.PositionPopupForm(pr); pr.Text = title; QueryResultsControl qrc = pr.QueryResultsControl; qm.LinkMember(qrc); Query q = qm.Query; qrc.BuildResultsPagesTabs(q); if (q.ResultsPages.Pages.Count <= 1) // hide tabs if only one { qrc.ResultsLabel.Visible = qrc.Tabs.Visible = false; } //qrc.ToolPanel.Visible = false; // hide tools for now (e.g. Edit Query) //if (q.ResultsPages.Pages.Count <= 1) // hide tabs if only one //{ // PanelControl pc = qrc.ResultsPagePanelContainer; // int delta = pc.Top; // pc.Top = 0; // pc.Height += delta; //} pr.Show(); //qrc.ConfigureResultsPage(0); // render the first page qrc.SelectPage(q.InitialBrowsePage); // show the initial browse page UIMisc.BringFormToFront(pr); return; }
/// <summary> /// Show error message & select token with error /// </summary> /// <param name="message"></param> /// <param name="pTok"></param> static void ConvertLabeledCriteriaError( string message, PositionedToken pTok, RichTextBox complexCriteriaCtl) { Progress.Hide(); if (complexCriteriaCtl != null) { complexCriteriaCtl.SelectionStart = pTok.Position; complexCriteriaCtl.SelectionLength = pTok.Text.Length; } MessageBoxMx.ShowError(message); if (complexCriteriaCtl != null) { complexCriteriaCtl.Focus(); } return; }
/// <summary> /// Build a Spotfire view for the QueryTable in the current query /// </summary> /// <param name="args"></param> /// <returns></returns> public static string BuildSpotfireQueryTableView(string viewName) { string initialViewName = viewName; if (Lex.IsUndefined(initialViewName)) { viewName = QbUtil.Query.UserObject.Name; } do { if (Lex.IsUndefined(initialViewName) || viewName.Length > 30) { viewName = InputBoxMx.Show("Name to assign to stored SQL:", "Build QueryTable SQL for Use by Spotfire", viewName); if (Lex.IsUndefined(viewName)) { return(""); } } }while (viewName.Length > 30); string serializedQuery = QbUtil.Query.Serialize(); string command = "BuildQueryTableOracleView " + viewName + " " + serializedQuery; Progress.Show("Executing Command..."); string result = CommandLine.ExecuteServiceCommand(command); Progress.Hide(); return(result); //QueryTable qt = QbUtil.Query.CurrentTable; //if (qt == null) return "No current QueryTable"; //Query q = new Query(); //qt = qt.Clone(); //q.AddQueryTable(qt); //string initialViewName = viewName; //if (Lex.IsUndefined(initialViewName)) // viewName = "SF_" + qt.MetaTable.Name; // default view name has SF prefix }
/// <summary> /// Display the grid of alerts & let user add, edit and cancel them. /// </summary> /// <returns></returns> public static string Show(string args) { List <UserObject> alerts; Alert alert = null; int alertId, queryId, row; string txt; string userid = SS.I.UserName; if (args == null || args == "") { Progress.Show("Retrieving alerts...", UmlautMobius.String, false); alerts = UserObjectDao.ReadMultiple(UserObjectType.Alert, SS.I.UserName, false, false); } else { if (!Security.IsAdministrator(SS.I.UserName)) { return("Only administrators can execute this command"); } Progress.Show("Retrieving alerts...", UmlautMobius.String, false); if (Lex.Eq(args, "All")) // all users { alerts = UserObjectDao.ReadMultiple(UserObjectType.Alert, false); } else // some other user { alerts = UserObjectDao.ReadMultiple(UserObjectType.Alert, args, false, false); } } AlertGridDialog Instance = new AlertGridDialog(); Instance.SetupGrid(alerts); Progress.Hide(); DialogResult dr = Instance.ShowDialog(SessionManager.ActiveForm); return(""); }
/// <summary> /// Navigate browser to an html popup form /// </summary> /// <param name="document">URI/UNC or document content</param> /// <param name="title">Title of document</param> public static void ShowHtmlPopupFormDocument( // navigate browser to a document string htmlOrUrl, string title) { string uri; Progress.Hide(); // hide any progress so popup gets focus //Thread.Sleep(100); // small time delay helps to keep popup on top //Application.DoEvents(); if (Lex.IsUri(htmlOrUrl) || htmlOrUrl.StartsWith(@"\\") || (htmlOrUrl.Length > 3 && htmlOrUrl.Substring(1, 2) == @":\")) { uri = htmlOrUrl; // html is the reference SystemUtil.StartProcess(uri); return; } else // write file to client & open { uri = ClientDirs.TempDir + @"\PopupHtml" + PopupCount + ".htm"; StreamWriter sw = new StreamWriter(uri); sw.Write(htmlOrUrl); sw.Close(); SS.I.BrowserPopup = new PopupHtml(); PopupHtml bp = SS.I.BrowserPopup; PositionPopupForm(bp); bp.Text = title; bp.Show(); bp.WebBrowser.Navigate(uri); return; } }
/// <summary> /// Build & show the Print Preview dialog /// </summary> /// <param name="printableDxControl"></param> /// <returns></returns> static DialogResult ShowDialog( IPrintable printableDxControl) { string leftColumn, middleColumn, rightColumn; int m; Query query = Instance.Qm.Query; int printScale = query.PrintScale; // scale the document if (printScale < 0 && !(Instance.Qm.MoleculeGrid.MainView is DevExpress.XtraGrid.Views.BandedGrid.BandedGridView)) { // if not banded view be sure not fit to width printScale = query.PrintScale = 100; } Instance.Qm.ResultsFormat.PageScale = printScale; // do view scaling based on printScale ResultsFormat rf = Instance.Qm.ResultsFormat; PrintingSystem ps = new PrintingSystem(); Instance.Ps = ps; Instance.PrintControl.PrintingSystem = ps; PrintableComponentLink pcl = new PrintableComponentLink(ps); Instance.Pcl = pcl; pcl.Component = printableDxControl; ps.Links.Add(pcl); pcl.CreateDetailArea += new CreateAreaEventHandler(Instance.PrintableComponentLink_CreateDetailArea); pcl.CreateDetailHeaderArea += new CreateAreaEventHandler(Instance.PrintableComponentLink_CreateDetailHeaderArea); pcl.CreateInnerPageHeaderArea += new CreateAreaEventHandler(Instance.PrintableComponentLink_InnerPageHeaderArea); pcl.CreateMarginalHeaderArea += new CreateAreaEventHandler(Instance.PrintableComponentLink_CreateMarginalHeaderArea); pcl.CreateReportHeaderArea += new CreateAreaEventHandler(Instance.PrintableComponentLink_CreateReportHeaderArea); if (query.PrintMargins > 0) { m = query.PrintMargins / 10; pcl.Margins = new Margins(m, m, m, m); } if (query.PrintOrientation == Orientation.Vertical) { pcl.Landscape = false; } else { pcl.Landscape = true; } PageHeaderFooter phf = pcl.PageHeaderFooter as PageHeaderFooter; phf.Header.Content.Clear(); middleColumn = rf.Query.UserObject.Name; // use query name for heading phf.Header.Content.AddRange(new string[] { "", middleColumn, "" }); phf.Header.LineAlignment = BrickAlignment.Center; phf.Header.Font = new Font("Arial", 10, FontStyle.Bold); leftColumn = "Mobius: " + DateTimeMx.Format(DateTimeMx.GetCurrentDate()); middleColumn = "Confidential"; rightColumn = "Page [Page #]"; phf.Footer.Content.Clear(); phf.Footer.Content.AddRange(new string[] { leftColumn, middleColumn, rightColumn }); phf.Footer.LineAlignment = BrickAlignment.Center; // Todo: If DataTable is big just use a subset for preview? Takes about 5 secs to format 100 structs. Instance.PreviewRowCount = Instance.Qm.DataTable.Rows.Count; Progress.Show("Formatting preview...", "Mobius", true); pcl.CreateDocument(); Progress.Hide(); if (printScale > 0) // scale to percentage { ps.Document.ScaleFactor = 1.0f; // keep document scale at 1.0 ps.Document.AutoFitToPagesWidth = 0; } else { Instance.Qm.MoleculeGrid.ScaleBandedGridView(100.0); // scale grid to full size before setting doc scale ps.Document.AutoFitToPagesWidth = (int)-printScale; // fit to 1 or more pages int pctScale = (int)(ps.Document.ScaleFactor * 100); Instance.Qm.ResultsFormat.PageScale = pctScale; Instance.Qm.MoleculeGrid.ScaleBandedGridView(pctScale / 100.0); // scale grid down to get structures correct size pcl.CreateDocument(); // recreate the doc } ps.StartPrint += new PrintDocumentEventHandler(Instance.PrintingSystem_StartPrint); ps.PrintProgress += new PrintProgressEventHandler(Instance.PrintingSystem_PrintProgress); ps.EndPrint += new EventHandler(Instance.PrintingSystem_EndPrint); ps.ShowPrintStatusDialog = true; Form shell = SessionManager.Instance.ShellForm; Instance.Location = shell.Location; Instance.Size = shell.Size; Instance.WindowState = shell.WindowState; RibbonControl src = SessionManager.Instance.RibbonCtl; // model this ribbon on shell ribbon if (src != null) { Instance.RibbonControl.RibbonStyle = src.RibbonStyle; Instance.RibbonControl.ApplicationIcon = src.ApplicationIcon; } DialogResult dr = Instance.ShowDialog(shell); // show the preview query.PrintMargins = pcl.Margins.Left * 10; // keep margins in milliinches if (pcl.Landscape) { query.PrintOrientation = Orientation.Horizontal; } else { query.PrintOrientation = Orientation.Vertical; } Progress.Hide(); // just in case return(dr); }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OkButton_Click(object sender, EventArgs e) { QueryTable qt; QueryColumn qc, qc2; MetaTable mt; string tName, tableLabel, selectedTableLabel = null, txt; bool b1; int ti, i1; // Get summarization & table position tab info ti = GetSelectedRow(); if (ti >= 0) { selectedTableLabel = (string)DataTable.Rows[ti]["TableNameCol"]; } List <QueryTable> newTables = new List <QueryTable>(); // build new query table list Query.Tables = newTables; // new set of reordered query tables for (i1 = 0; i1 < DataTable.Rows.Count; i1++) { tableLabel = (string)DataTable.Rows[i1]["TableNameCol"]; if (tableLabel == "") { continue; } qt = OriginalQueryTables[tableLabel]; // map text label back to query table if (qt == null) { continue; // shouldn't happen } object cs = DataTable.Rows[i1]["SummarizedCol"]; bool useSummarized = (cs is bool && (bool)cs == true); if ((useSummarized && !qt.MetaTable.UseSummarizedData) || // summary status change? (!useSummarized && qt.MetaTable.UseSummarizedData)) { qt = qt.AdjustSummarizationLevel(useSummarized); } //if (Query.GetQueryTableByName(qt.MetaTable.Name) != null) continue; // don't allow same table twice (comment out, multiples of same table allowed now) newTables.Add(qt); // no change to summary info qt.Query = Query; } if (Query.Tables.Count > 0 && ti < 0) { ti = 0; // in case nothing selected } // Get basic options if (DnfQc.DisplayFormat != ColumnFormatEnum.Unknown) // default number format changed? { SS.I.DefaultNumberFormat = DnfQc.DisplayFormat; Preferences.Set("DefaultNumberFormat", SS.I.DefaultNumberFormat.ToString()); SS.I.DefaultDecimals = DnfQc.Decimals; Preferences.Set("DefaultDecimals", SS.I.DefaultDecimals.ToString()); } txt = QnfStatsTextEdit.Text; Query.StatDisplayFormat = QbUtil.ConvertStatDisplayFormat(txt); if (SS.I.TableColumnZoom != TableColumnZoom.ZoomPct) { SS.I.TableColumnZoom = TableColumnZoom.ZoomPct; Preferences.Set("TableColumnZoom", TableColumnZoom.ZoomPct); } if (SS.I.GraphicsColumnZoom != GraphicsColumnZoom.ZoomPct) { SS.I.GraphicsColumnZoom = GraphicsColumnZoom.ZoomPct; Preferences.Set("GraphicsColumnZoom", GraphicsColumnZoom.ZoomPct); } // Advanced options - query specific Query.DuplicateKeyValues = DuplicateKeyValues.Checked; Query.FilterNullRows = FilterNullRows.Checked; Query.ShowCondFormatLabels = ShowCondFormatLabels.Checked; //Query.BrowseExistingResultsWhenOpened = BrowseExistingResultsWhenOpened.Checked; Query.RunQueryWhenOpened = RunQueryWhenOpened.Checked; Query.SingleStepExecution = CombineSearchAndRetrieval.Checked; //Query.UseCachedData = UseCachedData.Checked; Query.Multitable = Multitable.Checked; // (not visible) Query.Mobile = MobileQuery.Checked; //if (cbDefaultMobileQuery.Checked) Preferences.Set("MobileDefaultQuery",Query.UserObject.Id); // Advanced options - applies to all queries if (RestoreWindowsAtStartup.Checked != SS.I.RestoreWindowsAtStartup) { SS.I.RestoreWindowsAtStartup = !SS.I.RestoreWindowsAtStartup; Preferences.Set("RestoreWindowsAtStartup", SS.I.RestoreWindowsAtStartup); } if (HilightCorpIdChanges.Checked != SS.I.HilightCidChanges) { SS.I.HilightCidChanges = !SS.I.HilightCidChanges; Preferences.Set("HilightCorpIdChanges", SS.I.HilightCidChanges); } if (RemoveLeadingZerosFromCids.Checked != SS.I.RemoveLeadingZerosFromCids) { SS.I.RemoveLeadingZerosFromCids = !SS.I.RemoveLeadingZerosFromCids; Preferences.Set("RemoveLeadingZerosFromCids", SS.I.RemoveLeadingZerosFromCids); } if (RepeatReport.Checked != SS.I.RepeatReport) { SS.I.RepeatReport = !SS.I.RepeatReport; Preferences.Set("RepeatReport", SS.I.RepeatReport); } if (ShowStereoComments.Checked != SS.I.ShowStereoComments) { SS.I.ShowStereoComments = !SS.I.ShowStereoComments; Preferences.Set("ShowStereoComments", SS.I.ShowStereoComments); } if (BreakHtmlPopupsAtPageWidth.Checked != SS.I.BreakHtmlPopupsAtPageWidth) { SS.I.BreakHtmlPopupsAtPageWidth = !SS.I.BreakHtmlPopupsAtPageWidth; Preferences.Set("BreakHtmlPopupsAtPageWidth", SS.I.BreakHtmlPopupsAtPageWidth); } if (DefaultToSingleStepQueryExecution.Checked != MqlUtil.DefaultToSingleStepQueryExecution) { MqlUtil.DefaultToSingleStepQueryExecution = !MqlUtil.DefaultToSingleStepQueryExecution; Preferences.Set("DefaultToSingleStepQueryExecution", MqlUtil.DefaultToSingleStepQueryExecution); // set user preference QueryEngine.SetParameter("DefaultToSingleStepQueryExecution", MqlUtil.DefaultToSingleStepQueryExecution.ToString()); // set in QE for current session } //if (AllowNetezzaUse.Checked != SS.I.AllowNetezzaUse) //{ // SS.I.AllowNetezzaUse = AllowNetezzaUse.Checked; // Preferences.Set("AllowNetezzaUse", SS.I.AllowNetezzaUse); //} b1 = MarkCheckBoxesInitially.Checked; if (b1 != SS.I.GridMarkCheckBoxesInitially) { SS.I.GridMarkCheckBoxesInitially = b1; Preferences.Set("GridMarkCheckBoxesInitially", b1); } if (SS.I.EvenRowBackgroundColor != EvenRowBackgroundColor.Color) { SS.I.EvenRowBackgroundColor = EvenRowBackgroundColor.Color; Preferences.Set("EvenRowBackgroundColor", EvenRowBackgroundColor.Color.ToArgb()); } if (SS.I.OddRowBackgroundColor != OddRowBackgroundColor.Color) { SS.I.OddRowBackgroundColor = OddRowBackgroundColor.Color; Preferences.Set("OddRowBackgroundColor", OddRowBackgroundColor.Color.ToArgb()); } QbUtil.RenderQuery(ti); Progress.Hide(); DialogResult = DialogResult.OK; return; }
/// <summary> /// Thread to check to see if any imports need to started /// </summary> public void CheckForImportFileUpdatesThreadMethod(Object CheckAll) { // Check each ImportState user object for the user to see if any imports need to be started. // If any are found then start a new hidden Mobius client & server to upload the file(s) // and start an import user data process for each one. UserDataImportState udis; List <UserObject> imps = new List <UserObject>(); UserCmpndDbDao udbs = new UserCmpndDbDao(); int t0 = TimeOfDay.Milliseconds(); bool checkAllImportFiles = (bool)CheckAll; if (checkAllImportFiles) { imps = UserObjectDao.ReadMultiple(UserObjectType.ImportState, false); } else { imps = UserObjectDao.ReadMultiple(UserObjectType.ImportState, SS.I.UserName, false, false); } int t1 = TimeOfDay.Milliseconds() - t0; if (imps.Count == 0) { return; } // return ""; // debug int i1 = 0; while (i1 < imps.Count) { // pare list down do those needing updating UserObject uo = imps[i1]; try { udis = UserDataImportState.Deserialize(uo); } catch (Exception ex) { imps.RemoveAt(i1); continue; } if (udis.CheckForFileUpdates && ((checkAllImportFiles == true && udis.ClientFile.Substring(0, 1) == "\\" && FileUtil.Exists(udis.ClientFile)) || checkAllImportFiles == false)) { DateTime clientFileModDt = FileUtil.GetFileLastWriteTime(udis.ClientFile); // get client file mod date if (clientFileModDt == DateTime.MinValue || // skip if client file not found or udis.ImportIsRunning || // import is already running ((clientFileModDt - udis.ClientFileModified).TotalSeconds < 1 && // no change in client file mod date and !udis.ImportHasFailed)) // prev load attempt hasn't failed { imps.RemoveAt(i1); continue; } udis.ClientFileModified = clientFileModDt; // write the updated file date uo.Description = udis.Serialize(); UserObjectDao.Write(uo); } else // running or failed manual background import { if (udis.ImportHasFailed) // delete if failed { bool deleted = UserObjectDao.Delete(udis.Id); udbs.LogMessage("Deleted ImportState object for failed manual background import on " + uo.Name); } imps.RemoveAt(i1); // don't consider further here continue; } i1++; } //write a debug message and return udbs.LogMessage(string.Format("Found {0} annotation files that could be updated by the {1} account", imps.Count, SS.I.UserName)); int t2 = TimeOfDay.Milliseconds() - t0; if (imps.Count == 0) { return; } // Upload the file to the server and start a background process to update the annotation table foreach (UserObject uo2 in imps) { try { udis = UserDataImportState.Deserialize(uo2); string internalUoName = "Annotation_" + uo2.Id; string exportDir = ServicesIniFile.Read("BackgroundExportDirectory"); string serverFileName = // location for file on server exportDir + @"\" + internalUoName + Path.GetExtension(udis.FileName); ServerFile.CopyToServer(udis.FileName, serverFileName); string command = "ImportUserData " + serverFileName + ", " + internalUoName; CommandLine.StartBackgroundSession("ImportUserData " + serverFileName + ", " + uo2.Name); udbs.LogMessage("Auto-upload for ImportState ObjId = " + ", " + uo2.Id + ", Name = " + uo2.Name + ", Desc = " + uo2.Description); } catch (Exception ex) { try { udbs.LogMessage("Auto-upload exception ImportState ObjId = " + uo2.Id + ", Name = " + uo2.Name + ", Desc = " + uo2.Description + "\n" + DebugLog.FormatExceptionMessage(ex)); } catch (Exception ex2) { ex2 = ex2; } continue; } } Progress.Hide(); int t3 = TimeOfDay.Milliseconds() - t0; return; }
/// <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 }
/// <summary> /// Show progress message /// </summary> /// <param name="caption"></param> /// <param name="title"></param> /// <param name="allowCancel"></param> /// <param name="cancellingMessage"></param> void ShowInstance( string caption, string title, bool allowCancel, string cancellingMessage) { LastUpdateTime = TimeOfDay.Milliseconds(); //SystemUtil.Beep(); // debug if (Debug) { ClientLog.Message("Progress - Show: " + caption); } //bool disabled = true; // debug //if (disabled) return; if (!SS.I.Attended) { ClientLog.Message("Show: " + caption); return; } if (!Lex.IsNullOrEmpty(ScriptLog.FileName)) { ScriptLog.Message("Progress.Show: " + caption); } if (Lex.IsNullOrEmpty(caption)) // hide if no caption { Progress.Hide(); return; } bool sameMessage = Visible && Text == title && Caption.Text == caption && Cancel.Enabled == allowCancel && CancellingMessage.Text == cancellingMessage; //if (sameMessage) return; if (Debug) { ClientLog.Message("Progress - Show 2"); } // Adjust size of form to fit number of lines Size s2 = new Size(OriginalFormSize.Width, OriginalFormSize.Height); LexLineMetrics llm = Lex.AnalyzeLines(caption); int lineCnt = (llm.LineCnt > OriginalLines) ? llm.LineCnt : OriginalLines; // lines to display? int newCaptionHeight = (int)(lineCnt * (OriginalCaptionSize.Height / (OriginalLines * 1.0) + .5)); s2.Height = OriginalFormSize.Height + (newCaptionHeight - OriginalCaptionSize.Height); int lineLength = (llm.LongestLine > OriginalCharsPerLine) ? llm.LongestLine : OriginalCharsPerLine; // longer lines? int newCaptionWidth = (int)(llm.LongestLine * (OriginalCaptionSize.Width / (OriginalCharsPerLine * 1.0) + .5)); s2.Width = OriginalFormSize.Width + (newCaptionWidth - OriginalCaptionSize.Width); if (Height < s2.Height) { Height = s2.Height; // enlarge if necessary } if (Width < s2.Width) { Width = s2.Width; } // Fill in the form Text = title; Caption.Text = caption; Cancel.Enabled = allowCancel; CancellingMessage.Text = cancellingMessage; Refresh(); // force update of dialog if (SessionManager.ActiveForm == GetInstance()) // if this progress form is the active form then be sure it's visible { try { BringToFront(); Activate(); Focus(); //Application.DoEvents(); Showing = true; } catch (Exception ex) { ClientLog.Message("Show exception: " + DebugLog.FormatExceptionMessage(ex)); } } else if (!Showing) { try { //CenterToScreen(); Form owner = OwnerFormToUse; if (owner == null) { owner = SessionManager.ActiveForm; // if not defined get from session manager } Show(owner); // show the form, note: non-modal so we can return immediately to caller Showing = true; } catch (InvalidOperationException opEx) { ClientLog.Message("Show exception 1: " + DebugLog.FormatExceptionMessage(opEx)); // apparently something strange happened with focus... Try to recover gracefully Form shellForm = null; foreach (Form form in Application.OpenForms) { Type type = form.GetType(); if (type.FullName == "Mobius.Client.Shell") { shellForm = form; break; } } if (shellForm != null && !shellForm.Visible) { try { //Instance.CenterToScreen(); GetInstance().Show(shellForm); } catch (Exception ex) { ClientLog.Message("Instance.Show exception: " + DebugLog.FormatExceptionMessage(ex)); } } } catch (Exception ex) // some other error { string msg = "Show exception 2: "; if (SessionManager.ActiveForm != null) { msg += "ActiveForm: " + SessionManager.ActiveForm.Text + " "; } msg += DebugLog.FormatExceptionMessage(ex); ClientLog.Message(msg); } PerShowCancelRequestedFlag = false; } return; }
/// <summary> /// Right-click commands on objects in a tree /// </summary> /// <param name="command">The command to process</param> /// <param name="mtn">MetaTreeNode</param> /// <param name="uo">Any associated user object</param> /// <param name="ctc">ContentsTreeControl</param> /// <returns></returns> public static bool ProcessCommonRightClickObjectMenuCommands( string command, MetaTreeNode mtn, UserObject[] uoArray, ContentsTreeControl ctc) { UserObject uo2; string txt; UserObject uo = null; if (uoArray != null && uoArray.Length == 1) { uo = uoArray[0]; } //if (mtn == null) //{ // MessageBoxMx.ShowError("Operation is not allowed for this Database Contents node."); // return true; //} if (Lex.Eq(command, "Cut")) { CopyCutDelete(command, uoArray, ctc, true, true); } else if (Lex.Eq(command, "Copy")) { CopyCutDelete(command, uoArray, ctc, true, false); } else if (Lex.Eq(command, "Paste")) { try { txt = Clipboard.GetText(); //uo2 = UserObject.Deserialize(txt); uoArray = Deserialize(txt); if (uoArray == null) { throw new Exception("Not a UserObject"); } //if (uo2 == null) throw new Exception("Not a UserObject"); } catch (Exception ex) { MessageBoxMx.ShowError("The clipboard does not contain a recognized user objects"); return(true); } foreach (var userObject in uoArray) { Progress.Show("Pasting " + userObject.Name + "...", UmlautMobius.String, false); Permissions.UpdateAclForNewOwner(userObject, userObject.Owner, SS.I.UserName); // fixup the ACL for the new owner userObject.Owner = SS.I.UserName; userObject.ParentFolder = mtn.Name; mtn = UserObjectTree.GetValidUserObjectTypeFolder(userObject); for (int ci = 0; ; ci++) // find a name that's not used { UserObject uo3 = UserObjectDao.ReadHeader(userObject); if (uo3 == null) { break; } if (ci == 0) { userObject.Name = "Copy of " + userObject.Name; } else if (ci == 1) { userObject.Name = Lex.Replace(userObject.Name, "Copy of ", "Copy (2) of "); } else { userObject.Name = Lex.Replace(userObject.Name, "Copy (" + ci + ") of ", "Copy (" + (ci + 1) + ") of "); } } UserObject userObjectFinal = null; if (UserObjectDao.ReadHeader(userObject.Id) != null) // create a deep clone if orignal object exists { userObjectFinal = DeepClone(userObject); } if (userObjectFinal == null) { userObjectFinal = userObject; } UserObjectDao.Write(userObjectFinal, userObjectFinal.Id); // write using the current id Progress.Hide(); } //if (ctc != null) // need to update form directly? // UserObjectTree.RefreshSubtreeInTreeControl(uo2, ctc); } else if (Lex.Eq(command, "Delete")) { CopyCutDelete(command, uoArray, ctc, false, true); } else if (Lex.Eq(command, "Rename")) { if (!UserHasWriteAccess(uo)) { MessageBoxMx.ShowError("You are not authorized to rename " + uo.Name); return(true); } string newName = InputBoxMx.Show("Enter the new name for " + uo.Name, "Rename", uo.Name); if (newName == null || newName == "" || newName == uo.Name) { return(true); } if (!IsValidUserObjectName(newName)) { MessageBoxMx.ShowError("The name " + newName + " is not valid."); return(true); } uo2 = uo.Clone(); uo2.Name = newName; uo2.Id = 0; // clear Id so not looked up by id if (!Lex.Eq(newName, uo.Name) && UserObjectDao.ReadHeader(uo2) != null) { MessageBoxMx.ShowError(newName + " already exists."); return(true); } uo2.Id = uo.Id; UserObjectDao.UpdateHeader(uo2); if (ctc != null) { UserObjectTree.UpdateObjectInTreeControl(uo, uo2, ctc); } } else if (Lex.Eq(command, "MakePublic") || Lex.Eq(command, "MakePrivate")) { UserObjectAccess newAccess; MetaTreeNode objFolder; if (!UserHasWriteAccess(uo)) { MessageBoxMx.ShowError("You are not authorized to make " + uo.Name + ((Lex.Eq(command, "MakePublic")) ? " public" : " private")); return(true); } if (Lex.Eq(command, "MakePublic")) { if (uo.ParentFolder == "DEFAULT_FOLDER") { MessageBoxMx.ShowError("Items in the Default Folder cannot be made public"); return(true); } else { //check the folder id parentage to ensure that the current folder isn't a subfolder of the default folder if (UserObjectTree.FolderNodes.ContainsKey(uo.ParentFolder)) { objFolder = UserObjectTree.FolderNodes[uo.ParentFolder]; while (objFolder != null) { if (objFolder.Target == "DEFAULT_FOLDER") { MessageBoxMx.ShowError("Items in the Default Folder cannot be made public"); return(true); } objFolder = objFolder.Parent; } } else { throw new Exception("Failed to recognize the folder that this object is in!"); } } newAccess = UserObjectAccess.Public; } else { //user folders cannot be made private if they contain public children if (uo.Type == UserObjectType.Folder) { objFolder = UserObjectTree.BuildNode(uo); if (UserObjectTree.FolderNodes.ContainsKey(objFolder.Target)) { objFolder = UserObjectTree.FolderNodes[objFolder.Target]; for (int i = 0; i < objFolder.Nodes.Count; i++) { MetaTreeNode currentChild = (MetaTreeNode)objFolder.Nodes[i]; } } } newAccess = UserObjectAccess.Private; } uo2 = UserObjectDao.Read(uo); if (uo2 == null) { return(true); } if (uo2.AccessLevel == newAccess) { return(true); // no change } uo2.AccessLevel = newAccess; UserObjectDao.UpdateHeader(uo2); if (ctc != null) // need to update form directly? { UserObjectTree.RefreshSubtreeInTreeControl(uo2, ctc); } return(true); } else if (Lex.Eq(command, "ChangeOwner")) { string newOwner = InputBoxMx.Show("Enter the user name of the person to transfer ownership of " + Lex.AddDoubleQuotes(uo.Name) + " to:", "Change Owner", ""); if (Lex.IsNullOrEmpty(newOwner)) { return(true); } string result = UserObjectUtil.ChangeOwner(uo.Id, newOwner); if (!Lex.IsNullOrEmpty(result)) { MessageBoxMx.Show(result); } return(true); } else if (Lex.Eq(command, "Permissions")) // set object permissions { PermissionsDialog.Show(uo); return(true); } else if (Lex.Eq(command, "ViewSource")) { uo = UserObjectDao.Read(uo); if (uo == null) { return(true); } string ext = ".txt"; // default extension if (uo.Type == UserObjectType.Query || uo.Type == UserObjectType.Annotation) { ext = ".xml"; } string cFile = ClientDirs.TempDir + @"\Source" + ext; StreamWriter sw = new StreamWriter(cFile); sw.Write(uo.Content); sw.Close(); SystemUtil.StartProcess(cFile); // show it } else { return(false); // command not recognized } return(true); // command recognized and processed }
/// <summary> /// Retrieve the results of a background export /// Example: Retrieve Background Export 231243 /// </summary> /// <param name="objectIdString">Id of BackgroundExport UserObject containing serialized ResultsFormat</param> /// <returns></returns> public static string RetrieveBackgroundExport( string objectIdString) { ResultsFormat rf; Query q; int objId; QbUtil.SetMode(QueryMode.Build); // be sure in build mode if (!int.TryParse(objectIdString, out objId)) { return("Invalid UserObjectId: " + objectIdString); } UserObject uo = UserObjectDao.Read(objId); if (uo == null) { return("RunInBackground UserObject not found: " + objectIdString); } if (uo.Type != UserObjectType.BackgroundExport) { return("Object is not the expected RunInBackground UserObject type"); } rf = ResultsFormat.Deserialize(uo.Content); if (rf == null) { throw new Exception("Failed to deserialize ResultsFormat: " + objectIdString); } string clientFile = rf.OutputFileName; string serverFile = GetServerFileName(rf, objId); string ext = Path.GetExtension(clientFile); string filter = "*" + ext + "|*" + ext; if (SharePointUtil.IsRegularFileSystemName(clientFile)) { clientFile = UIMisc.GetSaveAsFilename("Retrieve Background Export File", clientFile, filter, ext); } else { clientFile = SharePointFileDialog.GetSaveAsFilename("Retrieve Background Export File", clientFile, filter, ext); } if (String.IsNullOrEmpty(clientFile)) { return(""); } Progress.Show("Retrieving file..."); try { ServerFile.CopyToClient(serverFile, clientFile); } catch (Exception ex) { string msg = "Unable to retrieve cached export file: " + serverFile + "\n" + "to client file: " + clientFile + "\n" + DebugLog.FormatExceptionMessage(ex); ServicesLog.Message(msg); Progress.Hide(); return(msg); } Progress.Hide(); if (Lex.Eq(ext, ".xls") || Lex.Eq(ext, ".xlsx") || Lex.Eq(ext, ".doc") || Lex.Eq(ext, ".docx")) { DialogResult dr = MessageBoxMx.Show("Do you want to open " + clientFile + "?", UmlautMobius.String, MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dr == DialogResult.Yes) { SystemUtil.StartProcess(clientFile); } } return("Background export file retrieved: " + clientFile); }
/// <summary> /// Handle conversion of Mobius custom data types between the grid and the underlying DataSet /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void ProcessCustomUnboundColumnDataEvent(object sender, CustomColumnDataEventArgs e) { MobiusDataType mdt = null; FormattedFieldInfo ffi = null; bool formatted = false; NumberMx numberEx; StringMx stringEx; ImageMx imageMx; DateTimeMx dateTimeEx; DataRowMx dr = null; BandedGridView mbgv; int nonNullDri; string debugMsg; if (DebugMx.False) // fillValuesImmediately debug test { e.Value = "XXX"; return; } DateTime t0 = DateTime.Now; int callId = ++UnboundCalls; // get id for this call if (sender is BandedGridView) { mbgv = sender as BandedGridView; } if (Grid.DataSource == null) { return; } CellInfo ci = Grid.GetDataTableCellInfo(e.ListSourceRowIndex, e.Column); //if (e.ListSourceRowIndex == 2 && ci.DataRowIndex == 1) e = e; // debug //if (ci.Mc.DataType == MetaColumnType.CompoundId && ci.DataRowIndex > 0) ci = ci; // debug //DebugLog.Message("CustomUnboundColumnData " + ci.DataRowIndex + ", " + ci.DataColIndex + ", " + ci.DataValue.ToString()); if (ci.Rfld == null) { return; } QueryManager qm = Grid.QueryManager; ResultsFormatter fmtr = qm.ResultsFormatter; ResultsFormat rf = qm.ResultsFormat; if (e.ListSourceRowIndex == GridControl.NewItemRowHandle || e.ListSourceRowIndex >= Qm.DataTable.Rows.Count) // new row being created { if (NewRow == null) { NewRow = Qm.DataTable.NewRow(); } dr = NewRow; } else if (e.ListSourceRowIndex >= 0 && ci.DataRowIndex >= 0) // row exist in DataTable (i.e. not new row) { AdjustDataRowToRender(ci); if (ci.DataRowIndex >= 0) { dr = DataTable.Rows[ci.DataRowIndex]; if (ci.DataRowIndex == 0) { } } } else { if (DebugDetails) { ClientLog.Message("Fail 1"); } return; // something else, ignore } // Store edited data for unbound column in DataTable if (e.IsSetData) { SetGridData(e, ci); return; } else if (!e.IsGetData) { return; // just return if not GetData as expected } // Get data from underlying unbound dataset & return in format for grid //if (ci.Mc.DataType == MetaColumnType.Structure) ci = ci; // debug //if (ci.Mc.DataType == MetaColumnType.String) ci = ci; // debug //if (ci.DataValue is StringEx && ((StringEx)ci.DataValue).Value == " ") ci = ci; // debug UnboundGets++; if (dr == null) { e.Value = null; if (DebugDetails) { ClientLog.Message("Fail 2"); // debug } return; } if (Dtm.IsRetrievingDataMessageRow(dr) && ci.Mc != null && !ci.Mc.IsGraphical) { //if (ci.Mc.IsKey) // show retrieving data message for key field e.Value = "Retrieving data..."; return; } object fieldValue = dr[ci.DataColIndex]; if (DebugDetails && fieldValue is MoleculeMx) // debug { MoleculeMx cs = fieldValue as MoleculeMx; MoleculeFormat csType = cs.PrimaryFormat; string csValue = cs.PrimaryValue; int csLen = cs.PrimaryValue.Length; string molfile = cs.GetMolfileString(); molfile = molfile; } try { // If already formatted use existing formatting info ffi = null; if (fieldValue is MobiusDataType) { mdt = (MobiusDataType)fieldValue; if (mdt.FormattedBitmap != null) { ffi = new FormattedFieldInfo(); ffi.FormattedBitmap = mdt.FormattedBitmap; } else if (mdt.FormattedText != null) { ffi = new FormattedFieldInfo(); ffi.FormattedText = mdt.FormattedText; } if (ffi != null) // if formatted then copy other format attributes as well { ffi.BackColor = mdt.BackColor; ffi.ForeColor = mdt.ForeColor; ffi.Hyperlink = mdt.Hyperlink; } } // If not formatted then format if (ffi == null) // need to format? { // Format non-image field (including structures) if (ci.Mc.DataType != MetaColumnType.Image) // format other than image immediately { //if (ci.Mc.DataType == MetaColumnType.Structure) // debug //{ // DebugLog.Message(fieldValue.ToString()); // UIMisc.Beep(); //} ffi = fmtr.FormatField(ci.Rt, ci.TableIndex, ci.Rfld, ci.FieldIndex, dr, e.ListSourceRowIndex, fieldValue, ci.DataRowIndex, false); FormatFieldCalls++; if (ci.Mc.DataType == MetaColumnType.Structure) { FormatStructureFieldCalls++; } StoreFormattingInformationInMdt(ffi, fieldValue, dr, ci, mdt); formatted = true; } // Image: start asynch call to get image in background as necessary since it is too slow to wait for it here else { if (fieldValue is ImageMx) { imageMx = fieldValue as ImageMx; } else { imageMx = new ImageMx(); if (fieldValue != null) { if (fieldValue is MobiusDataType) { imageMx.DbLink = (fieldValue as MobiusDataType).DbLink; } else { imageMx.DbLink = fieldValue.ToString(); // store field value as dblink } } dr.ItemArrayRef[ci.DataColIndex] = imageMx; // store new image object without firing event } mdt = imageMx; // copy image object to general MobiusDataType ffi = new FormattedFieldInfo(); if (imageMx.FormattedBitmap != null) // already have bitmap? { ffi.FormattedBitmap = imageMx.FormattedBitmap; } else if (imageMx.Value != null) // have the bitmap, just need to scale it { int fieldWidth = ci.Rfld.FieldWidth; // current field width in milliinches int desiredWidth = (int)((fieldWidth / 1000.0) * GraphicsMx.LogicalPixelsX * 1.0); // width in pixels imageMx.FormattedBitmap = BitmapUtil.ScaleBitmap(imageMx.Value, desiredWidth); ffi.FormattedBitmap = imageMx.FormattedBitmap; } else if (imageMx.IsRetrievingValue) // already retrieving? { ffi.FormattedBitmap = (Bitmap)RetrievingImageMsg.Image; // put up the processing image } else if (SS.I.AsyncImageRetrieval) // start async image retrieval { FormatImageFieldCalls++; GetImageBitmapAsync(ci, dr, e.ListSourceRowIndex, fieldValue, imageMx, callId); ffi.FormattedBitmap = (Bitmap)RetrievingImageMsg.Image; // put up the processing image } else // do synchronous image retrieval { GetImageBitmap(ci, dr, e.ListSourceRowIndex, fieldValue, imageMx, callId); ffi.FormattedBitmap = imageMx.FormattedBitmap; formatted = true; } } } //if (ci.Mc.DataType == MetaColumnType.CompoundId && String.IsNullOrEmpty(fmtdFld.Hyperlink)) ci = ci; // debug //if (mdt is CompoundId) mdt = mdt; // debug if (e.Column.ColumnEdit is RepositoryItemPictureEdit) { if (ffi != null && ffi.FormattedBitmap != null) { e.Value = ffi.FormattedBitmap; } else { e.Value = new Bitmap(1, 1); // avoid no-image data message } //ffi.FormattedBitmap.Save(@"c:\download\test.bmp"); // debug } else { e.Value = ffi.FormattedText; // non-picture column } if (ci.DataRowIndex == DataTable.Rows.Count - 1 && // if at end of DataTable && more rows available, request them !Dtm.RowRetrievalComplete) { //Progress.Show("Retrieving data..."); // put up progress dialog if not already up //if (WaitForMoreDataStartTime.Equals(DateTime.MinValue)) // say we've started waiting for data //{ // WaitForMoreDataStartTime = DateTime.Now; // ClientLog.Message("Set WaitForMoreDataStartTime: " + WaitForMoreDataStartTime.ToLongTimeString()); //} if (Dtm.RowRetrievalState == RowRetrievalState.Paused) { Dtm.StartRowRetrieval(); // .ReadNextRowsFromQueryEngine(); // restart retrieval } } else if (Lex.StartsWith(Progress.GetCaption(), "Retrieving data...") || Lex.IsUndefined(Progress.GetCaption())) { // hide any "Retrieving data..." message Progress.Hide(); //SystemUtil.Beep(); } Grid.LastRowRendered = e.ListSourceRowIndex; if (DebugDetails) { debugMsg = "Grid.GetData: " + callId + ", e.Row = " + e.ListSourceRowIndex + ", e.Col = " + e.Column.AbsoluteIndex + ", Formatted = " + (formatted ? "T" : "F") + ", Time(ms) = " + TimeOfDay.Delta(t0) + ", ColLabel = " + ci.Qc.ActiveLabel; debugMsg += ", FieldValue = "; if (fieldValue != null) { debugMsg += fieldValue.ToString(); } debugMsg += ", e.Value = "; if (e.Value != null) { debugMsg += e.Value.ToString(); } else { debugMsg += "null"; } ClientLog.Message(debugMsg); } // TODO: This does a some unnecessary hides which cause flashing of the window frame // This happens when we are not at the end of the DataTable but don't know if any additional requests // for rendering will occur. May be better to move this to DataTableManger when we detect // that we have retrieved a row that is below the level of those displayed in the grid or all rows have been retrieved. // Also maybe in MoleculeGridControl.RetrievalMonitorTimer_Tick } catch (Exception ex) { if (e.Column.ColumnEdit is RepositoryItemPictureEdit) { e.Value = new Bitmap(1, 1); // avoid no-image data message } else { e.Value = ex.Message; } string msg = "ColumnView_CustomUnboundColumnData Exception"; if (ci.Rfld != null) { msg += ", MetaColumn: " + ci.Rfld.MetaColumn.MetaTable.Name + "." + ci.Rfld.MetaColumn.Name; } msg += ", DataColIndex: " + ci.DataColIndex + ", DataRowIndex: " + ci.DataRowIndex; if (fieldValue != null) { msg += ", Value: " + fieldValue.ToString(); } ClientLog.Message(msg); } // t0 = TimeOfDay.Milliseconds() - t0; // ClientLog.Message("CustomUnboundColumnData event time: " + t0); }
/// <summary> /// Selected a new target map /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void TargetMap_SelectedIndexChanged(object sender, EventArgs e) { if (InSetup) { return; } string newTargetMap = TargetMap.Text; if (Lex.Eq(newTargetMap, "Retrieve KEGG Pathway...")) // lookup KEGG pathway { if (Math.Abs(1) == 1) // 2/1/2013, best available now e.g. http://www.kegg.jp/kegg-bin/show_pathway?hsa04010 { MessageBoxMx.ShowError(@"Automated access to pathway maps is now available through subsciption only."); return; } SetTargetMapText(SelectedTargetMap); // keep current map for now string pathwayId = InputBoxMx.Show( "Enter the KEGG pathway id (e.g. hsa00010) for the desired pathway. " + "Pathway identifiers can be looked up at: " + "<a href=\"http://www.genome.jp/kegg/pathway.html\" target=\"_blank\">http://www.genome.jp/kegg/pathway.html</a>", "KEGG Pathway Identifier"); if (String.IsNullOrEmpty(pathwayId)) { return; } try { Progress.Show("Retrieving KEGG information for pathway: " + pathwayId, UmlautMobius.String, false); TargetMap tm = TargetMapDao.GetKeggPathway(pathwayId); Progress.Hide(); if (!MapLabelDict.ContainsKey(tm.Label.ToUpper())) { MapLabelDict[tm.Label.ToUpper()] = null; MapLabelList.Add(tm.Label); UserMapNames.Add(tm.Name); } TargetMap.Properties.Items.Clear(); TargetMap.Properties.Items.AddRange(MapLabelList); // update list SelectedTargetMap = tm.Label; SetTargetMapText(SelectedTargetMap); // make current selection } catch (Exception ex) { string msg = ex.Message; Progress.Hide(); MessageBoxMx.ShowError("Pathway not found"); return; } return; } else if (newTargetMap.StartsWith("---")) // divider selected, ignore { SetTargetMapText(SelectedTargetMap); } SetTargetMapText(newTargetMap); // new map selected }
/// <summary> /// See if a ClickFunction command & process if so /// </summary> /// <param name="command"></param> /// <param name="qm"></param> /// <param name="cInf"></param> public static void Process( string command, QueryManager qm, CellInfo cInf = null) { QueryTable rootQt, qt; QueryColumn qc; MetaTable mt; MetaColumn mc; Query q2; string dbName = "", mtName = "", mcName = ""; List <string> args0, args; string funcName, arg1, arg2, arg3, arg4, arg5; string value = "", keyValue = ""; int ai; try { // Parse click function arguments stripping all single quotes. // Arguments may be defined in the clickfunction definition including col values // indicated by field.Value in the metacolumn clickfunction definition. // If no args are defined in the clickfunction definition then a field value // argument will be added by default or the keyValue if [keyvalue] appears in the // ClickFunction definition CurrentClickQueryManager = qm; args0 = Lex.ParseAllExcludingDelimiters(command, "( , )", false); args = new List <string>(); for (ai = 0; ai < args0.Count; ai++) // strip all single quotes { string arg = args0[ai]; if (arg.StartsWith("'")) { arg = Lex.RemoveSingleQuotes(arg); } //if (Lex.Eq(arg, "[rowcol]") && cInf!= null) //{ // pass grid row & col // args.Add(cInf.GridRowHandle.ToString()); // args.Add(cInf.GridColAbsoluteIndex.ToString()); //} //else args.Add(arg); } funcName = args[0]; arg1 = (args.Count >= 2 ? args[1] : ""); // get other args arg2 = (args.Count >= 3 ? args[2] : ""); arg3 = (args.Count >= 4 ? args[3] : ""); arg4 = (args.Count >= 5 ? args[4] : ""); arg5 = (args.Count >= 6 ? args[5] : ""); if (Lex.Eq(funcName, "DisplayAllData")) { // do all data display for supplied root table and key, i.e. DisplayAllData(TableName, KeyColName, KeyValue) ParseMetaTableMetaColumn(arg1, out mt, arg2, out mc); string extKey = arg3; string intKey = CompoundId.Normalize(extKey, mt); Progress.Show("Building Query..."); _query = QueryEngine.GetSelectAllDataQuery(mt.Name, intKey); Progress.Show("Retrieving data..."); // put up progress dialog since this may take a while QbUtil.RunPopupQuery(_query, mt.KeyMetaColumn.Name + " " + extKey); Progress.Hide(); return; } else if (Lex.Eq(funcName, "DisplayAllDataUsingDbName")) { // display all data for supplied database synonym & key value, i.e. DisplayAllData2(DataBaseSynonym, KeyValue) mtName = null; dbName = arg1; RootTable rti = RootTable.GetFromTableLabel(dbName); if (rti != null) { mtName = rti.MetaTableName; } else // try synonyms { DictionaryMx dict = DictionaryMx.Get("Database_Synonyms"); if (dict != null) { mtName = dict.LookupDefinition(dbName); } } if (String.IsNullOrEmpty(mtName)) { MessageBoxMx.ShowError("Unrecognized database: " + dbName); return; } mt = MetaTableCollection.Get(mtName); if (mt == null) { MessageBoxMx.ShowError("Can't find key metatable " + mtName + " for database " + dbName); return; } string extKey = arg2; string intKey = CompoundId.Normalize(extKey, mt); Progress.Show("Building Query..."); _query = QueryEngine.GetSelectAllDataQuery(mt.Name, intKey); Progress.Show("Retrieving data..."); // put up progress dialog since this may take a while QbUtil.RunPopupQuery(_query, mt.KeyMetaColumn.Name + " " + extKey); return; } // Run a query displaying results to a grid or web page and substituting a parameter value else if (Lex.Eq(funcName, "RunHtmlQuery") || Lex.Eq(funcName, "RunGridQuery")) { // command to display to grid or html if (arg1.StartsWith("MetaTreeNode=", StringComparison.OrdinalIgnoreCase)) { // query based on metatables under a tree node string nodeName = arg1.Substring("MetaTreeNode=".Length).Trim(); _cid = arg2; MetaTreeNode mtn = MetaTree.GetNode(nodeName); if (mtn == null) { MessageBoxMx.ShowError("Can't find tree node referenced in ClickFunction: " + nodeName); return; } _query = new Query(); MetaTable rootMt = null; foreach (MetaTreeNode mtn_ in mtn.Nodes) { if (!mtn_.IsDataTableType) { continue; } mt = MetaTableCollection.Get(mtn_.Target); if (mt == null) { continue; } if (rootMt == null) { rootMt = mt.Root; rootQt = new QueryTable(_query, rootMt); } if (mt == rootMt) { continue; } qt = new QueryTable(_query, mt); } if (_query.Tables.Count == 0) { MessageBoxMx.ShowError("No valid data tables found: " + nodeName); return; } _query.KeyCriteria = "= " + _cid; _title = mtn.Label + " for " + _query.Tables[0].MetaTable.MetaColumns[0].Label + " " + CompoundId.Format(_cid); } else if (arg1.StartsWith("Query=", StringComparison.OrdinalIgnoreCase)) { // query based on saved query string qIdString = arg1.Substring("Query=".Length).Trim(); if (qIdString.StartsWith("Query_", StringComparison.OrdinalIgnoreCase)) { qIdString = qIdString.Substring("Query_".Length).Trim(); } int qId = int.Parse(qIdString); _query = QbUtil.ReadQuery(qId); _cid = arg2; _query.KeyCriteria = "= " + _cid; _title = _query.UserObject.Name + " for " + _query.Tables[0].MetaTable.MetaColumns[0].Label + " " + CompoundId.Format(_cid); } else // explicit mql string to execute { _mql = arg1; // mql to execute if (Lex.IsUndefined(_mql)) { throw new Exception("Expected MQL query not found: " + command); } mt = null; mc = null; if (Lex.IsDefined(arg2) && Lex.IsDefined(arg3)) { mtName = arg2; mcName = arg3; value = arg4; // value to plug in to mql keyValue = value; ParseMetaTableMetaColumn(arg2, out mt, arg3, out mc); } else if (cInf != null) { mt = cInf.Mt; mc = cInf.Mc; value = cInf?.DataValue?.ToString(); keyValue = qm?.DataTableManager?.GetRowKey(cInf.DataRowIndex); } if (mt == null || mc == null) { throw new Exception("Invalid MetaTable or MetaColumn name(s): " + command); } if (!mc.IsNumeric) { value = Lex.AddSingleQuotes(value); // quote if not numeric } int i1 = _mql.ToLower().IndexOf("[value]"); // see if a value parameter if (i1 >= 0) { string value2 = value; _mql = _mql.Replace(_mql.Substring(i1, 7), value); _title = mc.Label + " " + value; } i1 = _mql.ToLower().IndexOf("[keyvalue]"); // see if a key value parameter if (i1 >= 0) { _mql = _mql.Replace(_mql.Substring(i1, 10), keyValue); _title = mt.KeyMetaColumn.Label + " " + keyValue; } try { _query = MqlUtil.ConvertMqlToQuery(_mql); } catch (Exception ex) { MessageBoxMx.ShowError("Error converting Mql to query: " + ex.Message); return; } } if (Lex.Eq(funcName, "RunHtmlQuery")) { QbUtil.RunPopupQuery(_query, _title, OutputDest.Html); } else // output to grid { QbUtil.RunPopupQuery(_query, _title, OutputDest.WinForms); } //else // create new grid query & run (will lose results for current query) //{ // QbUtil.NewQuery(_title); // show in query builder // QbUtil.SetCurrentQueryInstance(_query); // QbUtil.RenderQuery(); // string nextCommand = QueryExec.RunQuery(_query, OutputDest.Grid); //} return; } // Open a URL, normally substituting parameter value else if (Lex.Eq(funcName, "OpenUrl")) { string url = arg1; // url to execute value = arg2; // value to plug in to url int i1 = Lex.IndexOf(url, "[value]"); // fill in one of the value place holders if (i1 >= 0) { string value2 = value; url = url.Replace(url.Substring(i1, 7), value); } else // check to see if we are matching on key { i1 = Lex.IndexOf(url, "[keyvalue]"); if (i1 >= 0) { url = url.Replace(url.Substring(i1, 10), value); } } SystemUtil.StartProcess(url); return; } else if (Lex.Eq(funcName, "OpenUrlFromSmallWorldCid")) { SmallWorldDepictions.OpenUrlFromSmallWorldCid(arg1); return; } else if (Lex.Eq(funcName, "ShowProjectDescription")) { string projName = arg1; QbUtil.ShowProjectDescription(projName); return; } else if (Lex.Eq(funcName, "ShowTableDescription")) { mtName = arg1; QbUtil.ShowTableDescription(mtName); return; } else if (Lex.Eq(funcName, "DisplayDrilldownDetail")) { // drill down into a result value mtName = arg1; // table mcName = arg2; // column int level = Int32.Parse(arg3); string resultId = arg4; // quoted resultId to get q2 = QueryEngine.GetSummarizationDetailQuery(mtName, mcName, level, resultId); if (q2 == null) { throw new Exception("Unable to build drill-down query for: " + mtName + "." + mcName); } bool success = QbUtil.RunPopupQuery(q2, "Result Detail", OutputDest.WinForms); return; } //else if (Lex.Eq(funcName, "PopupSmilesStructure")) // display structure for a Smiles string (still needs some work...) //{ // string molString = arg1.ToString(); // ChemicalStructure cs = new ChemicalStructure(StructureFormat.Smiles, molString); // ToolHelper.DisplayStructureInPopupGrid("Title...", "Smiles", "Structure", cs); //} //else if (Lex.Eq(funcName, "PopupChimeStructure")) // display structure for a Chime string //{ // string molString = arg1.ToString(); // ChemicalStructure cs = new ChemicalStructure(StructureFormat.Smiles, molString); // ToolHelper.DisplayStructureInPopupGrid("Title...", "Smiles", "Structure", cs); //} else if (Lex.Eq(funcName, "DisplayWebPage")) { // substitute a field value into a url & display associated web page string url = arg1; ParseMetaTableMetaColumn(arg2, out mt, arg3, out mc); value = arg4; // value to plug in to mql // value = "{6E9C28EF-407E-44A0-9007-5FFB735A5C6C}"; // debug // value = "{0AC17903-E551-445E-BFAA-860023D2884F}"; // debug // value = "{63EE71F9-15BA-42FB-AFDC-C399103707B1}"; // debug // value = "{80591183-B7BA-4669-8C5F-7E7F53D981CE}"; //lex.OpenString(mc.ClickFunction); // reparse url to get proper case //funcName = lex.GetNonDelimiter(); //url = Lex.RemoveAllQuotes(lex.GetNonDelimiter()); _title = mc.Label + " " + value; int i1 = url.ToLower().IndexOf("[value]"); // fill in one of the value place holders if (i1 >= 0) { url = url.Replace(url.Substring(i1, 7), value); } else // check to see if we are matching on key { i1 = url.ToLower().IndexOf("[keyvalue]"); if (i1 >= 0) { url = url.Replace(url.Substring(i1, 10), value); _title = mt.KeyMetaColumn.Label + " " + value; } } UIMisc.ShowHtmlPopupFormDocument(url, _title); return; } else if (Lex.Eq(funcName, "DisplayOracleBlobDocument")) // display a document contained in an Oracle blob column { // Syntax: DisplayOracleBlobDocument(<table-to-lookup>, <value_match_column>, <file-name-or-type-col>, <content-column>) string table = arg1; string matchCol = arg2; string typeCol = arg3; string contentCol = arg4; string matchVal = arg5; // value to match try { string typeName; byte[] ba; UalUtil.SelectOracleBlob(table, matchCol, typeCol, contentCol, matchVal, out typeName, out ba); if (ba == null || ba.Length == 0) { return; } UIMisc.SaveAndOpenBinaryDocument(typeName, ba); } catch (Exception ex) { MessageBoxMx.ShowError("Error retrieving document: " + ex.Message); return; } return; } else if (Lex.Eq(funcName, "DisplayOracleClobDocument")) // display a document contained in an Oracle clob column { // Syntax: DisplayOracleBlobDocument(<table-to-lookup>, <value_match_column>, <file-name-or-type-col>, <content-column>) string table = arg1; string matchCol = arg2; string typeCol = arg3; string contentCol = arg4; string matchVal = arg5; // value to match try { string typeName, clobString; UalUtil.SelectOracleClob(table, matchCol, typeCol, contentCol, matchVal, out typeName, out clobString); if (Lex.IsUndefined(clobString)) { return; } UIMisc.SaveAndOpenBase64BinaryStringDocument(typeName, clobString); // assume clob string is a Base64Binary string } catch (Exception ex) { MessageBoxMx.ShowError("Error retrieving document: " + ex.Message); return; } return; } else if (Plugins.IsMethodExtensionPoint(funcName)) { List <object> objArgs = new List <object>(); for (ai = 1; ai < args.Count; ai++) // build list of object arguments { objArgs.Add(args[ai]); } Plugins.CallStringExtensionPointMethod(funcName, objArgs); } else if (Lex.Eq(funcName, "None")) // dummy click function { return; } else { MessageBoxMx.ShowError("Unrecogized click function: " + funcName); return; } } catch (Exception ex) { Exception ex2 = ex; if (ex.InnerException != null) { ex2 = ex.InnerException; } string msg = "Error executing ClickFunction: " + command + "\r\n" + DebugLog.FormatExceptionMessage(ex); MessageBoxMx.ShowError(msg); ServicesLog.Message(msg); } }
/// <summary> /// Execute search & get hit list /// </summary> /// <param name="saveHitlist"></param> /// <returns></returns> public bool ExecuteSearch(bool saveHitlist) { int voi, ti, fi; ResultsTable rt; ResultsField rfld; MetaTable mt; MetaColumn mc, mc2; if (saveHitlist) // clear current list { SessionManager.CurrentResultKeys = new List <string>(); if (QueryManager.StatusBarManager != null) { QueryManager.StatusBarManager.DisplayCurrentCount(); } } // Start thread running the query QueryResultsAvailable = false; QueryEngineException = null; ThreadStart ts = new ThreadStart(ExecuteQueryThreadMethod); Thread executeQueryThread = new Thread(ts); executeQueryThread.Name = "ExecuteSearch"; executeQueryThread.IsBackground = true; executeQueryThread.SetApartmentState(ApartmentState.STA); executeQueryThread.Start(); // Put up message for user if (((Query.ResultKeys != null && Query.UseResultKeys) || // already have list ResultsFormat.SessionOutputFormContext) && !QueryEngineStatsForm.ShowStats) { Progress.Show("Retrieving data...", UmlautMobius.String, true, "Cancelling retrieval..."); } else // normal type search { Progress.Show("Searching database - 0:00", UmlautMobius.String, true, "Cancelling search..."); if (QueryEngineStatsForm.ShowStats) { QueryEngineStatsForm.StartNewQueryExecution(Query); QueryEngineStatsForm.StartingSearch(); } } // Wait until results available or the query is cancelled by the user while (true) { Thread.Sleep(100); Application.DoEvents(); if (QueryResultsAvailable) // completed normally { ResultsKeys = QueryEngine.GetKeys(); if (saveHitlist) // store for session manager also (may differ but probably shouldn't) { SessionManager.CurrentResultKeys = ResultsKeys; } //Progress.Hide(); break; } else if (QueryEngineException != null) { Progress.Hide(); if (QueryEngineException is QueryException || QueryEngineException is UserQueryException) { throw QueryEngineException; } else { throw new Exception(QueryEngineException.Message, QueryEngineException); } } else if (Progress.CancelRequested) { if (QueryEngine != null) { QueryEngine.Cancel(false); // start the cancel } Thread.Sleep(250); Application.DoEvents(); if (executeQueryThread != null) { executeQueryThread.Abort(); // kill the local thread executing the query } Progress.Hide(); return(false); } } // If the query contains tables marked for remapping then build new expanded query & use going forward // modifiedQuery = QueryEngine.DoPresearchChecksAndTransforms(Query); // do any presearch transforms OriginalQuery = Query; if (TransformedQuery != null) { //ResultsPages qrp = query.ResultsPages; //ResultsPages mqrp = modifiedQuery.ResultsPages; // use same set of results pages so view changes propagate back to original query Query.PresearchDerivedQuery = TransformedQuery; // link original query to the transformed query Query = TransformedQuery; // replace original query with this query } else { Query.PresearchDerivedQuery = null; } InitializeQueryManager(QueryManager, Query, QueryManager.ResultsFormat, QueryEngine, ResultsKeys); // Save the hit list as needed if (saveHitlist) { CidList currentList = new CidList(ResultsKeys); CidListCommand.WriteCurrentList(currentList); SessionManager.DisplayCurrentCount(); } return(true); }
/// <summary> /// Run the query /// </summary> /// <param name="browseExistingResults">If true browse existing results</param> /// <returns></returns> public string RunQuery3( ResultsFormat rf, bool saveHitlist, bool browseExistingResults) { Query modifiedQuery; QueryTable qt; QueryColumn qc; ResultsTable rt; ResultsField rfld; MetaTable mt; MetaColumn mc; string txt, msg; DialogResult dr; bool success; CellGraphic cg; Lex lex = new Lex(); string tempfile, tok, command, unrecognizedCommand, response; int ti, gi, rc, i1, i2; // Begin execution if (rf == null) { throw new Exception("QueryExec.Run - Null ResultsFormat"); } if (ResultsFormatter == null) { throw new Exception("QueryExec.Run - Null ResultsFormatter"); } if (rf.Segments == null) { throw new Exception("QueryExec.Run - Null ResultsFormat.Segments"); } if (Query == null) { throw new Exception("QueryExec.Run - Null Rf.Query"); } if (Query.Tables == null || Query.Tables.Count <= 0) { throw new QueryException("QueryExec.Run - No Query Tables"); } QueryManager qm = QueryManager; ReturnMsg = ""; //bool useExistingQueryEngine = Rf.ParentQe != null; //bool useExistingDataTable = Query.BrowseExistingResultsWhenOpened && Query.SerializeResults && // qm.DataTable != null && qm.DataTable.Rows.Count > 0; try { //if (Math.Sqrt(4) == 2) throw new Exception("test"); // debug if (!browseExistingResults) // normal open of search { Progress.Show("Analyzing query..."); // put up a status message to the user as soon as possible to let them know something is happening... dr = ValidateQuery(Query); if (dr == DialogResult.Cancel) { return(""); } WriteCurrentListToServerIfNeeded(Query); if (rf.OutputDestination == OutputDest.WinForms) // update access stats if grid { UpdateTableUsageStatistics(Query); } Query.ResultsDataTable = null; // be sure to get new results qm = BuildQueryManager(Query, rf); Query.ResetViewStates(); // reset state of views for proper operation if (Rf.ParentQe == null) // open search unless using existing query engine { if (!ExecuteSearch(saveHitlist)) // returns false if cancelled by user { Progress.Hide(); return(""); } } if ((ResultsKeys == null || ResultsKeys.Count == 0) && // nothing for search !Query.Preview && !MqlUtil.SingleStepExecution(Query) && qm.DataTable.Rows.Count == 0 && Query.RetrievesDataFromQueryEngine) { // if (!Rf.PopupDisplay) Progress.Hide(); if (qm.StatusBarManager != null) { qm.StatusBarManager.DisplayStatusMessage(""); } // if (QueryEngine.Cancelled) return ""; // cancelled by user msg = "No data have been found that matches your query."; if (ResultsFormat.PopupOutputFormContext && !ResultsFormat.SuppressNoDataMessage) { MessageBoxMx.Show(msg, "Search Result", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return("Command EditQuery"); // return to edit query menu } else { return(msg); } } //if (ResultsFormat.PopupDisplay) // SessionManager.DisplayStatusMessage("Retrieving data..."); //else Progress.Show("Retrieving data...", UmlautMobius.Value, true, "Cancelling Retrieval..."); //Progress.Show("Retrieving data...", UmlautMobius.String, true, "Cancelling Retrieval..."); Progress.Hide(); // hide progress - "Retrieving data..." message now appears as bottom line of grid if (ResultsFormat.Grid) { if (ResultsFormat.SessionOutputFormContext) // if normal main session form grid display, set browse mode & view state { Query.ResetViewStates(); // reset view state for all views QbUtil.SetMode(QueryMode.Browse, Query); if (ResultsFormat.Query.LogicType == QueryLogicType.And) // log grid query by logic type { UsageDao.LogEvent("QueryGridAnd", ""); } else if (ResultsFormat.Query.LogicType == QueryLogicType.Or) { UsageDao.LogEvent("QueryGridOr", ""); } else if (ResultsFormat.Query.LogicType == QueryLogicType.Complex) { UsageDao.LogEvent("QueryGridComplex", ""); } } else if (ResultsFormat.PopupOutputFormContext) // create popup window & configure { PopupResults.Show(qm); //MoleculeGridPanel.ConfigureAndShow(qm, null); } else if (ResultsFormat.ToolOutputFormContext) { ContainerControl cc; QueryResultsControl qrc = ResultsFormat.OutputContainerControl as QueryResultsControl; AssertMx.IsTrue(qrc != null, "ResultsFormat.OutputContainerControl must be a QueryResultsControl"); if (!WindowsHelper.FindContainerControl(qrc, typeof(ToolResultsContainer), out cc)) { throw new Exception("ToolResultsContainer not found"); } ToolResultsContainer trc = cc as ToolResultsContainer; trc.SetupQueryResultsControlForResultsDisplay(qm); } else { throw new Exception("Invalid OutputformContext: " + ResultsFormat.OutputFormContext); } } } else // reentering display switch to browse tab { QbUtil.SetMode(QueryMode.Browse, Query); } response = ResultsFormatter.BeginFormatting(browseExistingResults); // format the data if (ResultsFormat.SessionOutputFormContext) // normal display { if (MqlUtil.SingleStepExecution(Query)) { // be sure hit count display is up to date if (ResultsKeys != null) { if (qm.StatusBarManager != null) { qm.StatusBarManager.DisplayCurrentCount(); } } } if (saveHitlist) { CidList hitList = new CidList(ResultsKeys); rc = CidListCommand.WriteCurrentList(hitList); SessionManager.DisplayCurrentCount(); } } return(response); } // end of surrounding try catch (Exception ex) { Progress.Hide(); if (ex is UserQueryException) // exception that can occur from user error { throw new UserQueryException(ex.Message, ex); } else { msg = DebugLog.FormatExceptionMessage(ex); if (!Lex.Contains(msg, "QueryLogged:")) // exception & query { QueryEngine.LogExceptionAndSerializedQuery(msg, Query); } else { ServicesLog.Message(msg); // just log exception } throw new Exception(ex.Message, ex); // pass it up } } }
/// <summary> /// Do basic checks for a valid query /// </summary> /// <param name="query"></param> /// <returns></returns> public static DialogResult ValidateQuery(Query query) { QueryTable firstQueryTable = null, qt; QueryColumn qc; string firstTableKey = ""; int qti, qci; if (query.Tables.Count == 0) { throw new QueryException("Query contains no query tables"); } // If multiple tables make sure key table is first if (query.IncludeRootTableAsNeeded() && query == QbUtil.Query) { QbUtil.RenderQuery(0); // rerender query } firstQueryTable = query.Tables[0]; // make a not of the first table and key firstTableKey = GetParentKey(firstQueryTable); // so we can compare first key with other table keys // Be sure we have some criteria (if other than preview) int totalCriteria = 0; if (query.KeyCriteria != "") { totalCriteria++; } int notExistsCriteria = 0; for (qti = 0; qti < query.Tables.Count; qti++) { qt = query.Tables[qti]; string currentTableKey = GetParentKey(qt); if (qt.KeyQueryColumn == null || currentTableKey == null) { throw new QueryException("Key column is not defined for table: " + qt.MetaTable.Name); } // Code below commented out because it disallowed valid multidatabase queries. // e.g. Search CorpDb and ACD together in same query with a subtable from each database included // Similar to MqlUtil.CheckTableCompatibility which does work properly // Unsure of original intent // -------------------------------------- /// Tables with different keys cannot be combined //if (qti > 0 && firstTableKey != currentTableKey) // throw new DevExpress.PivotGrid.QueryMode.QueryException( // "Tables with different keys cannot be in the same query.\n\n" + // "Key for " + firstQueryTable.ActiveLabel + ": " + firstTableKey + "\n" + // "Key for " + qt.ActiveLabel + ": " + currentTableKey + "\n"); if (!qt.KeyQueryColumn.Selected) // select key column if not done yet { qt.KeyQueryColumn.Selected = true; } for (qci = 0; qci < qt.QueryColumns.Count; qci++) { qc = qt.QueryColumns[qci]; if (qc.MetaColumn == null) { continue; } if (qc.Criteria != "" && qc.FilterSearch && // must be used to filter search !qc.MetaColumn.IsDatabaseSetColumn && !qc.IsKey) // key already counted { totalCriteria++; if (qc.HasNotExistsCriteria) { notExistsCriteria++; } string msg = ""; // check for summarization type mismatch on criteria if (qt.MetaTable.UseSummarizedData && !qc.MetaColumn.SummarizedExists) { msg = "summarized"; } else if (!qt.MetaTable.UseSummarizedData && !qc.MetaColumn.UnsummarizedExists) { msg = "unsummarized"; } if (msg != "" && !SS.I.QueryTestMode) { Progress.Hide(); msg = "This query has criteria on " + qc.ActiveLabel + " which does not exist in the\n" + msg + " view of " + qt.ActiveLabel + ".\n" + "Do you want to remove this criteria from the query?"; DialogResult dr = MessageBoxMx.Show(msg, "Invalid Criteria", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (dr == DialogResult.Yes) { qc.Criteria = qc.CriteriaDisplay = ""; totalCriteria--; if (query == QbUtil.Query) // redraw with possible change (referencing global query) { QbUtil.RenderQuery(QbUtil.Qt); } } else if (dr == DialogResult.Cancel || !Security.IsAdministrator(SS.I.UserName)) { return(DialogResult.Cancel); // can't continue unless administrator } } } } } bool noCriteria = false; if (query.Preview) { noCriteria = false; // don't need criteria if in preview mode } else if (query.LogicType == QueryLogicType.Complex && query.ComplexCriteria != "") { noCriteria = false; // something there for complex } else if (!query.RetrievesDataFromQueryEngine) { noCriteria = false; // don't need criteria if no tables retrieved from query engine } else if (totalCriteria == 0) { noCriteria = true; } //if (query. if (noCriteria) { // if (query.Tables.Count == 1) query.Preview = true; // do as a preview if just one table (this changes expected behavior and can't be done) // else if (SessionManager.CurrentResultKeysCount <= 0) { throw new UserQueryException("You must define at least one criteria for the query"); } else // see if user wants to use current list { Progress.Hide(); DialogResult dr = MessageBoxMx.Show( "This query contains no criteria.\n" + "Do you want to use the current search results (" + SessionManager.CurrentResultKeysCount + ") ?", "No Criteria", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dr != DialogResult.Yes) { return(DialogResult.Cancel); } query.KeyCriteria = " IN LIST CURRENT"; query.KeyCriteriaDisplay = "In current search results list (" + SessionManager.CurrentCountNotNull.ToString() + ")"; foreach (QueryTable qt2 in query.Tables) { qc = qt2.KeyQueryColumn; if (qc != null) { qc.Criteria = query.KeyCriteria; qc.CriteriaDisplay = query.KeyCriteriaDisplay; } } } } else if (query.LogicType != QueryLogicType.Complex && notExistsCriteria >= totalCriteria && !query.Preview && query.RetrievesDataFromQueryEngine) { throw new UserQueryException("At least one table in the query must contain criteria other than \"Doesn't Exist\"."); } query.ValidateAggregation(); return(DialogResult.OK); }
/// <summary> /// Check queued alerts. Several of these process may be running at the same time in parallel. /// </summary> /// <param name="args"></param> /// <returns></returns> public static string CheckQueuedAlerts( string args) { string msg; int i1; bool forceCheck = false; bool checkOnly = false; int firstToCheck = 0; bool hasMoreAlerts = true; int alertsWithNewData = 0; int alertsChecked = 0; string processorIdTxt = ", Pid: " + (int)DateTime.Now.TimeOfDay.TotalSeconds; // mark each message with id of processor (sec of day started) AlertUtil.LogAlertMessage("Queue processor started: " + args + processorIdTxt); if (args != null && args.Trim().Length > 0) { if (Lex.Contains(args, "forceCheck")) { forceCheck = true; } if (Lex.Contains(args, "checkOnly")) { checkOnly = true; } } string alertQueueFileName = GetAlertQueueFileName(); while (hasMoreAlerts) { UserObject uo = GetNextAlert(processorIdTxt, alertQueueFileName); if (uo == null) { break; } int queryId = 0; // get queryId from alert name i1 = uo.Name.IndexOf("_"); if (i1 > 0) { try { queryId = Int32.Parse(uo.Name.Substring(i1 + 1)); } catch (Exception) { } } msg = "Processing Alert: " + uo.Id + ", QueryId: " + queryId + processorIdTxt; // Thread.Sleep(10000); // debug AlertUtil.LogAlertMessage(msg); Progress.Show(msg); DateTime begin = DateTime.Now; try // check it { msg = AlertUtil.Check(uo, forceCheck, checkOnly, false); } catch (Exception ex) { msg = "Error executing Alert: " + uo.Id + ", QueryId: " + queryId + ", Processor: " + processorIdTxt; if (Lex.Contains(ex.Message, "ORA-01012") || Lex.Contains(ex.Message, "ORA-00028")) { msg += ", Error: " + ex.Message; // keep simple if forced logoff } else // include stack trace otherwise { msg += "Error: " + DebugLog.FormatExceptionMessage(ex, msg); } AlertUtil.LogAlertMessage(msg); AlertUtil.LogAlertErrorMessage(msg); alertsChecked++; continue; } if (Lex.Contains(msg, "Delayed Alert")) { AlertUtil.LogAlertMessage(msg); Alert alert = Alert.GetAlertFromUserObject(uo, true); AddAlertBack(alert); SleepUntilNextAlertStartTime(uo); continue; } string msg0 = // message prefix "Completed Alert: " + uo.Id + ", QueryId: " + queryId + processorIdTxt; //DateTime end = DateTime.Now; // (redundant) //TimeSpan elapsed = end.Subtract(begin); //string eTxt = elapsed.ToString(); //if ((i1 = eTxt.IndexOf(".")) > 0) eTxt = eTxt.Substring(0, i1); //msg0 += ", Time to process = " + eTxt; msg = msg0 + " " + msg; AlertUtil.LogAlertMessage(msg); if (Lex.Contains(msg, "Error executing alert")) // keep separate log of errors { AlertUtil.LogAlertErrorMessage(msg); } alertsChecked++; if (msg.Contains("Changed compounds")) { alertsWithNewData++; } } msg = "Queue processor complete, Alerts checked: " + alertsChecked + ", Alert E-mails: " + alertsWithNewData + processorIdTxt; AlertUtil.LogAlertMessage(""); AlertUtil.LogAlertMessage(msg); Progress.Hide(); return(msg); }