public static bool False = Math.Abs(1) == 2; // False constant (avoids compiler warning) /// <summary> /// Log an invalid condition /// </summary> /// <param name="message"></param> public static void InvalidConditionException(string message) { string msg = message + "\r\n" + new StackTrace(true); DebugLog.Message(msg); throw new Exception(msg); }
/// <summary> /// Backup and replace a file /// </summary> /// <param name="destFile">Where the new file should go</param> /// <param name="backupFile">Backup file to move existing dest file to</param> /// <param name="newFile">New file to move to dest file</param> public static bool BackupAndReplaceFile( string destFile, string backupFile, string newFile, bool logErrors) { if (File.Exists(backupFile)) // remove any old backup file { try { File.Delete(backupFile); } catch (Exception ex) { if (logErrors) { DebugLog.Message("Can't delete file: " + backupFile); } } } if (File.Exists(destFile)) { try { File.Move(destFile, backupFile); } // move any existing dest to bak catch (Exception ex) { // try deleting existing dest file if it can't be moved if (logErrors) { DebugLog.Message("Can't move file: " + destFile + " to file: " + backupFile); } try { File.Delete(destFile); } catch (Exception ex2) { if (logErrors) { DebugLog.Message("Can't delete file: " + destFile); } } } } try { File.Move(newFile, destFile); } // move new to dest catch (Exception ex) { { if (logErrors) { DebugLog.Message(DebugLog.FormatExceptionMessage(ex, "Can't move file: " + newFile + " to file: " + destFile, true)); } } return(false); } return(true); }
/// <summary> /// Cancel a connection /// </summary> /// <param name="connectionString"></param> public static void CancelConnection( string connectionString) { int t0 = TimeOfDay.Milliseconds(); connectionString = NormalizeConnectionStringToUncShareName(connectionString); int rv = WNetCancelConnection(connectionString, false); if (DebugAddConnection) { DebugLog.Message("WNetCancelConnection for: " + connectionString + ", time: " + (TimeOfDay.Milliseconds() - t0).ToString() + ", return value: " + rv); // debug } return; }
/// <summary> /// Add a new connection /// </summary> /// <param name="connectionString"></param> /// <param name="accountName"></param> /// <param name="accountPw"></param> /// <param name="interactive"></param> public static void AddConnection( string connectionString, string accountName, string accountPw, bool interactive) { try { int t0 = TimeOfDay.Milliseconds(); connectionString = NormalizeConnectionStringToUncShareName(connectionString); CancelConnection(connectionString); // try to cancel first (seems to make reconnect faster) NetworkConnectionWorker worker = new NetworkConnectionWorker(); worker.connectionString = connectionString; worker.directoryExists = false; worker.accountName = accountName; worker.accountPw = accountPw; worker.interactive = interactive; Thread workerThread = new Thread(new ThreadStart(worker.AddConnection)); workerThread.Name = "AddConnection"; workerThread.Start(); while (!workerThread.IsAlive) { ; // loop until worker thread activates. } while (workerThread.IsAlive) { Thread.Sleep(10); Application.DoEvents(); } //workerThread.Join(); if (worker.ex != null) { throw worker.ex; } } catch (Exception ex) { DebugLog.Message("AddConnection exception: " + DebugLog.FormatExceptionMessage(ex)); } return; }
/// <summary> /// Send mail object /// </summary> /// <param name="mail"></param> public static void Send( MailMessage mail) { string mailServerName = "[server]"; //string mailServerName = "[server]"; using (SmtpClient mailClient = new SmtpClient()) { if (ServicesIniFile.IniFile != null) { mailServerName = ServicesIniFile.Read("SmtpServer"); } mailClient.Host = mailServerName; mailClient.UseDefaultCredentials = true; // mailClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis; // It appears that the SMPTP server is rebooting and is unavailable at 1:01am every morning. // We will pause on a failure and try again up to three times. int attempt = 0; while (attempt < 3) { try { attempt++; mailClient.Send(mail); break; } catch (SmtpException) { if (attempt > 2) { DebugLog.Message("Handled Error: Attempt " + attempt + " of Email.Send failed. Email not sent."); throw; } DebugLog.Message("Mobius Warning: Attempt " + attempt + " of SmtpClient.Send failed. Re-attempting email send..."); Thread.Sleep(10000); // wait 10 seconds } } } }
/// <summary> /// Register bonus skins /// </summary> /// <returns></returns> public static bool BonusSkinsRegister() { try { // load bonus skins assembly if needed, i.e. call DevExpress.UserSkins.BonusSkins.Register(); DevExpress.UserSkins.BonusSkins.Register(); //string dxSkins = GetSkinManagerDefaultSkins(); // debug BonusSkinsRegistered = true; return(true); } catch (Exception ex) { DebugLog.Message("Error registering BonusSkins:\n" + DebugLog.FormatExceptionMessage(ex)); return(false); //DebugLog.Message("Error loading skin: " + lookAndFeelName + "\n" + DebugLog.FormatExceptionMessage(ex)); //lookAndFeelName = "Blue"; // default to blue //si = GetSkinFromInternalName(lookAndFeelName); } }
/// <summary> /// Check if directory exists /// </summary> /// <param name="connectionString"></param> /// <returns></returns> public static bool DirectoryExists(string path) { NetworkConnectionWorker worker = new NetworkConnectionWorker(); worker.path = path; worker.directoryExists = false; int t0 = TimeOfDay.Milliseconds(); if (DebugAddConnection) { DebugLog.Message( "Calling Directory.Exists for: " + path); } Thread workerThread = new Thread(new ThreadStart(worker.DirectoryExists)); workerThread.Name = "DirectoryExists"; workerThread.Start(); while (!workerThread.IsAlive) { ; // loop until worker thread activates. } while (workerThread.IsAlive) // allow limited time to check since may be slow if doesn't exist (~25 secs) { Thread.Sleep(10); Application.DoEvents(); } //workerThread.Join(); // (don't join because causes delay) if (DebugAddConnection) { DebugLog.Message( "Exists = " + worker.directoryExists + " time (ms): " + (TimeOfDay.Milliseconds() - t0).ToString()); } return(worker.directoryExists); }
/// <summary> /// Check if the directory exists /// </summary> internal void DirectoryExists() { try { directoryExists = Directory.Exists(path); } catch (Exception ex2) { ex = ex2; DebugLog.Message("Directory.Exists exception: " + ex.Message); } //if (exists) //{ // seems like this always succeeds as long as the server exists // DateTime dirCreateTime = Directory.GetCreationTime(connectionString); // string root = Directory.GetDirectoryRoot(connectionString); // return; // just return if already exists //} return; }
/// <summary> /// Get bitmap from SVG XML /// </summary> /// <param name="svgXml"></param> /// <param name="bitmapWidth">Desired width in pixels</param> /// <returns></returns> public static Bitmap GetBitmapFromSvgXml( string svgXml, int bitmapWidth) { RectangleF bb = new RectangleF(); if (Lex.IsUndefined(svgXml) || bitmapWidth <= 0) { return(new Bitmap(1, 1)); } try { SvgDocument doc = AdjustSvgDocumentToFitContent(svgXml, bitmapWidth, SvgUnitType.Pixel); if (doc == null) { return(new Bitmap(1, 1)); } int bitmapHeight = 1; if (doc.Width > 0) { bitmapHeight = (int)((doc.Height / doc.Width) * bitmapWidth); } Bitmap bmp = doc.Draw(bitmapWidth, bitmapHeight); // create bitmap //Bitmap bmp = doc.Draw(); // create bitmap if (DebugMx.True && ClientState.IsDeveloper) // debug - dump xml and bitmap { try { FileUtil.WriteFile(@"c:\downloads\SvgUtilTestXml.html", svgXml); bmp.Save(@"c:\downloads\SvgUtilTestBmp.bmp"); } catch (Exception ex) { ex = ex; } } return(bmp); } catch (Exception ex) { DebugLog.Message(ex); throw new Exception(ex.Message, ex); } //SvgAspectRatio aspectRatio = doc.AspectRatio; // aspect of the viewport. //RectangleF docBounds = doc.Bounds; // bounds of the svg element //SvgUnit docLeft = doc.X; // left position //SvgUnit docTop = doc.Y; // top position //SvgUnit docHeight = doc.Height; // height //SvgUnit docWidth = doc.Width; // width //string matchString = "<rect x='.0' y='.0' width='242.0' height='242.0' fill='rgba(0,0,0,0.00)' stroke='none'/>"; //xml = Lex.Replace(xml, matchString, ""); //float xRat = (dr.Width / vb.Width); // * (br.Width / vb.Width); //float yRat = (dr.Height / vb.Height); // * (br.Height / vb.Height); //RectangleF cr = new RectangleF(br.X * xRat, br.Y * yRat, br.Width * xRat, br.Height * yRat); //Bitmap bmp2 = bmp.Clone(cr, bmp.PixelFormat); // extract rectangle }
/// <summary> /// Add the connection /// </summary> internal void AddConnection() { const int ERROR_SUCCESS = 0; NETRESOURCE nr; int t0 = TimeOfDay.Milliseconds(); IntPtr hWndOwner = IntPtr.Zero; //if (Form.ActiveForm != null) hWndOwner = (IntPtr)Form.ActiveForm.Handle; // (May not work because different thread than was created on) nr.dwScope = (int)RESOURCE_SCOPE.RESOURCE_CONNECTED; nr.dwType = (int)RESOURCE_TYPE.RESOURCETYPE_DISK; nr.dwDisplayType = (int)RESOURCE_DISPLAYTYPE.RESOURCEDISPLAYTYPE_GENERIC; nr.dwUsage = (int)RESOURCE_USAGE.RESOURCEUSAGE_CONNECTABLE; nr.LocalName = null; // no local device nr.RemoteName = connectionString; nr.Comment = null; nr.Provider = null; string lpUserName = // need to qualify with domain so the domain is included in the login box System.Environment.UserDomainName + @"\" + System.Environment.UserName; //string lpUserName = null; // use default user name from the context for the process //string lpPassword = ""; // don't use password string lpPassword = null; // use current default password associated with lpUserName (still prompts) if (!Lex.IsNullOrEmpty(accountName) && !Lex.IsNullOrEmpty(accountPw)) // supplied account info? { lpUserName = accountName; lpPassword = accountPw; } int dwFlags = 0; if (interactive) { dwFlags |= (int)CONNECT_FLAGS.CONNECT_INTERACTIVE; // allow interaction //dwFlags |= (int)CONNECT_FLAGS.CONNECT_PROMPT; // force prompt (don't force but will prompt anyway) //dwFlags |= (int)CONNECT_FLAGS.CONNECT_CMD_SAVECRED; // save any credentials } if (DebugAddConnection) { string msg = "WNetAddConnection3 for user: "******"/" + lpPassword + (interactive ? " - Interactive" : " - Non-interactive"); DebugLog.Message(msg); } int rv = WNetAddConnection3(hWndOwner, ref nr, lpPassword, lpUserName, dwFlags); if (DebugAddConnection) { DebugLog.Message("WNetAddConnection3 time: " + (TimeOfDay.Milliseconds() - t0).ToString() + ", return value: " + rv); // debug } if (rv == ERROR_SUCCESS) { return; } ex = new Win32Exception(rv); }
/// <summary> /// Check if the current version of the client is up to date and where it is /// </summary> /// <param name="localIniPath"></param> /// <param name="localIniFile"></param> /// <param name="clientDeploymentDir"></param> /// <param name="remoteIniPath"></param> /// <param name="remoteIniFile"></param> /// <param name="logActivity"></param> /// <returns></returns> public static bool ClientVersionIsUpToDate( out string localIniPath, out IniFile localIniFile, out string clientDeploymentDir, out string remoteIniPath, out IniFile remoteIniFile, bool logActivity) { StreamReader sr = null; string localBinDir = null; localIniPath = ""; localIniFile = null; clientDeploymentDir = ""; remoteIniPath = ""; remoteIniFile = null; try { if (logActivity) { DebugLog.Message("Getting local & remote deployment Ids..."); } localIniPath = DefaultMobiusClientFolder + @"\MobiusClient.ini"; // ini file on client if (!File.Exists(localIniPath)) { localIniPath = Application.StartupPath + @"\MobiusClient.ini"; // ini file on client if (!File.Exists(localIniPath)) { return(true); } } localIniFile = new IniFile(localIniPath, "Mobius"); string localDeploymentId = localIniFile.Read("DeploymentId", "UnknownLocalDeployment"); if (logActivity) { DebugLog.Message("LocalDeploymentId: " + localDeploymentId); } clientDeploymentDir = localIniFile.Read("ClientDeploymentDir", DefaultMobiusClientFolder); if (logActivity) { DebugLog.Message("ClientDeploymentDir: " + clientDeploymentDir); } string remoteBinDir = localIniFile.Read("ServerBinDir"); // bin directory on server where things are if (Lex.IsNullOrEmpty(remoteBinDir)) { throw new Exception("ServerBinDir not defined in " + localIniPath); } remoteIniPath = remoteBinDir + @"\MobiusClient.ini"; // ini file on server try // be sure we can read remote inifile & trap any error { sr = new StreamReader(remoteIniPath); sr.Close(); remoteIniFile = new IniFile(remoteIniPath, "Mobius"); if (remoteIniFile == null) { throw new Exception("Null IniFile Object"); } } catch (Exception ex) { throw new Exception("Can't open remote inifile: " + remoteIniPath + ", " + ex.Message); } string remoteDeploymentId = remoteIniFile.Read("DeploymentId", "UnknownRemoteDeployment"); bool deploymentIdsMatch = (localDeploymentId == remoteDeploymentId); // local & remote deployment ids the same? if (logActivity) { DebugLog.Message("RemoteDeploymentId: " + remoteDeploymentId); } // Get current client deployment dir string clientExePath = clientDeploymentDir + @"\MobiusClient.exe"; // make sure executable is there if (!File.Exists(clientExePath)) { return(false); } if (!deploymentIdsMatch) { return(false); // local & remote deployment ids the same? } return(true); // up to date } catch (Exception ex) { if (logActivity) { string msg = "Client version check failed\r\n" + ex.Message + "\r\n" + ex.StackTrace; DebugLog.Message(msg); MessageBox.Show(msg); } return(true); // say true if error } }