private void Application_Startup(object sender, StartupEventArgs e) { instanceLock = new SingleGlobalInstance(TimeSpan.FromSeconds(1), "9b8e7757-9368-4034-9ecd-7892e7f730f7"); if (!instanceLock.GetMutex()) { MessageBox.Show("System Info is already running"); Shutdown(); } // Create a default configuration var configuration = new ConfigurationBuilder() .SetFileLoadExceptionHandler(x => x.Ignore = true) .AddJsonFile(SettingsHelper.GetSettingsFilePath(), true, true) .Build(); var serviceProvider = new ServiceCollection() .AddAssemblyResolver() .AddRegisteredTypes() .AddOptions() .AddSingleton <IConfiguration>(configuration) .Configure <WindowSettings>(configuration.GetSection(typeof(WindowSettings).Name)) .AddNonGenericLoggerError() .AddFromAssemblies(new[] { "SystemInfo.Core" }) .AddWindows(Array.Empty <string>()) .BuildServiceProvider(); notifyIcon = (TaskbarIcon)FindResource("NotifyIcon"); notifyIcon.DataContext = serviceProvider.GetRequiredService <INotifyIconViewModel>(); window = serviceProvider.GetView <MainWindow, IMainWindowViewModel>(); window.Show(); }
protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); AppDomain.CurrentDomain.UnhandledException += AppDomain_CurrentDomain_UnhandledException; mutex = new SingleGlobalInstance(); if (mutex.HasHandle && GetProcesses().Length <= 1) { Logger.Info("Launching UCR"); _hidGuardianClient = new HidGuardianClient(); _hidGuardianClient.WhitelistProcess(); InitializeUcr(); CheckForBlockedDll(); context.ParseCommandLineArguments(e.Args); var mw = new MainWindow(context); mw.Show(); } else { SendArgs(string.Join(";", e.Args)); Current.Shutdown(); } }
private static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(Program.CurrentDomain_UnhandledException); //ExceptionTracker.TestStackTrace(0, 10); // var ex = new NullReferenceException("Message"); //throw ex; if (!Program.CatchStuff) { using (Game1 game = new Game1()) { game.Run(); } } else { try { using (SingleGlobalInstance singleGlobalInstance = new SingleGlobalInstance(1000)) { using (Game1 game = new Game1()) { game.Run(); } } } catch (Exception exception) { Exception e = exception; MessageBox.Show(string.Concat("Whoops! Please post a screenshot of this to the StarDrive forums (", MainMenuScreen.Version, "):\n\n", e.ToString())); } } }
private static void ReadSettings() { using (SingleGlobalInstance.Acquire(Path.GetFileName(settingsFilePath))) { if (!File.Exists(settingsFilePath)) { return; } var lines = File.ReadAllLines(settingsFilePath); foreach (var line in lines) { ProcessLine(Virtualization, line, ref enableTreeViewVirtualization); //ProcessLine(ParentAllTargetsUnderProjectSetting, line, ref parentAllTargetsUnderProject); ProcessLine(MarkResultsInTreeSetting, line, ref markResultsInTree); ProcessLine(UseDarkThemeSetting, line, ref useDarkTheme); void ProcessLine(string setting, string text, ref bool variable) { if (!text.StartsWith(setting)) { return; } var value = text.Substring(setting.Length); if (bool.TryParse(value, out bool boolValue)) { variable = boolValue; } } } } }
public static void SaveCustomArguments(string projectFilePath, string newArguments) { using (SingleGlobalInstance.Acquire(Path.GetFileName(customArgumentsFilePath))) { if (!File.Exists(customArgumentsFilePath)) { if (newArguments == DefaultArguments) { return; } else { string directoryName = Path.GetDirectoryName(customArgumentsFilePath); Directory.CreateDirectory(directoryName); File.WriteAllLines(customArgumentsFilePath, new[] { projectFilePath + "=" + newArguments }); return; } } var list = File.ReadAllLines(customArgumentsFilePath).ToList(); if (FindArguments(list, projectFilePath, out string?arguments, out int index)) { list.RemoveAt(index); } list.Insert(0, projectFilePath + "=" + newArguments); if (list.Count >= MaximumProjectsInRecentArgumentsList) { list.RemoveAt(list.Count - 1); } File.WriteAllLines(customArgumentsFilePath, list); } }
IObservable <IDisposable> acquireUpdateLock() { if (updateLock != null) { return(Observable.Return(updateLock)); } return(Observable.Start(() => { var key = Utility.CalculateStreamSHA1(new MemoryStream(Encoding.UTF8.GetBytes(rootAppDirectory))); SingleGlobalInstance theLock; try { theLock = new SingleGlobalInstance(key, 2000); } catch (TimeoutException) { throw new TimeoutException("Couldn't acquire update lock, another instance may be running updates"); } var ret = Disposable.Create(() => { theLock.Dispose(); updateLock = null; }); updateLock = ret; return ret; })); }
private static void CleanupTempFiles() { using (SingleGlobalInstance.Acquire("StructuredLogViewerTempFileCleanup")) { if (cleanedUpTempFiles) { return; } cleanedUpTempFiles = true; var folder = tempFolder; try { foreach (var file in Directory.GetFiles(folder)) { try { var fileInfo = new FileInfo(file); if (fileInfo.LastWriteTimeUtc < DateTime.UtcNow - TimeSpan.FromDays(30)) { fileInfo.Delete(); } } catch { } } } catch { } } }
public static async Task MainAsync(SingleGlobalInstance instance) { using (instance) { var builder = new ContainerBuilder(); builder.RegisterAssemblyModules(AssemblyCollector.Instance.GetAssemblies()); try { using (var container = builder.Build()) { using (var scope = container.BeginLifetimeScope()) { var mediator = scope.Resolve <IMediator>(); // Any configuration checks, initializations should be handled by this event await mediator.Publish(new AppStartingEvent()); await mediator.Publish(new AppStartedEvent()); HostFactory.Run(x => //1 { x.UseAutofacContainer(scope); x.Service <TownCrier>(s => { //s.ConstructUsingAutofacContainer(); s.ConstructUsing(name => new TownCrier()); s.WhenStarted(async tc => { await mediator.Publish(new StartCorneyReq()); tc.Start(); }); s.WhenShutdown(tc => { tc.Stop(); }); s.WhenStopped(tc => { tc.Stop(); //scope?.Dispose(); //container?.Dispose(); }); }); x.RunAsLocalSystem(); x.SetDescription("Corney - Crontab file executor for Windows"); x.SetDisplayName("Corney"); x.SetServiceName("Corney"); }); } } } catch (Exception e) { _log.Error(e); _log.Error(e.Message); } } }
private static void SaveText(string storageFilePath, IEnumerable <string> lines) { using (SingleGlobalInstance.Acquire(Path.GetFileName(storageFilePath))) { string directoryName = Path.GetDirectoryName(storageFilePath); Directory.CreateDirectory(directoryName); File.WriteAllLines(storageFilePath, lines); } }
public IDisposable AcquireUpdateLock() { var key = Utility.CalculateStreamSHA1(new MemoryStream(Encoding.UTF8.GetBytes(rootAppDirectory))); var ret = new SingleGlobalInstance(key, 500); hasUpdateLock = true; return(Disposable.Create(() => { ret.Dispose(); hasUpdateLock = false; })); }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); DevExpress.Skins.SkinManager.EnableFormSkins(); DevExpress.UserSkins.BonusSkins.Register(); UserLookAndFeel.Default.SetSkinStyle("DevExpress Style"); SingleGlobalInstance.Run(5000, new Form1()); //Application.Run(new Form1()); }
private static void SaveSettings() { var sb = new StringBuilder(); sb.AppendLine(Virtualization + enableTreeViewVirtualization.ToString()); sb.AppendLine(ParentAllTargetsUnderProjectSetting + parentAllTargetsUnderProject.ToString()); sb.AppendLine(MarkResultsInTreeSetting + markResultsInTree.ToString()); using (SingleGlobalInstance.Acquire(Path.GetFileName(settingsFilePath))) { File.WriteAllText(settingsFilePath, sb.ToString()); } }
private static IEnumerable <string> GetRecentItems(string storageFilePath) { using (SingleGlobalInstance.Acquire(Path.GetFileName(storageFilePath))) { if (!File.Exists(storageFilePath)) { return(Array.Empty <string>()); } var lines = File.ReadAllLines(storageFilePath); return(lines); } }
public void OnlyOneInstanceAllowed() { var gui = Guid.NewGuid().ToString(); using var instance = new SingleGlobalInstance(gui); var hasInstance = instance.GetMutex(); var taskNotCancelled = Task.Run(() => { using var instance = new SingleGlobalInstance(gui); var hasInstance = instance.GetMutex(); }).Wait(TimeSpan.FromSeconds(1)); Assert.IsTrue(hasInstance); Assert.IsFalse(taskNotCancelled); }
public static void Main() { using (var mutex = new SingleGlobalInstance(1000)) { if (mutex._hasHandle) { App app = new App(); app.InitializeComponent(); app.Run(); } else { MessageBox.Show("Instance already running", "CardOrganizer"); } } }
public void DisposeReleasesMutex() { var gui = Guid.NewGuid().ToString(); var instance = new SingleGlobalInstance(gui); var hasInstance = instance.GetMutex(); Assert.IsTrue(hasInstance); var task = Task.Run(() => { using var instance = new SingleGlobalInstance(gui); var hasInstance = instance.GetMutex(); Assert.IsTrue(hasInstance); }); instance.Dispose(); var taskNotCancelled = task.Wait(TimeSpan.FromSeconds(5)); Assert.IsTrue(taskNotCancelled); }
private static void ReadSettings() { using (SingleGlobalInstance.Acquire(Path.GetFileName(settingsFilePath))) { if (!File.Exists(settingsFilePath)) { return; } var lines = File.ReadAllLines(settingsFilePath); foreach (var line in lines) { if (line.StartsWith(Virtualization)) { var value = line.Substring(Virtualization.Length); if (bool.TryParse(value, out bool boolValue)) { enableTreeViewVirtualization = boolValue; } } else if (line.StartsWith(ParentAllTargetsUnderProjectSetting)) { var value = line.Substring(ParentAllTargetsUnderProjectSetting.Length); if (bool.TryParse(value, out bool boolValue)) { parentAllTargetsUnderProject = boolValue; } } else if (line.StartsWith(MarkResultsInTreeSetting)) { var value = line.Substring(MarkResultsInTreeSetting.Length); if (bool.TryParse(value, out bool boolValue)) { markResultsInTree = boolValue; } } } } }
public static string WriteContentToTempFileAndGetPath(string content, string fileExtension) { var folder = tempFolder; var filePath = Path.Combine(folder, Utilities.GetMD5Hash(content, 16) + fileExtension); using (SingleGlobalInstance.Acquire(Path.GetFileName(filePath))) { if (File.Exists(filePath)) { return(filePath); } Directory.CreateDirectory(folder); File.WriteAllText(filePath, content); } if (!cleanedUpTempFiles) { System.Threading.Tasks.Task.Run(() => CleanupTempFiles()); } return(filePath); }
public static string GetCustomArguments(string filePath) { string[] lines; using (SingleGlobalInstance.Acquire(Path.GetFileName(customArgumentsFilePath))) { if (!File.Exists(customArgumentsFilePath)) { return(DefaultArguments); } lines = File.ReadAllLines(customArgumentsFilePath); } if (FindArguments(lines, filePath, out string?arguments, out int index)) { return(arguments); } var mostRecentArguments = TextUtilities.ParseNameValue(lines[0]); return(mostRecentArguments.Value); }
public void GetMutexWhenThreadExits() { var gui = Guid.NewGuid().ToString(); void Action() { var instance = new SingleGlobalInstance(gui); var hasInstance = instance.GetMutex(); Assert.IsTrue(hasInstance); Task.Delay(200).Wait(); } var thread1 = new Thread(new ThreadStart(Action)); var thread2 = new Thread(new ThreadStart(Action)); thread1.Start(); thread2.Start(); var taskNotCancelled1 = thread1.Join(TimeSpan.FromSeconds(1)); var taskNotCancelled2 = thread2.Join(TimeSpan.FromSeconds(1)); Assert.IsTrue(taskNotCancelled1); Assert.IsTrue(taskNotCancelled2); }
public void TestMethod1() { var guid = SingleGlobalInstance.GetApplicationGui(); Assert.AreEqual("2B0D126E-027B-43CE-8A27-DAFC51C03BD5", guid); }
public void ThrowsArgumentExceptionWhenNoGuiIsSupplied() => _ = Assert.ThrowsException <ArgumentException>(() => SingleGlobalInstance.GetApplicationGui());
IObservable<IDisposable> acquireUpdateLock() { if (updateLock != null) return Observable.Return(updateLock); return Observable.Start(() => { var key = Utility.CalculateStreamSHA1(new MemoryStream(Encoding.UTF8.GetBytes(rootAppDirectory))); SingleGlobalInstance theLock; try { theLock = new SingleGlobalInstance(key, 2000); } catch (TimeoutException) { throw new TimeoutException("Couldn't acquire update lock, another instance may be running updates"); } var ret = Disposable.Create(() => { theLock.Dispose(); updateLock = null; }); updateLock = ret; return ret; }); }