/// <summary> /// Log fatal error & display to user /// </summary> /// <param name="ex"></param> static void LogUnexpectedError(Exception ex) { string msg = DebugLog.FormatExceptionMessage(ex); ClientLog.LogFatalErrorMessage(msg); // special log ClientLog.Message(msg); // regular log MessageBoxMx.ShowError(msg); // show to user }
/// <summary> /// Detailed message loging /// </summary> /// <param name="msg"></param> public static void LogDetailedMessage(string msg) { if (!LogDetailedMessages) { return; } ClientLog.Message(msg); return; }
/// <summary> /// Handler invoked on Application exit to attempt to dispose of the user session /// If /// </summary> /// <param name="sender"></param> /// <param name="e"></param> static void ApplicationExit(object sender, EventArgs e) { try { DebugLog.Message("Exiting"); ServiceFacade.ServiceFacade.DisposeSession(); } catch (Exception ex) { ClientLog.Message(DebugLog.FormatExceptionMessage(ex)); // just log it } }
/// <summary> /// Get splash image from server and display /// </summary> public void SetSplashImage() { try { string splashImageDir = Splash.Instance.IniFile.Read("SplashImageDir"); // ClientLog.Message("SplashImageDir: " + splashImageDir); // debug string tok = Splash.Instance.IniFile.Read("SplashImageCount"); // ClientLog.Message("SplashImageCount: " + tok); // debug int splashCount = 0; Int32.TryParse(tok, out splashCount); int imageIdx = 1; tok = Splash.Instance.UserIniFile.Read("SplashImageIndex"); // ClientLog.Message("SplashImageIndex: " + tok); // debug if (tok != "") { imageIdx = Int32.Parse(tok) + 1; if (imageIdx > splashCount) { imageIdx = 1; } } Splash.Instance.UserIniFile.Write("SplashImageIndex", imageIdx.ToString()); // int ms = System.DateTime.Now.Millisecond; // int imageIdx = ms % splashCount + 1; // index of image to use string splashImagePath = // name of splash file on server splashImageDir + @"\Nature" + imageIdx.ToString() + ".jpg"; int t0 = TimeOfDay.Milliseconds(); if (File.Exists(splashImagePath)) { Splash.Instance.SetImage(new Bitmap(splashImagePath)); Splash.Instance.Invalidate(); Application.DoEvents(); } t0 = TimeOfDay.Milliseconds() - t0; } catch (Exception ex) { ClientLog.Message("Splash display error: " + ex.Message); } }
static void Main(string[] args) { Splash splash = null; bool unattended = false; bool startedByMobiusClientStart = false; string username = "", msg; string argString = ""; for (int ai = 0; ai < args.Length; ai++) { string arg = args[ai]; Lex.AppendToList(ref argString, " ", arg); // append arg separating by a space if (Lex.Eq(arg, "username") && ai + 2 < args.Length) { username = args[ai + 2].ToUpper(); } if (Lex.Eq(arg, "StartedByMobiusClientStart")) { startedByMobiusClientStart = true; } if (Lex.Eq(arg, "unattended")) { unattended = true; } } string machineName = Environment.MachineName; LogDetailedMessages = // flag to do special detailed logging Lex.Contains(machineName, "<server>"); // If not started by MobiusClientStart then do our own check to see if we are the current version if (!startedByMobiusClientStart) { UpdateClientVersionIfNecessary(); } ClientLog.Initialize(username); // initialize client logging ClientLog.Message("Mobius.Client started, ParmString: " + argString); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // must be done before first window is opened /* * DevExpress.XtraEditors.WindowsFormsSettings.SetDPIAware(); // don't do unless Mobius refactored as a DPI aware app (e.g. DX LayoutControl) * Note that setting Override high DPI scaling behavior = System (Enhanced) for the Mobius app can be used * to provide better Win 10 rendering for high DPI displays and/or non-100% display scaling * * To prevent the DevExpress de, es, ja, ru folders from being created delete the language files * under: C:\Program Files(x86)\DevExpress 19.1\Components\Bin\Framework (replace the version with the current version) */ // Set up handling of unexpected exits Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(ThreadException); // Occurs when an untrapped thread exception is thrown Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); // Always route exceptions to the System.Windows.Forms.Application.ThreadException handler AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Application.ThreadExit += new EventHandler(ThreadExit); Application.ApplicationExit += new EventHandler(ApplicationExit); ApplicationRecovery.OnApplicationCrash += new ApplicationRecovery.ApplicationCrashHandler(ApplicationRecovery_OnApplicationCrash); // try to catch crashes not caught via c# exceptions ApplicationRecovery.RegisterForRestart(); ///////////////////// // Development tests ///////////////////// //SpotfireApiClient.UseAnalystClient = true; // debug bool RunDevTest = false; if (RunDevTest) // && ClientState.IsDeveloper) // do a quick dev test & then exit { if (DebugMx.True) { Mobius.KekuleJs.KekuleTestForm f = new Mobius.KekuleJs.KekuleTestForm(); Application.Run(f); return; } if (DebugMx.False) { MoleculeViewer v = new MoleculeViewer(); Application.Run(v); return; } if (DebugMx.False) { //NCDK_Example.DepictionGenerator_Example.Run(); //string version = java.lang.Package.getPackage("java.lang").getImplementationVersion(); //StreamReader sr = new StreamReader(@"c:\downloads\aspirin.mol"); //string molfile = sr.ReadToEnd(); //sr.Close(); //IAtomContainer ac = CdkMol.MolfileToAtomContainer(molfile); //if (DebugMx.False) // Helm editor //{ // Helm.CefMx.InitializeCef(); // HelmEditorDialog editor = new HelmEditorDialog(); // string helm = "PEPTIDE1{A.L.C}$$$$"; // string newHelm = editor.Edit(helm); // return; // } if (DebugMx.False) { RelatedCompoundsDialog rcd = new RelatedCompoundsDialog(); rcd.QueryMolCtl.SetPrimaryTypeAndValue(MoleculeFormat.Smiles, "CC(=O)OC1=CC=CC=C1C(=O)O"); // aspirin Application.Run(rcd); return; } if (DebugMx.False) // Spotfire API test form { Application.Run(new Mobius.SpotfireClient.TestMobiusSpotfireApiForm()); //Application.Run(new Mobius.SpotfireClient.ScatterPlotPropertiesDialog()); return; } //string shares = DirectoryMx.GetSharedFolderAccessRule(); // get shares //if (DebugMx.False) // test old Spotfire Webplayer interface //{ // Application.Run(new Mobius.SpotfireClient.TestWebplayerInterfaceForm()); // return; //} //Mobius.ComOps.SVGParser.Test(); //string windowsLoginName = WindowsIdentity.GetCurrent().Name; //if (Lex.Eq(windowsLoginName, "<UserDomainAndName>")) // debugging settings //{ // CommandLineService.ExecuteCommand("Set DebugQE true"); // CommandLineService.ExecuteCommand("Set DebugDbCmd true"); //} //if (DebugMx.True) while (true) { new BitmapTest().ShowDialog(); } //RunDevTestMethod(); //return; } /////////////////////////// // End of Development tests /////////////////////////// // Check for required software versions if (!SessionManager.CheckForCorrectSoftwareVersions()) { Environment.Exit(-1); } // Put up splash screen Splash.Unattended = unattended; LogDetailedMessage("Putting up splash"); try { //if (Math.Abs(1) == 1) throw new Exception("Fatal Error Test"); // debug //if (!Lex.Contains(argString, "Attempt 3")) throw new Exception("Fatal Error Test"); // debug IniFile iniFile = null; // Put up splash screen if (splash == null) { splash = Splash.ShowForm(); } iniFile = MobiusClientUtil.OpenAppropriateClientIniFile(); if (iniFile == null) { throw new Exception("MobiusClient.ini not found"); } msg = "Startup iniFile: " + iniFile.IniFileName; ClientLog.Message(msg); // Initialize services and get a session, session is created asynch while rest of client code loads in try { int t0 = TimeOfDay.Milliseconds(); bool asynch = true; // initialize session asynch ServiceFacade.ServiceFacade.CreateSession(iniFile, argString, asynch); t0 = TimeOfDay.Milliseconds() - t0; LogDetailedMessage("ServiceFacade.Initialize time (asynch): " + t0); } catch (Exception ex) { msg = "ServiceFacade.Initialize failed:" + "\r\n\r\n" + DebugLog.FormatExceptionMessage(ex); DebugLog.Message(msg); ClientLog.Message(msg); MessageBoxMx.ShowError(msg); return; } LogDetailedMessage("Creating SessionManager"); SessionManager = new SessionManager(); SessionManager.Splash = splash; // Setup and display the Shell LogDetailedMessage("Setting up Shell"); Shell shell = new Shell(); // create the shell form SessionManager.ShellForm = shell; SessionManager.MainMenuControl = shell.MainMenuControl; SessionManager.HelpButton = shell.HelpButtonItem; SessionManager.RibbonCtl = shell.Ribbon; SessionManager.QuickSearchControl = shell.CommandLine; StatusBarManager sbm = SessionManager.StatusBarManager; SessionManager.StatusBarManager.StatusBarCtl = shell.StatusBar; LogDetailedMessage("Setting up Status Controls"); sbm.SetupStatusControls( shell.RetrievalProgressBar, shell.RetrievalProgressButton, shell.RowCountCtl, shell.DatabaseSubsetButtonItem, shell.ClearFiltersCtl, shell.FiltersEnabledCtl, shell.FilterStringCtl); LogDetailedMessage("Setting up Zoom Controls"); sbm.SetupViewZoomControls( shell.ZoomButtonItem, shell.ZoomPctBarItem, shell.ZoomSlider); SessionManager.QueriesControl = shell.QueriesControl; //SystemUtil.Beep(); if (!SessionManager.Initialize(argString)) { return; // Initialize the session, just return if init fails } //SystemUtil.Beep(); LogDetailedMessage("Calling Application.Run"); Application.Run(shell); // show the shell & start message loop return; // app normally never gets here } catch (Exception ex) // unexpected fatal error { if (unattended && !argString.Contains("Attempt 3")) // try restart up to three times if unattended { int attempt = 1; if (!Lex.Contains(argString, "Attempt")) { argString += " Attempt 2"; // get current attempt number and set new attempt } else if (Lex.TryReplace(ref argString, "Attempt 2", "Attempt 3")) { attempt = 2; } else { attempt = 3; } ClientLog.Message("Startup error, Attempt: " + attempt + ", " + DebugLog.FormatExceptionMessage(ex)); Process p = Process.Start(Application.ExecutablePath, argString); return; } LogUnexpectedError(ex); // log message and exit return; } }
/// <summary> /// Thread exit /// </summary> /// <param name="sender"></param> /// <param name="e"></param> static void ThreadExit(object sender, EventArgs e) { ClientLog.Message("ThreadExit"); }
/// <summary> /// ExportToPyMolMethod /// </summary> /// <param name="url"></param> /// <param name="qm"></param> void ExportToPyMolMethod( string url, string densityMapUrl, string target, QueryManager qm) { StreamWriter sw; string rec, msg, scriptSourceFile, pluginSourceFile, script; bool includeProtein = true; // always include protein //bool includeElectronDensity = IncludeElectronDensityPyMol.Checked; if (!IncludeElectronDensityPyMol.Checked) { _qcDensity = null; } pluginSourceFile = CommonConfigInfo.MiscConfigDir + @"\CorpView.py"; // the PyMOL plugin CopyToReadLockedFile(pluginSourceFile, CommonConfigInfo.MiscConfigDir + @"\CorpView2.py"); // move CorpView2.py to CorpView.py if (!File.Exists(pluginSourceFile)) { throw new Exception("Plugin file not found: " + pluginSourceFile); } scriptSourceFile = CommonConfigInfo.MiscConfigDir + @"\CorpView.pml"; // the script that starts pymol & hands it the .csv file CopyToReadLockedFile(scriptSourceFile, CommonConfigInfo.MiscConfigDir + @"\CorpView2.pml"); if (!File.Exists(scriptSourceFile)) { throw new Exception("Script file not found: " + scriptSourceFile); } string csvFile = ClientDirs.TempDir + @"\PyMolBatchLoad.csv"; // the .csv file to write WriteCsvFile(csvFile, ExportSingle.Checked, _qcProtein, _qcDensity, _qcTarget, qm, url, densityMapUrl, target); //qm.Query.Tables[0].MetaTable.Name try // Read the CorpView2.pml that gets edited. { StreamReader sr = new StreamReader(scriptSourceFile); script = sr.ReadToEnd(); sr.Close(); } catch (Exception ex) { throw new Exception("Error reading " + scriptSourceFile + ": " + ex.Message); } // Get the path to the plugin file string pluginFile = null; Lex lex = new Lex("="); lex.OpenString(script); while (true) { string tok = lex.Get(); if (tok == "") { break; } if (Lex.Ne(tok, "pluginLocation")) { continue; } pluginFile = lex.Get(); if (pluginFile == "=") { pluginFile = lex.Get(); } pluginFile = Lex.RemoveSingleQuotes(pluginFile); } if (pluginFile == null) { throw new Exception("Can't find definition of plugin location"); } // Get the proper plugin directory string pluginFolder = Path.GetDirectoryName(pluginFile); if (!Directory.Exists(pluginFolder)) { string pluginFile2 = pluginFile; pluginFile2 = Lex.Replace(pluginFile2, "Progra~1", "Progra~2"); // Win7 x86 folder using 8.3 names pluginFile2 = Lex.Replace(pluginFile2, "Program Files", "Program Files (x86)"); // Win7 x86 folder with regular names string pluginFolder2 = Path.GetDirectoryName(pluginFile2); if (!Directory.Exists(pluginFolder2)) { DebugLog.Message("Can't find PyMOL plugin folder: " + pluginFolder); MessageBox.Show("Can't find PyMol plugin folder " + pluginFolder + ".\rContact Pymol Support team."); Progress.Hide(); return; } script = Lex.Replace(script, pluginFile, pluginFile2); // substitute proper plugin file name in script pluginFile = pluginFile2; } bool update = false; bool pyMolInstalled = File.Exists(pluginFile); ClientLog.Message("Checking for PyMol installation..."); if (pyMolInstalled) { DateTime dt1 = File.GetLastWriteTime(pluginSourceFile); DateTime dt2 = File.GetLastWriteTime(pluginFile); if (DateTime.Compare(dt1, dt2) > 0) { ClientLog.Message(" PyMol file is older than the Mobius version."); update = true; } } else { ClientLog.Message(" Could not find PyMol file: " + pluginFile); update = true; } // Be sure the plugin is up to date if (update) { try { File.Copy(pluginSourceFile, pluginFile, true); // copy CorpView.py to Pymol startup dir } catch (Exception ex) { ClientLog.Message(" Error copying CorpView.py to: " + pluginFile + ", " + ex.Message); if (!pyMolInstalled) { MessageBox.Show("Unable to find Corp Plugin (CorpView.py) for Pymol.\rWindows 7 will not allow Mobius access to copy the plugin to your machine.\rContact Pymol Support team."); Progress.Hide(); return; } } } DebugLog.Message("Error copying CorpView.py to: " + pluginFile); // Plug the csv file name into the script string csvFileNameParm = "<csv-file-name>"; if (!Lex.Contains(script, csvFileNameParm)) { throw new Exception("<csv-file-name> not found in script"); } string csvFileNameForScript = csvFile.Replace(@"\", "/"); // translate backslashes so they aren't interpreted as escapes script = Lex.Replace(script, csvFileNameParm, csvFileNameForScript); string scriptFile = ClientDirs.TempDir + @"\CorpView.pml"; sw = new StreamWriter(scriptFile); sw.Write(script); sw.Close(); Progress.Show("Passing data to PyMOL..."); try { //DebugLog.Message("startFile: " + startFile); //DebugLog.Message("startArgs: " + startArgs); Process p = Process.Start(scriptFile); } catch (Exception ex) { MessageBoxMx.ShowError("Failed to start PyMOL"); Progress.Hide(); return; } System.Threading.Thread.Sleep(3000); // leave message up a bit while PyMOL is starting/being activated Progress.Hide(); }