Example #1
0
        /// <summary>
        /// Delete the given profiles.
        ///
        /// Result Failure contains the profile that couldn't be deleted because they don't exists.
        /// </summary>
        /// <param name="profiles"></param>
        /// <returns></returns>
        public Result <ProfileSetting[], VoidSuccess> DeleteProfiles(IEnumerable <ProfileSetting> profiles)
        {
            var errors = new List <ProfileSetting>();

            foreach (var profile in profiles)
            {
                if (!AppConfigs.Configuration.ProfileSettings.Contains(profile))
                {
                    errors.Add(profile);
                    continue;
                }


                if (profile.ApplicationPath != null)
                {
                    _profileByApplication.Remove(profile.ApplicationPath.ToLower());
                }

                if (profile.HotKey != null)
                {
                    WindowsAPIAdapter.UnRegisterHotKey(profile.HotKey);
                    _profileByHotkey.Remove(profile.HotKey);
                }

                AppConfigs.Configuration.ProfileSettings.Remove(profile);
            }

            AppConfigs.Configuration.Save();
            if (errors.Count > 0)
            {
                return(errors.ToArray());
            }

            return(Result.Success());
        }
Example #2
0
        public bool SetHotkeyCombination(HotKeys hotkeys, AudioDeviceType deviceType)
        {
            using (AppLogger.Log.InfoCall())
            {
                HotKeys confHotKeys = null;
                switch (deviceType)
                {
                case AudioDeviceType.Playback:
                    confHotKeys = AppConfigs.Configuration.PlaybackHotKeys;
                    break;

                case AudioDeviceType.Recording:
                    confHotKeys = AppConfigs.Configuration.RecordingHotKeys;
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(deviceType), deviceType, null);
                }
                using (AppLogger.Log.InfoCall())
                {
                    AppLogger.Log.Info("Unregister previous hotkeys", confHotKeys);
                    WindowsAPIAdapter.UnRegisterHotKey(confHotKeys);
                    AppLogger.Log.Info("Unregistered previous hotkeys", confHotKeys);

                    if (hotkeys.Enabled && !WindowsAPIAdapter.RegisterHotKey(hotkeys))
                    {
                        AppLogger.Log.Warn("Can't register new hotkeys", hotkeys);
                        ErrorTriggered?.Invoke(this,
                                               new ExceptionEvent(new Exception("Impossible to register HotKey: " + hotkeys)));
                        return(false);
                    }

                    AppLogger.Log.Info("New Hotkeys registered", hotkeys);
                }
                switch (deviceType)
                {
                case AudioDeviceType.Playback:
                    AppConfigs.Configuration.PlaybackHotKeys = hotkeys;
                    break;

                case AudioDeviceType.Recording:
                    AppConfigs.Configuration.RecordingHotKeys = hotkeys;
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(deviceType), deviceType, null);
                }
                AppConfigs.Configuration.Save();
                return(true);
            }
        }
Example #3
0
        /// <summary>
        /// Initialize the profile manager. Return the list of Profile that it couldn't register hotkeys for.
        /// </summary>
        /// <returns></returns>
        public Result <ProfileSetting[], VoidSuccess> Init()
        {
            RegisterEvents();

            var errors = AppConfigs.Configuration.ProfileSettings
                         .Where(setting => setting.HotKey != null)
                         .Where(profileSetting => !WindowsAPIAdapter.RegisterHotKey(profileSetting.HotKey))
                         .ToArray();

            if (errors.Length > 0)
            {
                return(errors);
            }

            return(Result.Success());
        }
Example #4
0
        private Result <string, VoidSuccess> ValidateAddProfile(ProfileSetting profile)
        {
            if (string.IsNullOrEmpty(profile.ProfileName))
            {
                return(SettingsStrings.profile_error_no_name);
            }

            if (string.IsNullOrEmpty(profile.ApplicationPath) && profile.HotKey == null)
            {
                return(SettingsStrings.profile_error_needHKOrPath);
            }

            if (profile.Recording == null && profile.Playback == null)
            {
                return(SettingsStrings.profile_error_needPlaybackOrRecording);
            }

            if (profile.HotKey != null && _profileByHotkey.ContainsKey(profile.HotKey))
            {
                return(string.Format(SettingsStrings.profile_error_hotkey, profile.HotKey));
            }

            if (!string.IsNullOrEmpty(profile.ApplicationPath) && _profileByApplication.ContainsKey(profile.ApplicationPath.ToLower()))
            {
                return(string.Format(SettingsStrings.profile_error_application, profile.ApplicationPath));
            }

            if (AppConfigs.Configuration.ProfileSettings.Contains(profile))
            {
                return(string.Format(SettingsStrings.profile_error_name, profile.ProfileName));
            }

            if (profile.HotKey != null && !WindowsAPIAdapter.RegisterHotKey(profile.HotKey))
            {
                return(string.Format(SettingsStrings.profile_error_hotkey, profile.HotKey));
            }

            return(Result.Success());
        }
Example #5
0
        private static void Main()
        {
            bool createdNew;

            InitializeLogger();
            Log.Information("Application Starts");
            var audioDeviceLister = new AudioDeviceLister(DeviceState.Active);

            using (var recordingDevices = audioDeviceLister.GetRecordingDevices())
            {
                Log.Information("Devices Recording {device}", recordingDevices);
            }

            using (var playbackDevices = audioDeviceLister.GetPlaybackDevices())
            {
                Log.Information("Devices Playback {device}", playbackDevices);
            }
#if !DEBUG
            AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
            {
                HandleException((Exception)args.ExceptionObject);
            };

            Log.Information("Set Exception Handler");
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
            WindowsAPIAdapter.Start(Application_ThreadException);
#else
            WindowsAPIAdapter.Start();
#endif
            Thread.CurrentThread.CurrentUICulture = LanguageParser.ParseLanguage(AppModel.Instance.Language);

            using (new Mutex(true, Application.ProductName, out createdNew))
            {
                if (!createdNew)
                {
                    Log.Warning("Application already started");
                    using (var client = new IPCClient(AppConfigs.IPCConfiguration.ClientUrl()))
                    {
                        try
                        {
                            var service = client.GetService();
                            service.StopApplication();
                            RestartApp();
                            return;
                        }
                        catch (RemotingException e)
                        {
                            Log.Error(e, "Unable to stop another running application");
                            Application.Exit();
                            return;
                        }
                    }
                }

                AppModel.Instance.ActiveAudioDeviceLister = new AudioDeviceLister(DeviceState.Active);

                // Windows Vista or newer.
                if (Environment.OSVersion.Version.Major >= 6)
                {
                    SetProcessDPIAware();
                }

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                // Manage the Closing events send by Windows
                // Since this app don't use a Form as "main window" the app doesn't close
                // when it should without this.
                WindowsAPIAdapter.RestartManagerTriggered += (sender, @event) =>
                {
                    Log.Debug("Restart Event received: {Event}", @event);
                    switch (@event.Type)
                    {
                    case WindowsAPIAdapter.RestartManagerEventType.Query:
                        @event.Result = new IntPtr(1);

                        break;

                    case WindowsAPIAdapter.RestartManagerEventType.EndSession:
                    case WindowsAPIAdapter.RestartManagerEventType.ForceClose:
                        Log.Debug("Close Application");
                        Application.Exit();
                        break;
                    }
                };

                Log.Information("Set Tray Icon with Main");
#if !DEBUG
                try
                {
#endif
                MMNotificationClient.Instance.Register();
                using (var ipcServer = new IPCServer(AppConfigs.IPCConfiguration.ServerUrl()))
                    using (var icon = new TrayIcon())
                    {
                        var available = false;
                        while (!available)
                        {
                            try
                            {
                                ipcServer.InitServer();
                                available = true;
                            }
                            catch (RemotingException)
                            {
                                Thread.Sleep(250);
                            }
                        }
                        AppModel.Instance.TrayIcon = icon;
                        AppModel.Instance.InitializeMain();
                        AppModel.Instance.NewVersionReleased += (sender, @event) =>
                        {
                            if (@event.UpdateMode == UpdateMode.Silent)
                            {
                                new AutoUpdater("/VERYSILENT /NOCANCEL /NORESTART", ApplicationPath.Default).Update(@event.Release, true);
                            }
                        };
                        if (AppConfigs.Configuration.FirstRun)
                        {
                            icon.ShowSettings();
                            AppConfigs.Configuration.FirstRun = false;
                            Log.Information("First run");
                        }
                        Application.Run();
                    }
#if !DEBUG
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
#endif
            }
            MMNotificationClient.Instance.UnRegister();
            WindowsAPIAdapter.Stop();
            Log.CloseAndFlush();
        }
Example #6
0
        private static void Main()
        {
            var sentryOptions = new SentryOptions
            {
                Dsn         = "https://[email protected]/5755327",
                Environment = AssemblyUtils.GetReleaseState().ToString()
            };
            var contribOptions = new ContribSentryOptions()
            {
                GlobalSessionMode = true,
                DistinctId        = AppConfigs.Configuration.UniqueInstallationId.ToString()
            };

            sentryOptions.AddIntegration(new ContribSentrySdkIntegration(contribOptions));
            using var _ = SentrySdk.Init(sentryOptions);

            SentrySdk.ConfigureScope(scope => scope.User = new User
            {
                Id       = AppConfigs.Configuration.UniqueInstallationId.ToString(),
                Username = Environment.UserName
            });
            ContribSentrySdk.StartSession();
            InitializeLogger();
            Log.Information("Application Starts");
#if !DEBUG
            AppDomain.CurrentDomain.UnhandledException += (sender, args) => { HandleException((Exception)args.ExceptionObject); };

            Log.Information("Set Exception Handler");
            Application.ThreadException += Application_ThreadException;
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            WindowsAPIAdapter.Start(Application_ThreadException);
#else
            WindowsAPIAdapter.Start();
#endif
            Thread.CurrentThread.CurrentUICulture = new LanguageFactory().Get(AppModel.Instance.Language).CultureInfo;
            Thread.CurrentThread.Name             = "Main Thread";
            var userMutexName = Application.ProductName + Environment.UserName;

            using var mainMutex = new Mutex(true, Application.ProductName);
            using var userMutex = new Mutex(true, userMutexName, out var userMutexHasOwnership);
            if (!userMutexHasOwnership)
            {
                Log.Warning("SoundSwitch is already running for this user {@Mutex}", userMutexName);
                WindowsAPIAdapter.Stop();
                Log.CloseAndFlush();
                return;
            }


            SetProcessDPIAware();

            Application.EnableVisualStyles();
#if NETCORE
            Application.SetHighDpiMode(HighDpiMode.PerMonitorV2);
#endif
            Application.SetCompatibleTextRenderingDefault(false);
            // Manage the Closing events send by Windows
            // Since this app don't use a Form as "main window" the app doesn't close
            // when it should without this.
            WindowsAPIAdapter.RestartManagerTriggered += (sender, @event) =>
            {
                Log.Debug("Restart Event received: {Event}", @event);
                switch (@event.Type)
                {
                case WindowsAPIAdapter.RestartManagerEventType.Query:
                    @event.Result = new IntPtr(1);

                    break;

                case WindowsAPIAdapter.RestartManagerEventType.EndSession:
                case WindowsAPIAdapter.RestartManagerEventType.ForceClose:
                    Log.Debug("Close Application");
                    Environment.Exit(0);
                    break;
                }
            };

            Log.Information("Set Tray Icon with Main");
#if !DEBUG
            try
            {
#endif
            MMNotificationClient.Instance.Register();


            using var ctx = new WindowsFormsSynchronizationContext();

            SynchronizationContext.SetSynchronizationContext(ctx);
            try
            {
                Application.Run(new SoundSwitchApplicationContext());
            }
            finally
            {
                SynchronizationContext.SetSynchronizationContext(null);
            }


#if !DEBUG
        }

        catch (Exception ex)
        {
            HandleException(ex);
        }
#endif
            AppModel.Instance.Dispose();
            WindowsAPIAdapter.Stop();
            MMNotificationClient.Instance?.Dispose();
            ContribSentrySdk.EndSession();
            Log.CloseAndFlush();
        }
Example #7
0
        private static void Main()
        {
            bool createdNew;

            AppLogger.Log.Info("Application Starts");
#if !DEBUG
            AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
            {
                HandleException((Exception)args.ExceptionObject);
            };

            AppLogger.Log.Info("Set Exception Handler");
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
            WindowsAPIAdapter.Start(Application_ThreadException);
#else
            WindowsAPIAdapter.Start();
#endif

            using (new Mutex(true, Application.ProductName, out createdNew))
            {
                if (!createdNew)
                {
                    AppLogger.Log.Warn("Application already started");
                    using (new AppLogger.LogRestartor())
                    {
                        using (var client = new IPCClient(AppConfigs.IPCConfiguration.ClientUrl()))
                        {
                            try
                            {
                                var service = client.GetService();
                                service.StopApplication();
                                RestartApp();
                                return;
                            }
                            catch (RemotingException e)
                            {
                                AppLogger.Log.Error("Can't stop the other app ", e);
                                Application.Exit();
                                return;
                            }
                        }
                    }
                }
                AppModel.Instance.ActiveAudioDeviceLister = new AudioDeviceLister(DeviceState.Active);
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                //Manage the Closing events send by Windows
                //Since this app don't use a Form as "main window" the app doesn't close
                //when it should without this.
                WindowsAPIAdapter.RestartManagerTriggered += (sender, @event) =>
                {
                    using (AppLogger.Log.DebugCall())
                    {
                        AppLogger.Log.Debug("Restart Event recieved", @event);
                        switch (@event.Type)
                        {
                        case WindowsAPIAdapter.RestartManagerEventType.Query:
                            @event.Result = new IntPtr(1);

                            break;

                        case WindowsAPIAdapter.RestartManagerEventType.EndSession:
                        case WindowsAPIAdapter.RestartManagerEventType.ForceClose:
                            AppLogger.Log.Debug("Close Application");
                            Application.Exit();
                            break;
                        }
                    }
                };

                AppLogger.Log.Info("Set Tray Icon with Main");
#if !DEBUG
                try
                {
#endif
                using (var ipcServer = new IPCServer(AppConfigs.IPCConfiguration.ServerUrl()))
                    using (var icon = new TrayIcon())
                    {
                        var available = false;
                        while (!available)
                        {
                            try
                            {
                                ipcServer.InitServer();
                                available = true;
                            }
                            catch (RemotingException)
                            {
                                Thread.Sleep(250);
                            }
                        }
                        AppModel.Instance.TrayIcon = icon;
                        AppModel.Instance.InitializeMain();
                        AppModel.Instance.NewVersionReleased += (sender, @event) =>
                        {
                            if (@event.UpdateState != UpdateState.Steath)
                            {
                                return;
                            }
                            new AutoUpdater("/VERYSILENT /NOCANCEL /NORESTART", ApplicationPath.Default).Update(@event.Release, true);
                        };
                        if (AppConfigs.Configuration.FirstRun)
                        {
                            icon.ShowSettings();
                            AppConfigs.Configuration.FirstRun = false;
                            AppLogger.Log.Info("First run");
                        }
                        Application.Run();
                    }
#if !DEBUG
            }

            catch (Exception ex)
            {
                HandleException(ex);
            }
#endif
            }
            WindowsAPIAdapter.Stop();
        }
Example #8
0
        private static void Main()
        {
            bool createdNew;

            AppLogger.Log.Info("Application Starts");
            using (new Mutex(true, Application.ProductName, out createdNew))
            {
                if (!createdNew)
                {
                    AppLogger.Log.Warn("Application already started");
                    return;
                }
                AppModel.Instance.ActiveAudioDeviceLister = new AudioDeviceLister(DeviceState.Active);
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
#if !DEBUG
                Application.ThreadException += Application_ThreadException;
#endif
                WindowsAPIAdapter.Start();
                //Manage the Closing events send by Windows
                //Since this app don't use a Form as "main window" the app doesn't close
                //when it should without this.
                WindowsAPIAdapter.RestartManagerTriggered += (sender, @event) =>
                {
                    using (AppLogger.Log.DebugCall())
                    {
                        AppLogger.Log.Debug("Restart Event recieved", @event);
                        switch (@event.Type)
                        {
                        case WindowsAPIAdapter.RestartManagerEventType.Query:
                            @event.Result = new IntPtr(1);

                            break;

                        case WindowsAPIAdapter.RestartManagerEventType.EndSession:
                        case WindowsAPIAdapter.RestartManagerEventType.ForceClose:
                            AppLogger.Log.Debug("Close Application");
                            Application.Exit();
                            break;
                        }
                    }
                };
                AppLogger.Log.Info("Set Exception Handler");
#if !DEBUG
                WindowsAPIAdapter.AddThreadExceptionHandler(Application_ThreadException);
#endif
                AppLogger.Log.Info("Set Tray Icon with Main");
#if !DEBUG
                try
                {
#endif
                using (var icon = new TrayIcon())
                {
                    if (AppConfigs.Configuration.FirstRun)
                    {
                        icon.ShowSettings();
                        AppConfigs.Configuration.FirstRun = false;
                        AppLogger.Log.Info("First run");
                    }
                    Application.Run();
                    WindowsAPIAdapter.Stop();
                }
#if !DEBUG
            }

            catch (Exception ex)
            {
                HandleException(ex);
            }
#endif
            }
        }
Example #9
0
        private static void Main()
        {
            InitializeLogger();
            Log.Information("Application Starts");
#if !DEBUG
            AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
            {
                HandleException((Exception)args.ExceptionObject);
            };

            Log.Information("Set Exception Handler");
            Application.ThreadException += Application_ThreadException;
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            WindowsAPIAdapter.Start(Application_ThreadException);
#else
            WindowsAPIAdapter.Start();
#endif
            Thread.CurrentThread.CurrentUICulture = new LanguageFactory().Get(AppModel.Instance.Language).CultureInfo;
            Thread.CurrentThread.Name             = "Main Thread";
            var userMutexName = Application.ProductName + Environment.UserName;

            using var mainMutex = new Mutex(true, Application.ProductName);
            using var userMutex = new Mutex(true, userMutexName, out var userMutexHasOwnership);
            if (!userMutexHasOwnership)
            {
                Log.Warning("SoundSwitch is already running for this user {@Mutex}", userMutexName);
                WindowsAPIAdapter.Stop();
                Log.CloseAndFlush();
                return;
            }


            SetProcessDPIAware();

            Application.EnableVisualStyles();
#if NETCORE
            Application.SetHighDpiMode(HighDpiMode.PerMonitorV2);
#endif
            Application.SetCompatibleTextRenderingDefault(false);

            // Manage the Closing events send by Windows
            // Since this app don't use a Form as "main window" the app doesn't close
            // when it should without this.
            WindowsAPIAdapter.RestartManagerTriggered += (sender, @event) =>
            {
                Log.Debug("Restart Event received: {Event}", @event);
                switch (@event.Type)
                {
                case WindowsAPIAdapter.RestartManagerEventType.Query:
                    @event.Result = new IntPtr(1);

                    break;

                case WindowsAPIAdapter.RestartManagerEventType.EndSession:
                case WindowsAPIAdapter.RestartManagerEventType.ForceClose:
                    Log.Debug("Close Application");
                    Environment.Exit(0);
                    break;
                }
            };

            Log.Information("Set Tray Icon with Main");
#if !DEBUG
            try
            {
#endif
            MMNotificationClient.Instance.Register();


            using var ctx = new WindowsFormsSynchronizationContext();

            SynchronizationContext.SetSynchronizationContext(ctx);
            try
            {
                Application.Run(new SoundSwitchApplicationContext());
            }
            finally
            {
                SynchronizationContext.SetSynchronizationContext(null);
            }


#if !DEBUG
        }

        catch (Exception ex)
        {
            HandleException(ex);
        }
#endif
            AppModel.Instance.ActiveAudioDeviceLister.Dispose();
            AppModel.Instance.ActiveUnpluggedAudioLister.Dispose();
            AppModel.Instance.TrayIcon.Dispose();
            WindowsAPIAdapter.Stop();
            MMNotificationClient.Instance.Dispose();
            Log.CloseAndFlush();
        }