Exemple #1
0
        private void Stop_Click(object sender, RoutedEventArgs e)
        {
            var client  = IPCClient.GetInstance();
            var factory = new IPCMessageFactory();

            client.Send(factory.Create("stop"));
        }
Exemple #2
0
        public WorldServer RequestConnection(IPCClient client, WorldServerData world)
        {
            //check ip
            if (!IsIPAllowed(client.Address))
            {
                logger.Error("Server <Id : {0}> ({1}) Try to connect self on the authenfication server but its ip is not allowed (see WorldServerManager.AllowedServerIps)",
                             world.Id, client.Address);
                throw new Exception(string.Format("Ip {0} not allow by auth. server", client.Address));
            }

            WorldServer server;

            if (!m_realmlist.ContainsKey(world.Id))
            {
                server = CreateWorld(world);
            }
            else
            {
                server = m_realmlist[world.Id];
                UpdateWorld(server, world, false);
            }

            server.SetOnline(client);
            Database.Update(server);

            logger.Info("Registered World : \"{0}\" <Id : {1}> <{2}>", world.Name, world.Id, world.Address);

            OnServerAdded(server);
            return(server);
        }
        public static void Main(string[] args)
        {

            _CurrentProperty = ThreadProperties.FromCurrentThread();

            using (var mutex = new Mutex(false, "MusicCollection SingleApplication"))
            {
                // Wait a few seconds if contended, in case another instance
                // of the program is still in the process of shutting down.
                if (!mutex.WaitOne(TimeSpan.FromSeconds(3), false))
                {
                    Trace.WriteLine("Another instance of the MusicCollection is running!");

                    if (ApplicationDeployment.IsNetworkDeployed)
                    {
                        string activationData = GetInputFilePath();
                        if (activationData != null)
                        {
                            try
                            {
                                IMusicFileImporter imf = new IPCClient<IMusicFileImporter>().GetService();
                                imf.ImportCompactedFileAsync(activationData).Wait();
                            }
                            catch { }
                        }
                    }

                    return;
                }

                Execute(args);
            }
        }
Exemple #4
0
        private void UserControl_Unloaded(object sender, RoutedEventArgs e)
        {
            var client = IPCClient.GetInstance();

            client.Disconnected    -= IPCClient_Disconnected;
            client.MessageReceived -= IPCClient_MessageReceived;

            client.Close();
        }
Exemple #5
0
        private void UserControl_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            var factory = new IPCMessageFactory();
            var message = factory.Create("restoreWindow");

            var client = IPCClient.GetInstance();

            client.Send(message);
        }
        public void Test_OK_IsOK()
        {
            MySame ms = new MySame();
            _Server = new IPCServer<ITheSame>("Test",ms, "Test");

            IPCClient<ITheSame> target = new IPCClient<ITheSame>("Test", "Test");
            ITheSame res = target.GetService();

            res.Should().NotBeNull();
            res.Get(9).Should().Be(9);
            res.Get(10).Should().Be(10);
        }
 public ServersController(
     MonitorDBContext context,
     IMapper mapper,
     IAuthorizationService authorizationService,
     UserManager <MonitorUser> userManager,
     IPCClient ipcClient
     )
 {
     _context = context;
     _mapper  = mapper;
     _authorizationService = authorizationService;
     _userManager          = userManager;
     _ipcClient            = ipcClient;
 }
Exemple #8
0
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            var client = IPCClient.GetInstance();

            client.Disconnected    += IPCClient_Disconnected;
            client.MessageReceived += IPCClient_MessageReceived;

            client.Init();

            // update information
            var factory = new IPCMessageFactory();

            client.Send(factory.Create("update"));
        }
        public void Test_NotFound_WrongAdress()
        {
            MySame ms = new MySame();
            _Server = new IPCServer<ITheSame>("Test", ms, "Test");

            IPCClient<ITheSame> target = new IPCClient<ITheSame>("Test2", "Test");
            ITheSame res = target.GetService();

            res.Should().NotBeNull();

            int resget = 0;
            Action ac = () => resget =  res.Get(0);
            ac.ShouldThrow<EndpointNotFoundException>();
           
        }
Exemple #10
0
        private async void OnRelinquishRelaxedPolicyRequested()
        {
            using (var ipcClient = new IPCClient())
            {
                ipcClient.ConnectedToServer = () =>
                {
                    ipcClient.RelinquishRelaxedPolicy();
                };

                ipcClient.RelaxedPolicyInfoReceived += delegate(RelaxedPolicyMessage msg)
                {
                    ShowRelaxedPolicyMessage(msg, false);
                };

                ipcClient.WaitForConnection();
                await Task.Delay(3000);
            }
        }
Exemple #11
0
        private void Position_ValueChanged(object sender, RoutedPropertyChangedEventArgs <double> e)
        {
            if (doNotTriggerEvent)
            {
                return;
            }

            var factory = new IPCMessageFactory();
            var message = factory.Create("setPosition", out XmlNode messageNode);

            var positionNode = message.CreateElement("position");

            positionNode.InnerText = ((int)e.NewValue).ToString();
            messageNode.AppendChild(positionNode);

            var client = IPCClient.GetInstance();

            client.Send(message);
        }
Exemple #12
0
        public async void OnRelaxedPolicyRequested(bool fromTray)
        {
            using (var ipcClient = new IPCClient())
            {
                ipcClient.ConnectedToServer = () =>
                {
                    //ipcClient.RequestRelaxedPolicy();
                    throw new NotImplementedException("When we use this library again, make sure to port OnRelaxedPolicyRequested() behavior to CloudVeilGUI");
                };

                ipcClient.RelaxedPolicyInfoReceived += delegate(RelaxedPolicyMessage msg)
                {
                    ShowRelaxedPolicyMessage(msg, fromTray);
                };

                ipcClient.WaitForConnection();
                await Task.Delay(3000);
            }
        }
        public async Task Authenticate()
        {
            ErrorMessage = string.Empty;

            var unencrypedPwordBytes = this.m_userPassword.SecureStringBytes();

            try
            {
                // Clear error message before running the authentication again. Makes it clearer to the user what's going on.
                m_loginViewModel.ErrorMessage = "";

                await Task.Run(() =>
                {
                    using (var ipcClient = new IPCClient())
                    {
                        ipcClient.ConnectedToServer = () =>
                        {
                            ipcClient.AttemptAuthentication(m_userName, m_userPassword);
                        };

                        ipcClient.AuthenticationResultReceived = (msg) =>
                        {
                            if (msg.AuthenticationResult.AuthenticationMessage != null)
                            {
                                m_loginViewModel.ErrorMessage = msg.AuthenticationResult.AuthenticationMessage;
                            }
                        };

                        ipcClient.WaitForConnection();
                        Task.Delay(3000).Wait();
                    }
                });
            }
            finally
            {
                // Always purge password from memory ASAP.
                if (unencrypedPwordBytes != null && unencrypedPwordBytes.Length > 0)
                {
                    Array.Clear(unencrypedPwordBytes, 0, unencrypedPwordBytes.Length);
                }
            }
        }
Exemple #14
0
        public async Task <bool> RequestAppDeactivation()
        {
            try
            {
                using (var ipcClient = new IPCClient())
                {
                    ipcClient.ConnectedToServer = () =>
                    {
                        ipcClient.RequestDeactivation();
                    };

                    ipcClient.WaitForConnection();
                    await Task.Delay(3000);
                }
            }
            catch (Exception e)
            {
                LoggerUtil.RecursivelyLogException(m_logger, e);
            }

            return(false);
        }
Exemple #15
0
        public async Task Authenticate()
        {
            ErrorMessage = "";

            await Task.Run(() =>
            {
                using (var ipcClient = new IPCClient())
                {
                    ipcClient.ConnectedToServer = () =>
                    {
                        // TODO: Rework either password box or login message to not require unsafe code in order to send authentication.
                        SecureString passwordStr = null;
                        unsafe
                        {
                            fixed(char *pass = password)
                            {
                                passwordStr = new SecureString(pass, password.Length);
                            }
                        }

                        ipcClient.AttemptAuthentication(username, passwordStr);
                    };

                    ipcClient.AuthenticationResultReceived = (msg) =>
                    {
                        if (msg.AuthenticationResult.AuthenticationMessage != null)
                        {
                            ErrorMessage = msg.AuthenticationResult.AuthenticationMessage;
                        }
                    };

                    ipcClient.WaitForConnection();
                    Task.Delay(3000).Wait();
                }
            });
        }
Exemple #16
0
        public WorldServer RequestConnection(IPCClient client, WorldServerData world)
        {
            if (!this.IsIPAllowed(client.Address))
            {
                WorldServerManager.logger.Error <int, IPAddress>("Server <Id : {0}> ({1}) Try to connect self on the authenfication server but its ip is not allowed (see WorldServerManager.AllowedServerIps)", world.Id, client.Address);
                throw new Exception(string.Format("Ip {0} not allow by auth. server", client.Address));
            }
            WorldServer worldServer;

            if (!this.m_realmlist.ContainsKey(world.Id))
            {
                worldServer = this.CreateWorld(world);
            }
            else
            {
                worldServer = this.m_realmlist[world.Id];
                this.UpdateWorld(worldServer, world, false);
            }
            worldServer.SetOnline(client);
            base.Database.Update(worldServer);
            WorldServerManager.logger.Info <string, int, string>("Registered World : \"{0}\" <Id : {1}> <{2}>", world.Name, world.Id, world.Address);
            this.OnServerAdded(worldServer);
            return(worldServer);
        }
Exemple #17
0
        private static void DoPreamble()
        {
            // Make sure the temp directory exists
            if (!TempDirectoryCreator.CheckTempExists())
            {
                MessageBoxes.Error(@"Qiqqa needs the directory {0} to exist for it to function properly.  Please create it or set the TEMP environment variable and restart Qiqqa.", TempFile.TempDirectory);
            }

            // Make sure that windir is set (goddamned font sybustem bug: http://stackoverflow.com/questions/10094197/wpf-window-throws-typeinitializationexception-at-start-up)
            {
                if (String.IsNullOrEmpty(Environment.GetEnvironmentVariable("windir")))
                {
                    Logging.Warn("Environment variable windir is empty so setting it to {0}", Environment.GetEnvironmentVariable("SystemRoot"));
                    Environment.SetEnvironmentVariable("windir", Environment.GetEnvironmentVariable("SystemRoot"));
                }
            }

            Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;

            string on_your_conscience =
                "Qiqqa is Copyright © Quantisle 2010-2016.  All rights reserved." +
                "If you are reading this in a disassembler, you know you are doing evil and will probably always have to look over your shoulder..."
            ;

            on_your_conscience = "Main";

            Thread.CurrentThread.Name = on_your_conscience;

            if (RegistrySettings.Instance.IsSet(RegistrySettings.DebugConsole))
            {
                Console.Instance.Init();
                Logging.Info("Console initialised");
            }

            // Support windows-level error reporting - helps suppressing the errors in pdfdraw.exe and QiqqaOCR.exe
            // https://msdn.microsoft.com/en-us/library/windows/desktop/ms680621%28v=vs.85%29.aspx
            if (true)
            {
                try
                {
                    SetErrorMode(0x0001 | 0x0002 | 0x0004 | 0x8000);
                }
                catch (Exception ex)
                {
                    Logging.Error(ex, "Error trying to suppress global process failure.");
                }
            }



            if (true)
            {
                AppDomain.CurrentDomain.AssemblyLoad += delegate(object sender, AssemblyLoadEventArgs args)
                {
                    Logging.Info("Loaded assembly: {0}", args.LoadedAssembly.FullName);
                };
            }

            try
            {
                FirstInstallWebLauncher.Check();
            }
            catch (Exception ex)
            {
                Logging.Error(ex, "Unknown exception during FirstInstallWebLauncher.Check().");
            }

            try
            {
                FileAssociationRegistration.DoRegistration();
            }
            catch (Exception ex)
            {
                Logging.Error(ex, "Unknown exception during FileAssociationRegistration.DoRegistration().");
            }

            //// Start tracing WPF events
            //WPFTrace wpf_trace = new WPFTrace();
            //PresentationTraceSources.Refresh();
            //PresentationTraceSources.DataBindingSource.Listeners.Add(wpf_trace);
            //PresentationTraceSources.DataBindingSource.Switch.Level = SourceLevels.Error;
            //System.Diagnostics.Trace.AutoFlush = true;

            // If we have a command line parameter and another instance is running, send it to them and exit
            if (true)
            {
                string[] command_line_args = Environment.GetCommandLineArgs();
                if (1 < command_line_args.Length && !ProcessSingleton.IsProcessUnique(false))
                {
                    IPCClient.SendMessage(command_line_args[1]);
                    Environment.Exit(-2);
                }
            }

            // Check that we are the only instance running
            if (true)
            {
                try
                {
                    if (!RegistrySettings.Instance.IsSet(RegistrySettings.AllowMultipleQiqqaInstances) && !ProcessSingleton.IsProcessUnique(true))
                    {
                        MessageBoxes.Info("There seems to be an instance of Qiqqa already running so Qiqqa will not start again.\n\nSometimes it takes a few moments for Qiqqa to exit as it finishes up a final OCR or download.  If this problem persists, you can kill the Qiqqa.exe process in Task Manager.");
                        Logging.Info("There is another instance of Qiqqa running, so exiting.");
                        Environment.Exit(-1);
                    }
                }
                catch (Exception ex)
                {
                    Logging.Error(ex, "Unknown exception while checking for single app instance.  Continuing as normal so there could be several Qiqqas running.");
                }
            }

            ComputerStatistics.LogCommonStatistics();
        }
Exemple #18
0
        static void Main(string[] args)
        {
            Console.WriteLine("This program was designed to be a diagnostics collector for CloudVeil for Windows.");
            Console.WriteLine("Use this program when you want to collect data on sites that aren't behaving properly while the filter is running.");
            Console.WriteLine("Here are the common commands:");
            Console.WriteLine("\tstart-diag [filename]: Use this to start collecting diagnostics information from CloudVeil for Windows");
            Console.WriteLine("\tstop-diag: Stops the diagnostic data collection and saves it to the file specified by start-diag");
            Console.WriteLine("\tquit: Quits the program.");
            Console.WriteLine("Use 'help' to get a comprehensive list of commands.");

            bool quit = false;

            AppDomain.CurrentDomain.ProcessExit += OnProcessExit;

            //System.AppDomain.CurrentDomain.
            IPCClient.InitDefault();
            ipcClient = IPCClient.Default;

            Console.WriteLine("Waiting for connection...");
            ipcClient.WaitForConnection();
            Console.WriteLine("Connected...");

            while (!quit)
            {
                Console.Write("> ");
                string command = Console.ReadLine();

                string[] commandParts = command.Split(' ');

                switch (commandParts[0])
                {
                case "start-diag":
                {
                    string filename = null;

                    if (commandParts.Length > 1)
                    {
                        filename = string.Join(" ", commandParts.Skip(1).ToArray());
                    }

                    StartDiagnostics(filename);
                    break;
                }

                case "load-diag":
                {
                    string filename = null;

                    if (commandParts.Length > 1)
                    {
                        filename = string.Join(" ", commandParts.Skip(1).ToArray());
                    }
                    else
                    {
                        Console.WriteLine("load-diag requires a filename.");
                        break;
                    }

                    LoadDiagnostics(filename);
                    break;
                }


                case "stop-diag":
                    StopDiagnostics();
                    break;

                case "compare-client-server-requests":
                {
                    string filename = null;

                    if (commandParts.Length > 1)
                    {
                        filename = string.Join(" ", commandParts.Skip(1).ToArray());
                    }

                    CompareClientServerRequestHeaders(filename);
                }
                break;

                case "help":
                    Help();
                    break;

                case "quit":
                    quit = true;
                    break;
                }
            }
        }
Exemple #19
0
 public Server(string ip, int port) : base(ip, port)
 {
     WorldService = new IPCClient(ip, "WorldServer");
 }
Exemple #20
0
        public static void Main(string[] args)
        {
            try
            {
                if (Process.GetCurrentProcess().SessionId <= 0)
                {
                    try
                    {
                        LoggerUtil.GetAppWideLogger().Error("GUI client started in session 0 isolation. Exiting. This should not happen.");
                        Environment.Exit((int)ExitCodes.ShutdownWithoutSafeguards);
                        return;
                    }
                    catch (Exception e)
                    {
                        // XXX TODO - We can't really log here unless we do a direct to-file write.
                        Environment.Exit((int)ExitCodes.ShutdownWithoutSafeguards);
                        return;
                    }
                }
            }
            catch
            {
                // Lets assume that if we can't even read our session ID, that we're in session 0.
                Environment.Exit((int)ExitCodes.ShutdownWithoutSafeguards);
                return;
            }

            try
            {
                string appVerStr = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
                System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
                appVerStr += "." + System.Reflection.AssemblyName.GetAssemblyName(assembly.Location).Version.ToString();

                bool createdNew;
                try
                {
                    InstanceMutex = new Mutex(true, string.Format(@"Local\{0}", GuidUtility.Create(GuidUtility.DnsNamespace, appVerStr).ToString("B")), out createdNew);
                }
                catch
                {
                    // We can get access denied if SYSTEM is running this.
                    createdNew = false;
                }

                if (!createdNew)
                {
                    try
                    {
                        var thisProcess = Process.GetCurrentProcess();
                        var processes   = Process.GetProcessesByName(thisProcess.ProcessName).Where(p => p.Id != thisProcess.Id);

                        foreach (Process runningProcess in processes)
                        {
                            foreach (var handle in WindowHelpers.EnumerateProcessWindowHandles(runningProcess.Id))
                            {
                                // Send window show.
                                WindowHelpers.SendMessage(handle, (uint)WindowMessages.SHOWWINDOW, 9, 0);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        LoggerUtil.RecursivelyLogException(LoggerUtil.GetAppWideLogger(), e);
                    }

                    // In case we have some out of sync state where the app is running at a higher
                    // privilege level than us, the app won't get our messages. So, let's attempt an
                    // IPC named pipe to deliver the message as well.
                    try
                    {
                        using (var ipcClient = new IPCClient())
                        {
                            ipcClient.RequestPrimaryClientShowUI();

                            // Wait plenty of time before dispose to allow delivery of the msg.
                            Task.Delay(500).Wait();
                        }
                    }
                    catch (Exception e)
                    {
                        // The only way we got here is if the server isn't running, in which case we
                        // can do nothing because its beyond our domain.
                        LoggerUtil.RecursivelyLogException(LoggerUtil.GetAppWideLogger(), e);
                    }

                    // Close this instance.
                    Environment.Exit(-1);
                    return;
                }
            }
            catch (Exception e)
            {
                // The only way we got here is if the server isn't running, in which case we can do
                // nothing because its beyond our domain.
                LoggerUtil.RecursivelyLogException(LoggerUtil.GetAppWideLogger(), e);
                return;
            }

            try
            {
                MainLogger = LoggerUtil.GetAppWideLogger();
            }
            catch { }

            try
            {
                var app = new CitadelApp();
                app.InitializeComponent();
                app.Run();

                // Always release mutex.
                InstanceMutex.ReleaseMutex();
            }
            catch (Exception e)
            {
                try
                {
                    MainLogger = LoggerUtil.GetAppWideLogger();
                    LoggerUtil.RecursivelyLogException(MainLogger, e);
                }
                catch (Exception be)
                {
                    // XXX TODO - We can't really log here unless we do a direct to-file write.
                }
            }

            // No matter what, always ensure that critical flags are removed from our process before exiting.
            CriticalKernelProcessUtility.SetMyProcessAsNonKernelCritical();
        }
        private static void DoPreamble()
        {
            // Make sure the temp directory exists
            if (!TempDirectoryCreator.CheckTempExists())
            {
                MessageBoxes.Error(@"Qiqqa needs the directory {0} to exist for it to function properly.  Please create it or set the TEMP environment variable and restart Qiqqa.", TempFile.TempDirectoryForQiqqa);
            }

            // Make sure that windir is set (goddamned font subsystem bug: http://stackoverflow.com/questions/10094197/wpf-window-throws-typeinitializationexception-at-start-up)
            {
                if (String.IsNullOrEmpty(Environment.GetEnvironmentVariable("windir")))
                {
                    Logging.Warn("Environment variable windir is empty so setting it to {0}", Environment.GetEnvironmentVariable("SystemRoot"));
                    Environment.SetEnvironmentVariable("windir", Environment.GetEnvironmentVariable("SystemRoot"));
                }
            }

            Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;

            Thread.CurrentThread.Name = "Main";

            if (RegistrySettings.Instance.IsSet(RegistrySettings.DebugConsole))
            {
                Console.Instance.Init();
                Logging.Info("Console initialised");
            }

            // Support windows-level error reporting - helps suppressing the errors in pdfdraw.exe and QiqqaOCR.exe
            // https://msdn.microsoft.com/en-us/library/windows/desktop/ms680621%28v=vs.85%29.aspx
            try
            {
                SetErrorMode(0x0001 | 0x0002 | 0x0004 | 0x8000);
            }
            catch (Exception ex)
            {
                Logging.Error(ex, "Error trying to suppress global process failure.");
            }

            // kick the number of threads in the threadpool down to a reasonable number
            SafeThreadPool.SetMaxActiveThreadCount();

            AppDomain.CurrentDomain.AssemblyLoad += delegate(object sender, AssemblyLoadEventArgs args)
            {
                Logging.Info("Loaded assembly: {0}", args.LoadedAssembly.FullName);
                Logging.TriggerInit();
            };

#if CEFSHARP
            #region CEFsharp setup

            // CEFsharp setup for AnyPC as per https://github.com/cefsharp/CefSharp/issues/1714:
            AppDomain.CurrentDomain.AssemblyResolve += CefResolver;

            InitCef();

            #endregion CEFsharp setup
#endif

            try
            {
                FirstInstallWebLauncher.Check();
            }
            catch (Exception ex)
            {
                Logging.Error(ex, "Unknown exception during FirstInstallWebLauncher.Check().");
            }

            try
            {
                FileAssociationRegistration.DoRegistration();
            }
            catch (Exception ex)
            {
                Logging.Error(ex, "Unknown exception during FileAssociationRegistration.DoRegistration().");
            }

            // Start tracing WPF events
#if DEBUG
            WPFTrace wpf_trace = new WPFTrace();
            PresentationTraceSources.Refresh();
            PresentationTraceSources.DataBindingSource.Listeners.Add(wpf_trace);
            PresentationTraceSources.DataBindingSource.Switch.Level = SourceLevels.Error;
            System.Diagnostics.Trace.AutoFlush = true;
#endif

            // If we have a command line parameter and another instance is running, send it to them and exit
            string[] command_line_args = Environment.GetCommandLineArgs();
            if (1 < command_line_args.Length && !ProcessSingleton.IsProcessUnique(false))
            {
                IPCClient.SendMessage(command_line_args[1]);
                Environment.Exit(-2);
            }

            // Check that we are the only instance running
            try
            {
                if (!RegistrySettings.Instance.IsSet(RegistrySettings.AllowMultipleQiqqaInstances) && !ProcessSingleton.IsProcessUnique(bring_other_process_to_front_if_it_exists: true))
                {
                    MessageBoxes.Info("There seems to be an instance of Qiqqa already running so Qiqqa will not start again.\n\nSometimes it takes a few moments for Qiqqa to exit as it finishes up a final OCR or download.  If this problem persists, you can kill the Qiqqa.exe process in Task Manager.");
                    Logging.Info("There is another instance of Qiqqa running, so exiting.");
                    Environment.Exit(-1);
                }
            }
            catch (Exception ex)
            {
                Logging.Error(ex, "Unknown exception while checking for single app instance.  Continuing as normal so there could be several Qiqqas running.");
            }

            ComputerStatistics.LogCommonStatistics();
        }
Exemple #22
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();
        }
 public void SetOnline(IPCClient client)
 {
     this.Status    = ServerStatusEnum.ONLINE;
     this.LastPing  = DateTime.Now;
     this.IPCClient = client;
 }
Exemple #24
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();
        }
Exemple #25
0
        // ReSharper disable once CyclomaticComplexity
        private static void SwitchProfile(IReadOnlyList <Profile> profiles, int profileIndex)
        {
            var rollbackProfile = Profile.GetCurrent(string.Empty);

            if (profileIndex < 0)
            {
                throw new Exception(Language.Selected_profile_is_invalid_or_not_found);
            }
            if (!profiles[profileIndex].IsPossible)
            {
                throw new Exception(Language.Selected_profile_is_not_possible);
            }
            if (
                IPCClient.QueryAll()
                .Any(
                    client =>
                    (client.Status == InstanceStatus.Busy) ||
                    (client.Status == InstanceStatus.OnHold)))
            {
                throw new Exception(
                          Language
                          .Another_instance_of_this_program_is_in_working_state_Please_close_other_instances_before_trying_to_switch_profile);
            }
            if (!string.IsNullOrWhiteSpace(CommandLineOptions.Default.ExecuteFilename))
            {
                if (!File.Exists(CommandLineOptions.Default.ExecuteFilename))
                {
                    throw new Exception(Language.Executable_file_not_found);
                }
                if (!GoProfile(profiles[profileIndex]))
                {
                    throw new Exception(Language.Can_not_change_active_profile);
                }
                var process = Process.Start(CommandLineOptions.Default.ExecuteFilename,
                                            CommandLineOptions.Default.ExecuteArguments);
                var processes = new Process[0];
                if (!string.IsNullOrWhiteSpace(CommandLineOptions.Default.ExecuteProcessName))
                {
                    var ticks = 0;
                    while (ticks < CommandLineOptions.Default.ExecuteProcessTimeout * 1000)
                    {
                        processes = Process.GetProcessesByName(CommandLineOptions.Default.ExecuteProcessName);
                        if (processes.Length > 0)
                        {
                            break;
                        }
                        Thread.Sleep(300);
                        ticks += 300;
                    }
                }
                if (processes.Length == 0)
                {
                    processes = new[] { process }
                }
                ;
                IPCService.GetInstance().HoldProcessId = processes.FirstOrDefault()?.Id ?? 0;
                IPCService.GetInstance().Status        = InstanceStatus.OnHold;
                NotifyIcon notify = null;
                try
                {
                    notify = new NotifyIcon
                    {
                        Icon = Properties.Resources.Icon,
                        Text = string.Format(
                            Language.Waiting_for_the_0_to_terminate,
                            processes[0].ProcessName),
                        Visible = true
                    };
                    Application.DoEvents();
                }
                catch
                {
                    // ignored
                }
                foreach (var p in processes)
                {
                    try
                    {
                        p.WaitForExit();
                    }
                    catch
                    {
                        // ignored
                    }
                }
                if (notify != null)
                {
                    notify.Visible = false;
                    notify.Dispose();
                    Application.DoEvents();
                }
                IPCService.GetInstance().Status = InstanceStatus.Busy;
                if (!rollbackProfile.IsActive)
                {
                    if (!GoProfile(rollbackProfile))
                    {
                        throw new Exception(Language.Can_not_change_active_profile);
                    }
                }
            }
            else if (CommandLineOptions.Default.ExecuteSteamApp > 0)
            {
                var steamGame = new SteamGame(CommandLineOptions.Default.ExecuteSteamApp);
                if (!SteamGame.SteamInstalled)
                {
                    throw new Exception(Language.Steam_is_not_installed);
                }
                if (!File.Exists(SteamGame.SteamAddress))
                {
                    throw new Exception(Language.Steam_executable_file_not_found);
                }
                if (!steamGame.IsInstalled)
                {
                    throw new Exception(Language.Steam_game_is_not_installed);
                }
                if (!steamGame.IsOwned)
                {
                    throw new Exception(Language.Steam_game_is_not_owned);
                }
                if (!GoProfile(profiles[profileIndex]))
                {
                    throw new Exception(Language.Can_not_change_active_profile);
                }
                var address = $"steam://rungameid/{steamGame.AppId}";
                if (!string.IsNullOrWhiteSpace(CommandLineOptions.Default.ExecuteArguments))
                {
                    address += "/" + CommandLineOptions.Default.ExecuteArguments;
                }
                var steamProcess = Process.Start(address);
                // Wait for steam game to update and then run
                var ticks = 0;
                while (ticks < CommandLineOptions.Default.ExecuteProcessTimeout * 1000)
                {
                    if (steamGame.IsRunning)
                    {
                        break;
                    }
                    Thread.Sleep(300);
                    if (!steamGame.IsUpdating)
                    {
                        ticks += 300;
                    }
                }
                IPCService.GetInstance().HoldProcessId = steamProcess?.Id ?? 0;
                IPCService.GetInstance().Status        = InstanceStatus.OnHold;
                NotifyIcon notify = null;
                try
                {
                    notify = new NotifyIcon
                    {
                        Icon = Properties.Resources.Icon,
                        Text = string.Format(
                            Language.Waiting_for_the_0_to_terminate,
                            steamGame.Name),
                        Visible = true
                    };
                    Application.DoEvents();
                }
                catch
                {
                    // ignored
                }
                // Wait for the game to exit
                if (steamGame.IsRunning)
                {
                    while (true)
                    {
                        if (!steamGame.IsRunning)
                        {
                            break;
                        }
                        Thread.Sleep(300);
                    }
                }
                if (notify != null)
                {
                    notify.Visible = false;
                    notify.Dispose();
                    Application.DoEvents();
                }
                IPCService.GetInstance().Status = InstanceStatus.Busy;
                if (!rollbackProfile.IsActive)
                {
                    if (!GoProfile(rollbackProfile))
                    {
                        throw new Exception(Language.Can_not_change_active_profile);
                    }
                }
            }
            else
            {
                if (!GoProfile(profiles[profileIndex]))
                {
                    throw new Exception(Language.Can_not_change_active_profile);
                }
            }
        }
    }
Exemple #26
0
        private void CitadelOnStartup(object sender, StartupEventArgs e)
        {
            // Here we need to check 2 things. First, we need to check to make sure that our filter
            // service is running. Second, and if the first condition proves to be false, we need to
            // check if we are running as an admin. If we are not admin, we need to schedule a
            // restart of the app to force us to run as admin. If we are admin, then we will create
            // an instance of the service starter class that will take care of forcing our service
            // into existence.
            bool needRestartAsAdmin = false;
            bool mainServiceViable  = true;

            try
            {
                var sc = new ServiceController("FilterServiceProvider");

                switch (sc.Status)
                {
                case ServiceControllerStatus.Stopped:
                case ServiceControllerStatus.StopPending:
                {
                    mainServiceViable = false;
                }
                break;
                }
            }
            catch (Exception ae)
            {
                mainServiceViable = false;
            }

            if (!mainServiceViable)
            {
                var id = WindowsIdentity.GetCurrent();

                var principal = new WindowsPrincipal(id);
                if (principal.IsInRole(WindowsBuiltInRole.Administrator))
                {
                    needRestartAsAdmin = false;
                }
                else
                {
                    needRestartAsAdmin = id.Owner == id.User;
                }

                if (needRestartAsAdmin)
                {
                    m_logger.Info("Restarting as admin.");

                    try
                    {
                        // Restart program and run as admin
                        ProcessStartInfo updaterStartupInfo = new ProcessStartInfo();
                        updaterStartupInfo.FileName       = "cmd.exe";
                        updaterStartupInfo.Arguments      = string.Format("/C TIMEOUT {0} && \"{1}\"", 3, Process.GetCurrentProcess().MainModule.FileName);
                        updaterStartupInfo.WindowStyle    = ProcessWindowStyle.Hidden;
                        updaterStartupInfo.Verb           = "runas";
                        updaterStartupInfo.CreateNoWindow = true;
                        Process.Start(updaterStartupInfo);
                    }
                    catch (Exception se)
                    {
                        LoggerUtil.RecursivelyLogException(m_logger, se);
                    }

                    Environment.Exit(-1);
                    return;
                }
                else
                {
                    // Just creating an instance of this will do the job of forcing our service to
                    // start. Letting it fly off into garbage collection land should have no effect.
                    // The service is self-sustaining after this point.
                    var provider = new ServiceRunner();
                }
            }

            // Hook the shutdown/logoff event.
            Current.SessionEnding += OnAppSessionEnding;

            // Hook app exiting function. This must be done on this main app thread.
            this.Exit += OnApplicationExiting;

            // Do stuff that must be done on the UI thread first. Here we HAVE to set our initial
            // view state BEFORE we initialize IPC. If we change it after, then we're going to get
            // desynchronized in our state.
            try
            {
                InitViews();
                OnViewChangeRequest(typeof(ProgressWait));
            }
            catch (Exception ve)
            {
                LoggerUtil.RecursivelyLogException(m_logger, ve);
            }

            try
            {
                // XXX FIXME
                m_ipcClient = IPCClient.InitDefault();
                m_ipcClient.AuthenticationResultReceived = (authenticationFailureResult) =>
                {
                    switch (authenticationFailureResult.Action)
                    {
                    case AuthenticationAction.Denied:
                    case AuthenticationAction.Required:
                    case AuthenticationAction.InvalidInput:
                    {
                        // User needs to log in.
                        BringAppToFocus();
                        OnViewChangeRequest(typeof(LoginView));
                    }
                    break;

                    case AuthenticationAction.Authenticated:
                    case AuthenticationAction.ErrorNoInternet:
                    case AuthenticationAction.ErrorUnknown:
                    {
                        OnViewChangeRequest(typeof(DashboardView));
                    }
                    break;
                    }
                };

                m_ipcClient.ServerAppUpdateRequestReceived = async(args) =>
                {
                    string updateSettingsPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "CloudVeil", "update.settings");

                    if (File.Exists(updateSettingsPath))
                    {
                        using (StreamReader reader = File.OpenText(updateSettingsPath))
                        {
                            string command = reader.ReadLine();

                            string[] commandParts = command.Split(new char[] { ':' }, 2);

                            if (commandParts[0] == "RemindLater")
                            {
                                DateTime remindLater;
                                if (DateTime.TryParse(commandParts[1], out remindLater))
                                {
                                    if (DateTime.Now < remindLater)
                                    {
                                        return;
                                    }
                                }
                            }
                            else if (commandParts[0] == "SkipVersion")
                            {
                                if (commandParts[1] == args.NewVersionString)
                                {
                                    return;
                                }
                            }
                        }
                    }

                    BringAppToFocus();

                    var updateAvailableString = string.Format("An update to version {0} is available. You are currently running version {1}. Would you like to update now?", args.NewVersionString, args.CurrentVersionString);

                    if (args.IsRestartRequired)
                    {
                        updateAvailableString += "\r\n\r\nThis update WILL require a reboot. Save all your work before continuing.";
                    }

                    await Current.Dispatcher.BeginInvoke(
                        System.Windows.Threading.DispatcherPriority.Normal,

                        (Action)async delegate()
                    {
                        if (m_mainWindow != null)
                        {
                            var result = await m_mainWindow.AskUserUpdateQuestion("Update Available", updateAvailableString);

                            switch (result)
                            {
                            case UpdateDialogResult.UpdateNow:
                                m_ipcClient.NotifyAcceptUpdateRequest();
                                m_mainWindow.ShowUserMessage("Updating", "The update is being downloaded. The application will automatically update and restart when the download is complete.");
                                break;

                            case UpdateDialogResult.RemindLater:
                                using (StreamWriter writer = new StreamWriter(File.Open(updateSettingsPath, FileMode.Create)))
                                {
                                    writer.WriteLine("RemindLater:{0}", DateTime.Now.AddDays(1).ToString("o"));
                                }

                                break;

                            case UpdateDialogResult.SkipVersion:
                                using (StreamWriter writer = new StreamWriter(File.Open(updateSettingsPath, FileMode.Create)))
                                {
                                    writer.WriteLine("SkipVersion:{0}", args.NewVersionString);
                                }

                                break;
                            }
                        }
                    });
                };

                m_ipcClient.ServerUpdateStarting = () =>
                {
                    Application.Current.Shutdown(ExitCodes.ShutdownForUpdate);
                };

                m_ipcClient.DeactivationResultReceived = (deactivationCmd) =>
                {
                    m_logger.Info("Deactivation command is: {0}", deactivationCmd.ToString());

                    if (deactivationCmd == DeactivationCommand.Granted)
                    {
                        if (CriticalKernelProcessUtility.IsMyProcessKernelCritical)
                        {
                            CriticalKernelProcessUtility.SetMyProcessAsNonKernelCritical();
                        }

                        m_logger.Info("Deactivation request granted on client.");

                        // Init the shutdown of this application.
                        Application.Current.Shutdown(ExitCodes.ShutdownWithoutSafeguards);
                    }
                    else
                    {
                        m_logger.Info("Deactivation request denied on client.");

                        Current.Dispatcher.BeginInvoke(
                            System.Windows.Threading.DispatcherPriority.Normal,
                            (Action) delegate()
                        {
                            if (m_mainWindow != null)
                            {
                                string message = null;
                                string title   = null;

                                switch (deactivationCmd)
                                {
                                case DeactivationCommand.Requested:
                                    message = "Your deactivation request has been received, but approval is still pending.";
                                    title   = "Request Received";
                                    break;

                                case DeactivationCommand.Denied:
                                    // A little bit of tact will keep the mob and their pitchforks
                                    // from slaughtering us.
                                    message = "Your deactivation request has been received, but approval is still pending.";
                                    title   = "Request Received";
                                    //message = "Your deactivation request has been denied.";
                                    //title = "Request Denied";
                                    break;

                                case DeactivationCommand.Granted:
                                    message = "Your request was granted.";
                                    title   = "Request Granted";
                                    break;

                                case DeactivationCommand.NoResponse:
                                    message = "Your deactivation request did not reach the server. Check your internet connection and try again.";
                                    title   = "No Response Received";
                                    break;
                                }

                                m_mainWindow.ShowUserMessage(title, message);
                            }
                        }
                            );
                    }
                };

                m_ipcClient.BlockActionReceived = (args) =>
                {
                    // Add this blocked request to the dashboard.
                    Current.Dispatcher.BeginInvoke(
                        System.Windows.Threading.DispatcherPriority.Normal,
                        (Action) delegate()
                    {
                        if (m_viewDashboard != null)
                        {
                            m_viewDashboard.AppendBlockActionEvent(args.Category, args.Resource.ToString());
                        }
                    }
                        );
                };

                m_ipcClient.ConnectedToServer = () =>
                {
                    m_logger.Info("Connected to IPC server.");
                };

                m_ipcClient.DisconnectedFromServer = () =>
                {
                    m_logger.Warn("Disconnected from IPC server! Automatically attempting reconnect.");
                };

                m_ipcClient.RelaxedPolicyExpired = () =>
                {
                    // We don't have to do anything here on our side, but we may want to do something
                    // here in the future if we modify how our UI shows relaxed policy timer stuff.
                    // Like perhaps changing views etc.
                };

                m_ipcClient.RelaxedPolicyInfoReceived = (args) =>
                {
                    Current.Dispatcher.BeginInvoke(
                        System.Windows.Threading.DispatcherPriority.Normal,
                        (Action) delegate()
                    {
                        // Bypass lists have been enabled.
                        if (args.PolicyInfo != null && m_viewDashboard.DataContext != null && m_viewDashboard.DataContext is DashboardViewModel)
                        {
                            var dashboardViewModel = ((DashboardViewModel)m_viewDashboard.DataContext);
                            dashboardViewModel.AvailableRelaxedRequests = args.PolicyInfo.NumberAvailableToday;
                            dashboardViewModel.RelaxedDuration          = new DateTime(args.PolicyInfo.RelaxDuration.Ticks).ToString("HH:mm");

                            // Ensure we don't overlap this event multiple times by decrementing first.
                            dashboardViewModel.Model.RelaxedPolicyRequested -= OnRelaxedPolicyRequested;
                            dashboardViewModel.Model.RelaxedPolicyRequested += OnRelaxedPolicyRequested;

                            // Ensure we don't overlap this event multiple times by decrementing first.
                            dashboardViewModel.Model.RelinquishRelaxedPolicyRequested -= OnRelinquishRelaxedPolicyRequested;
                            dashboardViewModel.Model.RelinquishRelaxedPolicyRequested += OnRelinquishRelaxedPolicyRequested;
                        }
                    }
                        );
                };

                m_ipcClient.StateChanged = (args) =>
                {
                    m_logger.Info("Filter status from server is: {0}", args.State.ToString());
                    switch (args.State)
                    {
                    case FilterStatus.CooldownPeriodEnforced:
                    {
                        // Add this blocked request to the dashboard.
                        Current.Dispatcher.BeginInvoke(
                            System.Windows.Threading.DispatcherPriority.Normal,
                            (Action) delegate()
                            {
                                if (m_viewDashboard != null)
                                {
                                    m_viewDashboard.ShowDisabledInternetMessage(DateTime.Now.Add(args.CooldownPeriod));
                                }
                            }
                            );
                    }
                    break;

                    case FilterStatus.Running:
                    {
                        OnViewChangeRequest(typeof(DashboardView));

                        // Change UI state of dashboard to not show disabled message anymore.
                        // If we're not already in a disabled state, this will have no effect.
                        Current.Dispatcher.BeginInvoke(
                            System.Windows.Threading.DispatcherPriority.Normal,
                            (Action) delegate()
                            {
                                if (m_viewDashboard != null)
                                {
                                    m_viewDashboard.HideDisabledInternetMessage();
                                }
                            }
                            );
                    }
                    break;

                    case FilterStatus.Synchronizing:
                    {
                        // Update our timestamps for last sync.
                        OnViewChangeRequest(typeof(ProgressWait));

                        lock (m_synchronizingTimerLockObj)
                        {
                            if (m_synchronizingTimer != null)
                            {
                                m_synchronizingTimer.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
                                m_synchronizingTimer.Dispose();
                            }

                            m_synchronizingTimer = new Timer((state) =>
                                {
                                    m_ipcClient.RequestStatusRefresh();
                                    m_synchronizingTimer.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
                                    m_synchronizingTimer.Dispose();
                                });

                            m_synchronizingTimer.Change(TimeSpan.FromSeconds(5), Timeout.InfiniteTimeSpan);
                        }
                    }
                    break;

                    case FilterStatus.Synchronized:
                    {
                        // Update our timestamps for last sync.
                        OnViewChangeRequest(typeof(DashboardView));

                        // Change UI state of dashboard to not show disabled message anymore.
                        // If we're not already in a disabled state, this will have no effect.
                        Current.Dispatcher.BeginInvoke(
                            System.Windows.Threading.DispatcherPriority.Normal,
                            (Action) delegate()
                            {
                                if (m_viewDashboard != null && m_viewDashboard.DataContext != null)
                                {
                                    var dashboardViewModel      = ((DashboardViewModel)m_viewDashboard.DataContext);
                                    dashboardViewModel.LastSync = DateTime.Now;
                                }
                            }
                            );
                    }
                    break;
                    }
                };

                m_ipcClient.ClientToClientCommandReceived = (args) =>
                {
                    switch (args.Command)
                    {
                    case ClientToClientCommand.ShowYourself:
                    {
                        BringAppToFocus();
                    }
                    break;
                    }
                };

                m_ipcClient.CaptivePortalDetectionReceived = (msg) =>
                {
                    // C# doesn't like cross-thread GUI variable access, so run this on window thread.
                    m_mainWindow.Dispatcher.InvokeAsync(() =>
                    {
                        ((MainWindowViewModel)m_mainWindow.DataContext).ShowIsGuestNetwork = msg.IsCaptivePortalDetected;
                    });
                };

#if CAPTIVE_PORTAL_GUI_ENABLED
                m_ipcClient.CaptivePortalDetectionReceived = (msg) =>
                {
                    if (msg.IsCaptivePortalDetected && !m_captivePortalShownToUser)
                    {
                        if (m_mainWindow.Visibility == Visibility.Visible)
                        {
                            if (!m_mainWindow.IsVisible)
                            {
                                BringAppToFocus();
                            }

                            ((MainWindowViewModel)m_mainWindow.DataContext).ShowIsGuestNetwork = true;
                        }
                        else
                        {
                            DisplayCaptivePortalToolTip();
                        }

                        m_captivePortalShownToUser = true;
                    }
                    else if (!msg.IsCaptivePortalDetected)
                    {
                        m_captivePortalShownToUser = false;
                    }
                };
#endif
            }
            catch (Exception ipce)
            {
                LoggerUtil.RecursivelyLogException(m_logger, ipce);
            }

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            // Run the background init worker for non-UI related initialization.
            m_backgroundInitWorker                     = new BackgroundWorker();
            m_backgroundInitWorker.DoWork             += DoBackgroundInit;
            m_backgroundInitWorker.RunWorkerCompleted += OnBackgroundInitComplete;

            m_backgroundInitWorker.RunWorkerAsync(e);
        }
Exemple #27
0
        private static void RunGuiChecks(bool startMinimized)
        {
            guiChecks = PlatformTypes.New <IGUIChecks>();

            // First, lets check to see if the user started the GUI in an isolated session.
            try
            {
                if (guiChecks.IsInIsolatedSession())
                {
                    LoggerUtil.GetAppWideLogger().Error("GUI client start in an isolated session. This should not happen.");
                    Environment.Exit((int)ExitCodes.ShutdownWithoutSafeguards);
                    return;
                }
            }
            catch
            {
                Environment.Exit((int)ExitCodes.ShutdownWithoutSafeguards);
                return;
            }

            try
            {
                bool createdNew = false;
                if (guiChecks.PublishRunningApp())
                {
                    createdNew = true;
                }

                /**/

                if (!createdNew)
                {
                    try
                    {
                        if (!startMinimized)
                        {
                            guiChecks.DisplayExistingUI();
                        }
                    }
                    catch (Exception e)
                    {
                        LoggerUtil.RecursivelyLogException(LoggerUtil.GetAppWideLogger(), e);
                    }

                    // In case we have some out of sync state where the app is running at a higher
                    // privilege level than us, the app won't get our messages. So, let's attempt an
                    // IPC named pipe to deliver the message as well.
                    try
                    {
                        // Something about instantiating an IPCClient here is making it all blow up in my face.
                        using (var ipcClient = IPCClient.InitDefault())
                        {
                            if (!startMinimized)
                            {
                                ipcClient.RequestPrimaryClientShowUI();
                            }

                            // Wait plenty of time before dispose to allow delivery of the message.
                            Task.Delay(500).Wait();
                        }
                    }
                    catch (Exception e)
                    {
                        // The only way we got here is if the server isn't running, in which case we
                        // can do nothing because its beyond our domain.
                        LoggerUtil.RecursivelyLogException(LoggerUtil.GetAppWideLogger(), e);
                    }

                    LoggerUtil.GetAppWideLogger().Info("Shutting down process since one is already open.");

                    // Close this instance.
                    Environment.Exit((int)ExitCodes.ShutdownProcessAlreadyOpen);
                    return;
                }
            }
            catch (Exception e)
            {
                // The only way we got here is if the server isn't running, in which case we can do
                // nothing because its beyond our domain.
                LoggerUtil.RecursivelyLogException(LoggerUtil.GetAppWideLogger(), e);
                return;
            }
        }
        public void Test_NotFound_NotRunned()
        {
            IPCClient<ITheSame> target = new IPCClient<ITheSame>("Test2", "Test");
            ITheSame res = target.GetService();

            int resget = 0;
            Action ac = () => resget = res.Get(0);
            ac.ShouldThrow<EndpointNotFoundException>();
        }