private void App_OnStartup(object sender, StartupEventArgs e) { var globalMutex = new GlobalMutex("clawPDF-137a7751-1070-4db4-a407-83c1625762c7"); globalMutex.Acquire(); AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Thread.CurrentThread.Name = "ProgramThread"; try { LoggingHelper.InitFileLogger("clawPDF", LoggingLevel.Error); RunApplication(e.Args); } catch (Exception ex) { Logger.Error(ex, "There was an error while starting clawPDF"); } finally { globalMutex.Release(); Logger.Debug("Ending clawPDF"); Shutdown(); } }
public static int Main(string[] args) { if (args.Length > 0 && args[0] == "/exit") { return(CloseRunningInstance().GetAwaiter().GetResult()); } App.InitializeSettings(); // Make sure the settings are properly saved in the end AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit; // Keep the setup away GlobalMutex.Create("Unclassified.MiniWebCompiler"); if (!GlobalMutex.Instance.TryWait(0)) { MessageBox.Show("Another instance is already running.", App.Name, MessageBoxButton.OK, MessageBoxImage.Information); Environment.Exit(1); } try { var app = new App(); app.InitializeComponent(); app.Run(); return(0); } catch (Exception ex) { MessageBox.Show("An unexpected error has occurred.\n" + ex.ToString(), "Mini Web Compiler Error", MessageBoxButton.OK, MessageBoxImage.Error); return(1); } }
public void GlobalMutex_Basic() { #if WINFULL var thread = new Thread(new ThreadStart(ThreadProc)); #else var thread = new CEThread(new ThreadStart(ThreadProc)); #endif mutex1 = new GlobalMutex("Test"); mutex2 = new GlobalMutex("Test"); try { mutex1.WaitOne(); thread.Start(); Thread.Sleep(1100); mutex1.ReleaseMutex(); Thread.Sleep(1000); Assert.IsTrue(finishTime - startTime >= TimeSpan.FromMilliseconds(1000)); } finally { mutex1.Close(); mutex2.Close(); thread.Join(); } }
public static void Main() { // Set the image file's build action to "Resource" and "Never copy" for this to work. if (!Debugger.IsAttached) { App.SplashScreen = new SplashScreen("Images/TxFlag_256.png"); App.SplashScreen.Show(false, true); } // Set up FieldLog FL.AcceptLogFileBasePath(); FL.RegisterPresentationTracing(); TaskHelper.UnhandledTaskException = ex => FL.Critical(ex, "TaskHelper.UnhandledTaskException", true); // Keep the setup away GlobalMutex.Create("Unclassified.TxEditor"); App.InitializeSettings(); // Make sure the settings are properly saved in the end AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit; // Setup logging //Tx.LogFileName = "tx.log"; //Tx.LogFileName = ""; //Environment.SetEnvironmentVariable("TX_LOG_UNUSED", "1", EnvironmentVariableTarget.User); //Environment.SetEnvironmentVariable("TX_LOG_UNUSED", null, EnvironmentVariableTarget.User); InitializeLocalisation(); App app = new App(); app.InitializeComponent(); app.Run(); }
/// <summary> /// Cleans up the SLDR. This should be called to properly clean up SLDR resources. /// </summary> public static void Cleanup() { CheckInitialized(); _sldrCacheMutex.Dispose(); _sldrCacheMutex = null; _languageTags = null; }
public void Initialize_CreatedNew_ReturnsTrue() { using (var mutex = new GlobalMutex("test")) { mutex.Unlink(); Assert.That(mutex.Initialize(), Is.True); } }
private static GlobalMutex AcquireMutex() { var globalMutex = new GlobalMutex("PDFCreator-137a7751-1070-4db4-a407-83c1625762c7"); globalMutex.Acquire(); return(globalMutex); }
protected override int StartupInternal(int currentModelVersion) { CreateSettingsStores(); m_commitLogMutex = new GlobalMutex(MutexName); bool createdNew; using (m_commitLogMutex.InitializeAndLock(out createdNew)) { CreateSharedMemory(createdNew); using (MemoryMappedViewStream stream = m_commitLogMetadata.CreateViewStream()) { CommitLogMetadata metadata = null; if (!createdNew) { if (TryGetMetadata(stream, out metadata)) { CheckExitedPeerProcesses(metadata); if (m_peerProcesses.Count == 0) { createdNew = true; } } else { createdNew = true; } } if (createdNew) { metadata = new CommitLogMetadata(); } using (Process curProcess = Process.GetCurrentProcess()) metadata.Peers[m_peerID] = new CommitLogPeer { ProcessID = curProcess.Id, Generation = metadata.FileGeneration }; if (metadata.Master == Guid.Empty) { base.LockProject(); metadata.Master = m_peerID; } int startupModelVersion = ReadInSurrogates(currentModelVersion); // non-master peers cannot migrate the XML file if (startupModelVersion < currentModelVersion && metadata.Master != m_peerID) { throw new LcmDataMigrationForbiddenException(); } SaveMetadata(stream, metadata); return(startupModelVersion); } } }
public void Initialize_Existing_ReturnsFalse() { using (var mutex1 = new GlobalMutex("test")) { mutex1.Initialize(); using (var mutex2 = new GlobalMutex("test")) Assert.That(mutex2.Initialize(), Is.False); } }
/// <summary> /// Cleans up the SLDR. This should be called to properly clean up SLDR resources. /// </summary> public static void Cleanup() { CheckInitialized(); _sldrCacheMutex.Dispose(); _sldrCacheMutex = null; _languageTags = null; IcuRulesCollator.DisposeCollators(); }
public void InitializeAndLock_Reentrancy_DoesNotBlock() { using (var mutex = new GlobalMutex("test")) { using (mutex.InitializeAndLock()) { using (mutex.Lock()) {} } } }
public void InitializeAndLock_CreatedNew_ReturnsTrue() { using (var mutex = new GlobalMutex("test")) { mutex.Unlink(); bool createdNew; using (mutex.InitializeAndLock(out createdNew)) {} Assert.That(createdNew, Is.True); } }
protected override void OnStartup(StartupEventArgs e) { if (!GlobalMutex.TryGetMutex()) { Environment.Exit(0); } else { base.OnStartup(e); } }
static void Main() { // Set up FieldLog FL.AcceptLogFileBasePath(); // Keep the setup away GlobalMutex.Create("Unclassified.EasyPdfSigning"); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new EasyForm()); }
protected virtual void Dispose(bool disposing) { if (GlobalMutex == null) { return; } if (disposing) { GlobalMutex.Close(); } GlobalMutex = null; }
public void InitializeAndLock_Existing_ReturnsFalse() { using (var mutex1 = new GlobalMutex("test")) { mutex1.Initialize(); using (var mutex2 = new GlobalMutex("test")) { bool createdNew; using (mutex2.InitializeAndLock(out createdNew)) {} Assert.That(createdNew, Is.False); } } }
/// <summary> /// This method is used for testing purposes. /// </summary> internal static void Initialize(bool offlineMode, string sldrCachePath, DateTime embeddedAllTagsTime) { if (IsInitialized) { throw new InvalidOperationException("The SLDR has already been initialized."); } _sldrCacheMutex = new GlobalMutex("SldrCache"); _sldrCacheMutex.Initialize(); _offlineMode = offlineMode; SldrCachePath = sldrCachePath; _embeddedAllTagsTime = embeddedAllTagsTime; }
protected override void OnStartup(StartupEventArgs e) { Directory.SetCurrentDirectory(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); if (!GlobalMutex.TryGetMutex()) { Environment.Exit(0); } else { base.OnStartup(e); } ServicePointManager.DefaultConnectionLimit = 25; }
public static void Main() { App.InitializeSettings(); // Make sure the settings are properly saved in the end AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit; InitializeLocalisation(); // Keep the setup away GlobalMutex.Create("Unclassified.CecilExplorer"); App app = new App(); app.InitializeComponent(); app.Run(); }
public static void Main() { // Set up FieldLog FL.AcceptLogFileBasePath(); FieldLogTraceListener.Start(); TaskHelper.UnhandledTaskException = ex => FL.Critical(ex, "TaskHelper.UnhandledTaskException", true); App.InitializeSettings(); // Make sure the settings are properly saved in the end AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit; // Keep the setup away GlobalMutex.Create("Unclassified.FieldLogViewer"); App app = new App(); app.InitializeComponent(); app.Run(); }
protected override void CreateInternal() { m_commitLogMutex = new GlobalMutex(MutexName); using (m_commitLogMutex.InitializeAndLock()) { CreateSharedMemory(true); var metadata = new CommitLogMetadata { Master = m_peerID }; using (Process curProcess = Process.GetCurrentProcess()) metadata.Peers[m_peerID] = new CommitLogPeer { ProcessID = curProcess.Id, Generation = metadata.FileGeneration }; using (MemoryMappedViewStream stream = m_commitLogMetadata.CreateViewStream()) { SaveMetadata(stream, metadata); } base.CreateInternal(); } }
protected override void OnExit(ExitEventArgs e) { GlobalMutex.ReleaseMutex(); base.OnExit(e); }
public void run(PackageResult packageResult, ChocolateyConfiguration config) { var installDirectory = packageResult != null ? packageResult.InstallLocation : string.Empty; if (string.IsNullOrWhiteSpace(installDirectory) || installDirectory.is_equal_to(ApplicationParameters.InstallLocation) || installDirectory.is_equal_to(ApplicationParameters.PackagesLocation)) { var logMessage = "Install location is not specific enough, cannot capture files:{0} Erroneous install location captured as '{1}'".format_with(Environment.NewLine, installDirectory); if (packageResult != null) { packageResult.Messages.Add(new ResultMessage(ResultType.Warn, logMessage)); } this.Log().Error(logMessage); return; } var transformFiles = _fileSystem.get_files(installDirectory, "*" + ApplicationParameters.ConfigFileTransformExtension, SearchOption.AllDirectories); foreach (var transformFile in transformFiles.or_empty_list_if_null()) { this.Log().Debug(() => "Preparing transform for '{0}'".format_with(transformFile)); var targetFileName = _fileSystem.get_file_name(transformFile.Replace(ApplicationParameters.ConfigFileTransformExtension, string.Empty)); // target files must exist, otherwise one is added next to the transform var targetFiles = _fileSystem.get_files(installDirectory, targetFileName, SearchOption.AllDirectories); var targetFilesTest = targetFiles as IList <string> ?? targetFiles.ToList(); if (!targetFilesTest.Any()) { targetFiles = new[] { transformFile.Replace(ApplicationParameters.ConfigFileTransformExtension, string.Empty) }; this.Log().Debug(() => "No matching files found for transform {0}.{1} Creating '{2}'".format_with(_fileSystem.get_file_name(transformFile), Environment.NewLine, targetFiles.FirstOrDefault())); } foreach (var targetFile in targetFilesTest.or_empty_list_if_null()) { GlobalMutex.enter( () => { var backupTargetFile = targetFile.Replace(ApplicationParameters.PackagesLocation, ApplicationParameters.PackageBackupLocation); FaultTolerance.try_catch_with_logging_exception( () => { // if there is a backup, we need to put it back in place // the user has indicated they are using transforms by putting // the transform file into the folder, so we will override // the replacement of the file and instead pull from the last // backup and let the transform to its thing instead. if (_fileSystem.file_exists(backupTargetFile)) { this.Log().Debug(() => "Restoring backup configuration file for '{0}'.".format_with(targetFile)); _fileSystem.copy_file(backupTargetFile, targetFile, overwriteExisting: true); } }, "Error replacing backup config file", throwError: false, logWarningInsteadOfError: true); try { this.Log().Info(() => "Transforming '{0}' with the data from '{1}'".format_with(_fileSystem.get_file_name(targetFile), _fileSystem.get_file_name(transformFile))); using (var transformation = new XmlTransformation(_fileSystem.read_file(transformFile), isTransformAFile: false, logger: null)) { using (var document = new XmlTransformableDocument { PreserveWhitespace = true }) { using (var inputStream = _fileSystem.open_file_readonly(targetFile)) { document.Load(inputStream); } // before applying the XDT transformation, let's make a // backup of the file that should be transformed, in case // things don't go correctly this.Log().Debug(() => "Creating backup configuration file for '{0}'.".format_with(targetFile)); _fileSystem.copy_file(targetFile, backupTargetFile, overwriteExisting: true); bool succeeded = transformation.Apply(document); if (succeeded) { this.Log().Debug(() => "Transform applied successfully for '{0}'".format_with(targetFile)); using (var memoryStream = new MemoryStream()) { document.Save(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); using (var fileStream = _fileSystem.create_file(targetFile)) { fileStream.SetLength(0); memoryStream.CopyTo(fileStream); } } // need to test that the transformed configuration file is valid // XML. We can test this by trying to load it again into an XML document try { this.Log().Debug(() => "Verifying transformed configuration file..."); document.Load(targetFile); this.Log().Debug(() => "Transformed configuration file verified."); } catch (Exception) { this.Log().Warn(() => "Transformed configuration file doesn't contain valid XML. Restoring backup file..."); _fileSystem.copy_file(backupTargetFile, targetFile, overwriteExisting: true); this.Log().Debug(() => "Backup file restored."); } } else { // at this point, there is no need to restore the backup file, // as the resulting transform hasn't actually been written to disk. this.Log().Warn(() => "Transform failed for '{0}'".format_with(targetFile)); } } } } catch (Exception) { FaultTolerance.try_catch_with_logging_exception( () => { // something went wrong with the transformation, so we should restore // the original configuration file from the backup this.Log().Warn(() => "There was a problem transforming configuration file, restoring backup file..."); _fileSystem.copy_file(backupTargetFile, targetFile, overwriteExisting: true); this.Log().Debug(() => "Backup file restored."); }, "Error restoring backup configuration file."); } }, MUTEX_TIMEOUT); } } }
public static GetChocolatey GetChocolatey(bool initializeLogging) { return(GlobalMutex.enter(() => set_up(initializeLogging), 10)); }
protected override void ShutdownInternal() { if (m_commitLogMutex != null && m_commitLogMetadata != null) { CompleteAllCommits(); using (m_commitLogMutex.Lock()) { #if __MonoCS__ bool delete = false; #endif using (MemoryMappedViewStream stream = m_commitLogMetadata.CreateViewStream()) { CommitLogMetadata metadata; if (TryGetMetadata(stream, out metadata)) { if (metadata.Master == m_peerID) { // commit any unseen foreign changes List <ICmObjectSurrogate> foreignNewbies; List <ICmObjectSurrogate> foreignDirtballs; List <ICmObjectId> foreignGoners; if (GetUnseenForeignChanges(metadata, out foreignNewbies, out foreignDirtballs, out foreignGoners)) { var newObjects = new HashSet <ICmObjectOrSurrogate>(foreignNewbies); var editedObjects = new HashSet <ICmObjectOrSurrogate>(foreignDirtballs); var removedObjects = new HashSet <ICmObjectId>(foreignGoners); IEnumerable <CustomFieldInfo> fields; if (HaveAnythingToCommit(newObjects, editedObjects, removedObjects, out fields) && (StartupVersionNumber == ModelVersion)) { base.WriteCommitWork(new CommitWork(newObjects, editedObjects, removedObjects, fields)); } } // XML file is now totally up-to-date metadata.FileGeneration = metadata.CurrentGeneration; } RemovePeer(metadata, m_peerID); #if __MonoCS__ delete = metadata.Peers.Count == 0; #endif SaveMetadata(stream, metadata); } } base.UnlockProject(); m_commitLog.Dispose(); m_commitLog = null; m_commitLogMetadata.Dispose(); m_commitLogMetadata = null; #if __MonoCS__ if (delete) { File.Delete(Path.Combine(m_commitLogDir, CommitLogMetadataName)); File.Delete(Path.Combine(m_commitLogDir, CommitLogName)); m_commitLogMutex.Unlink(); } #endif } } if (m_commitLogMutex != null) { m_commitLogMutex.Dispose(); m_commitLogMutex = null; } if (CommitThread != null) { CommitThread.Stop(); CommitThread.Dispose(); CommitThread = null; } foreach (Process peerProcess in m_peerProcesses.Values) { peerProcess.Close(); } m_peerProcesses.Clear(); }
public XmlType deserialize <XmlType>(string xmlFilePath, int retryCount) { return(FaultTolerance.retry(retryCount, () => GlobalMutex.enter( () => { this.Log().Trace("Entered mutex to deserialize '{0}'".format_with(xmlFilePath)); return FaultTolerance.try_catch_with_logging_exception( () => { var xmlSerializer = new XmlSerializer(typeof(XmlType)); using (var fileStream = _fileSystem.open_file_readonly(xmlFilePath)) using (var fileReader = new StreamReader(fileStream)) using (var xmlReader = XmlReader.Create(fileReader)) { if (!xmlSerializer.CanDeserialize(xmlReader)) { this.Log().Warn("Cannot deserialize response of type {0}", typeof(XmlType)); return default(XmlType); } try { return (XmlType)xmlSerializer.Deserialize(xmlReader); } catch (InvalidOperationException ex) { // Check if its just a malformed document. if (ex.Message.Contains("There is an error in XML document")) { // If so, check for a backup file and try an parse that. if (_fileSystem.file_exists(xmlFilePath + ".backup")) { using (var backupStream = _fileSystem.open_file_readonly(xmlFilePath + ".backup")) using (var backupReader = new StreamReader(backupStream)) using (var backupXmlReader = XmlReader.Create(backupReader)) { var validConfig = (XmlType)xmlSerializer.Deserialize(backupXmlReader); // If there's no errors and it's valid, go ahead and replace the bad file with the backup. if (validConfig != null) { // Close fileReader so that we can copy the file without it being locked. fileReader.Close(); _fileSystem.copy_file(xmlFilePath + ".backup", xmlFilePath, overwriteExisting: true); } return validConfig; } } } throw; } finally { foreach (var updateFile in _fileSystem.get_files(_fileSystem.get_directory_name(xmlFilePath), "*.update").or_empty_list_if_null()) { this.Log().Debug("Removing '{0}'".format_with(updateFile)); FaultTolerance.try_catch_with_logging_exception( () => _fileSystem.delete_file(updateFile), errorMessage: "Unable to remove update file", logDebugInsteadOfError: true, isSilent: true ); } } } }, "Error deserializing response of type {0}".format_with(typeof(XmlType)), throwError: true); }, MUTEX_TIMEOUT), waitDurationMilliseconds: 200, increaseRetryByMilliseconds: 200)); }
public void serialize <XmlType>(XmlType xmlType, string xmlFilePath, bool isSilent) { _fileSystem.create_directory_if_not_exists(_fileSystem.get_directory_name(xmlFilePath)); FaultTolerance.retry(3, () => GlobalMutex.enter( () => { this.Log().Trace("Entered mutex to serialize '{0}'".format_with(xmlFilePath)); FaultTolerance.try_catch_with_logging_exception( () => { var xmlSerializer = new XmlSerializer(typeof(XmlType)); this.Log().Trace("Opening memory stream for xml file creation."); using (var memoryStream = new MemoryStream()) using (var streamWriter = new StreamWriter(memoryStream, encoding: new UTF8Encoding(encoderShouldEmitUTF8Identifier: true)) { AutoFlush = true } ){ xmlSerializer.Serialize(streamWriter, xmlType); streamWriter.Flush(); // Grab the hash of both files and compare them. this.Log().Trace("Hashing original file at '{0}'".format_with(xmlFilePath)); var originalFileHash = _hashProvider.hash_file(xmlFilePath); memoryStream.Position = 0; if (!originalFileHash.is_equal_to(_hashProvider.hash_stream(memoryStream))) { this.Log().Trace("The hashes were different."); // If there wasn't a file there in the first place, just write the new one out directly. if (string.IsNullOrEmpty(originalFileHash)) { this.Log().Debug("There was no original file at '{0}'".format_with(xmlFilePath)); memoryStream.Position = 0; _fileSystem.write_file(xmlFilePath, () => memoryStream); this.Log().Trace("Closing xml memory stream."); memoryStream.Close(); streamWriter.Close(); return; } // Otherwise, create an update file, and resiliently move it into place. var tempUpdateFile = xmlFilePath + "." + Process.GetCurrentProcess().Id + ".update"; this.Log().Trace("Creating a temp file at '{0}'".format_with(tempUpdateFile)); memoryStream.Position = 0; this.Log().Trace("Writing file '{0}'".format_with(tempUpdateFile)); _fileSystem.write_file(tempUpdateFile, () => memoryStream); memoryStream.Close(); streamWriter.Close(); this.Log().Trace("Replacing file '{0}' with '{1}'.".format_with(xmlFilePath, tempUpdateFile)); _fileSystem.replace_file(tempUpdateFile, xmlFilePath, xmlFilePath + ".backup"); } } }, errorMessage: "Error serializing type {0}".format_with(typeof(XmlType)), throwError: true, isSilent: isSilent); }, MUTEX_TIMEOUT), waitDurationMilliseconds: 200, increaseRetryByMilliseconds: 200); }
public static GetChocolatey GetChocolatey() { return(GlobalMutex.enter(() => set_up(), 10)); }