Exemplo n.º 1
0
 public static void Main(string[] args)
 {
     if (SingleInstance <App> .InitializeAsFirstInstance(SingleInstanceUid))
     {
         // making it this far means that we are THE single instance
         try
         {
             if (PreGuiCommandLineArgs(args))
             {
                 return;
             }
             var app = new App();
             app.InitializeComponent();
             app.Run();
         }
         finally
         {
             SingleInstance <App> .Cleanup();
         }
     }
 }
Exemplo n.º 2
0
        public static void Main()
        {
            if (App._settings.App_UpgradeRequired)
            {
                App._settings.Upgrade();
                App._settings.App_UpgradeRequired = false;
            }
            string directoryName = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);

            if (!string.IsNullOrEmpty(directoryName) && System.IO.Directory.GetCurrentDirectory() != directoryName)
            {
                System.IO.Directory.SetCurrentDirectory(directoryName);
            }
            if (SingleInstance <App> .InitializeAsFirstInstance("Not all of us can do great things. But we can do small things with great love."))
            {
                App app = new App();
                app.InitializeComponent();
                app.Run();
                SingleInstance <App> .Cleanup();
            }
        }
Exemplo n.º 3
0
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            if (SingleInstance <App> .InitializeAsFirstInstance(Unique))
            {
                int    file  = 0;
                string path  = null;
                bool   exist = false;
                int    theme = 0;
                double vol   = 1;
                try
                {
                    if (WPF_Study.Properties.Settings.Default != null)
                    {
                        vol   = WPF_Study.Properties.Settings.Default.Volume;
                        theme = WPF_Study.Properties.Settings.Default.Theme;
                        if (WPF_Study.Properties.Settings.Default.Track.Capacity != 0)
                        {
                            exist = true;
                        }
                    }
                }
                catch (Exception) { }
                if (e.Args.Length == 1)
                {
                    if (e.Args[0].EndsWith(".lpl"))
                    {
                        path = e.Args[0];
                        file = 1;
                    }
                    else if (e.Args[0].EndsWith(".mp3") || e.Args[0].EndsWith(".flac") || e.Args[0].EndsWith(".wav") || e.Args[0].EndsWith(".aac") || e.Args[0].EndsWith(".m4a"))
                    {
                        path = e.Args[0];
                        file = 2;
                    }
                }

                new MainWindow(theme, musicLoad: path, fileExt: file, start: 1, vol: vol, hasPlaylist: exist).Show();
                SingleInstance <App> .Cleanup();
            }
        }
Exemplo n.º 4
0
        public static void Main()
        {
#if SQUIRREL
            if (SingleInstance <App> .InitializeAsFirstInstance(Unique))
            {
                var application = new App();

                application.InitializeComponent();
                application.ChangeTheme(Theme.Dark);
                application.Run();

                // Allow single instance code to perform cleanup operations
                SingleInstance <App> .Cleanup();
            }
#else
            var application = new App();

            application.InitializeComponent();
            application.ChangeTheme(Theme.Dark);
            application.Run();
#endif
        }
Exemplo n.º 5
0
        public static void Main(string[] args)
        {
            if (SingleInstance <App> .InitializeAsFirstInstance(UniqueName))
            {
                if (args.Length != 0)
                {
                    var player = MainWindowViewModel.Instance;
                    player.OpenFile(args[0]);
                    player.Play();

                    _application = new App();
                    _application.InitializeComponent();
                    _application.Run();

                    player.Free();
                }


                // Allow single instance code to perform cleanup operations
                SingleInstance <App> .Cleanup();
            }
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            //1.0.0.12 1.0.0.13 http://net.4006337366.com/UpdateFiles/1.0.0.13.zip D:\Program Files\HXD\SampleCabinetManage
            //args = new string[] { "1.0.0.13","1.0.0.14","1","http://net.4006337366.com/UpdateFiles/1.0.0.14.zip",
            //    @"D:\Program Files\HXD\SampleCabinetManage",""};
            if (args.Length != 6)
            {
                return;
            }
            if (SingleInstance <App> .InitializeAsFirstInstance(AppId))
            {
                System.Threading.Thread.Sleep(1000 * 2);
                var win = new MainWindow();
                var vm  = new MainWindowViewModel(args, win.Close);
                win.DataContext = vm;

                var application = new App();
                application.InitializeComponent();
                application.Run(win);
                SingleInstance <App> .Cleanup();
            }
        }
Exemplo n.º 7
0
        public static void Main()
        {
            AppInfo.BaseAppInfo.Log.QueueLogMessageAsync($"Determining if another instance of {AppInfo.BaseAppInfo.AppName} is running.");
            if (SingleInstance <App> .InitializeAsFirstInstance("LogViewer_sag65s4df684wefsgfr9w8se7xzhst"))
            {
                AppInfo.BaseAppInfo.Log.QueueLogMessageAsync($"Determined that no other application instances are running. Continuing execution.");
                new SplashScreen("SplashScreen1.png").Show(true);

                //Upgrade user settings
                try
                {
                    if (Settings.Default.UpgradeSettings)
                    {
                        AppInfo.BaseAppInfo.Log.QueueLogMessageAsync($"Upgrading user settings.");
                        Settings.Default.Upgrade();
                        Settings.Default.UpgradeSettings = false;
                        Settings.Default.Save();
                        AppInfo.BaseAppInfo.Log.QueueLogMessageAsync($"User settings successfully upgraded.");
                    }
                }
                catch (Exception ex)
                {
                    AppInfo.BaseAppInfo.Log.QueueLogMessageAsync($"Failed to upgrade user settings. Error message: {ex.Message}", LogMessageType.Error);
                }

                var application = new App();
                application.InitializeComponent();
                application.Run();

                // Allow single instance code to perform cleanup operations
                SingleInstance <App> .Cleanup();
            }
            else
            {
                AppInfo.BaseAppInfo.Log.QueueLogMessageAsync($"Determined that another application instance is running. Forwarding command parameters to existing instance and terminating.");
                AppInfo.BaseAppInfo.Log.Dispose();
            }
        }
Exemplo n.º 8
0
        public static void Main()
        {
            // If this is the first instance...
            if (SingleInstance <App> .InitializeAsFirstInstance(UniqueStringForSingleInstanceApp))
            {
                try
                {
                    var application = new App();
                    application.InitializeComponent();
                    application.Run();
                }
                catch (Exception ex)
                {
                    // Global application exception logging can be handled here.

                    //Log.WriteEvent(
                    //    ex,
                    //    Message: "Unhandled Exception Caught at App level.",
                    //    Sender: "App.Xaml.cs",
                    //    Method: "Main()");

                    string innerException = "";
                    string stackTrace     = "";
                    if (ex.InnerException != null)
                    {
                        innerException = ex.InnerException.ToString();
                    }
                    if (ex.StackTrace != null)
                    {
                        stackTrace = ex.StackTrace;
                    }
                    MessageBox.Show(ex.Message + Environment.NewLine + innerException + Environment.NewLine + stackTrace);
                }

                // Allow single instance code to perform cleanup operations
                SingleInstance <App> .Cleanup();
            }
        }
Exemplo n.º 9
0
        public static void Main(string[] args)
        {
            try
            {
                if (SingleInstance <App> .InitializeAsFirstInstance("POS"))
                {
                    var application = new App();

                    application.InitializeComponent();
                    application.Run();
                    application.DispatcherUnhandledException += Application_DispatcherUnhandledException;
                    // Allow single instance code to perform cleanup operations
                    SingleInstance <App> .Cleanup();
                }
                Timeline.DesiredFrameRateProperty.OverrideMetadata(typeof(Timeline), new FrameworkPropertyMetadata {
                    DefaultValue = 10
                });
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemplo n.º 10
0
        public static void Main(string[] args)
        {
            var assemblyLocation = Assembly.GetEntryAssembly().Location;

            if (!args.Contains("-no-shadow"))
            {
                var shadowPath = Path.Combine(Environment.CurrentDirectory, "launcher.shadow.exe");
                if (File.Exists(shadowPath))
                {
                    File.Delete(shadowPath);
                }

                File.Copy(assemblyLocation, shadowPath);

                Process.Start(new ProcessStartInfo
                {
                    FileName  = shadowPath,
                    Arguments = string.Join(" ", args.Concat(new[] { "-no-shadow" }))
                });

                Environment.Exit(0);
            }

            var identifier = assemblyLocation?.Replace('\\', '_') ?? FallbackSingleInstanceIdentifier;

            if (SingleInstance <App> .InitializeAsFirstInstance(identifier))
            {
                var application = new App();

                application.InitializeComponent();
                application.Run();

                // Allow single instance code to perform cleanup operations
                SingleInstance <App> .Cleanup();
            }
        }
Exemplo n.º 11
0
        public static void Main()
        {
            int exitCode = 0;

            if (SingleInstance <App> .InitializeAsFirstInstance(Unique, out exitCode))
            {
                SplashScreen splashScreen = new SplashScreen("resources/toolset_splash.png");
                if (Environment.GetCommandLineArgs().Length == 1)
                {
                    splashScreen.Show(false);
                }
                App app = new App();
                app.InitializeComponent();
                splashScreen.Close(TimeSpan.FromMilliseconds(1));
                app.Run();

                // Allow single instance code to perform cleanup operations
                SingleInstance <App> .Cleanup();
            }
            else
            {
                Environment.Exit(exitCode);
            }
        }
Exemplo n.º 12
0
        public static void Main(string[] args)
        {
            // manually set TLS v1.2 for all HTTP requests in current application domain!
            if (System.Net.ServicePointManager.SecurityProtocol < System.Net.SecurityProtocolType.Tls12)
            {
                System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
            }

            // set Application version globally
            Platform.Version = Assembly.GetExecutingAssembly().GetName().Version.ToString();

            //Logging.SetLogFile("C:\\delme\\ivpnclient.log");
            //Logging.Enable();

            if (!CheckConfig())
            {
                return;
            }

            if (!TryUpgradeSettings())
            {
                return;
            }

            Platform.InstallationDirectory = Path.GetDirectoryName(GetExecutingAssemblyFile());

            if (SingleInstance <App> .InitializeAsFirstInstance("IVPNClient"))
            {
                var application = new App();
                application.DispatcherUnhandledException += App_DispatcherUnhandledException;
                application.InitializeComponent();
                application.Run();

                SingleInstance <App> .Cleanup();
            }
        }
Exemplo n.º 13
0
        public static void Main()
        {
            if (!SingleInstance <App> .InitializeAsFirstInstance(Unique))
            {
                return;
            }
            var application = new App();

            //ini business rules
            var appSettings = ACMC_Library_System.Properties.Settings.Default;

            BusinessRules.MemberRenewPeriodInYEar = appSettings.MemberRenewPeriodInYear;
            BusinessRules.ItemRenewPeriodInDay    = appSettings.ItemRenewPeriodInDay;
            BusinessRules.DefaultQuotaPerMember   = appSettings.DefaultQuotaPerMember;
            BusinessRules.FinesPerWeek            = appSettings.FinesPerWeek;
            BusinessRules.LibMemberBarcode        = appSettings.LibMemberBarcode;
            BusinessRules.LibMemberId             = appSettings.LibMemberId;

            application.InitializeComponent();
            application.Run();

            // Allow single instance code to perform cleanup operations
            SingleInstance <App> .Cleanup();
        }
Exemplo n.º 14
0
        public static void Main(string[] args)
        {
            bool isRunOnMono = TraceLabSDK.RuntimeInfo.IsRunInMono;
            bool startInstance;

            if (!isRunOnMono)
            {
                //in windows TraceLab runs as single instance application
                //preventing TraceLab being open as multiple processes
                startInstance = (SingleInstance.InitializeAsFirstInstance(Unique));
            }
            else
            {
                //in mono don't use single instance startup
                //single instance must be developed in another way than on windows
                startInstance = true;
            }

            if (startInstance)
            {
                try
                {
                    try
                    {
                        Thread.CurrentThread.CurrentCulture = ThreadFactory.DefaultCulture;
                        var app = new TraceLabApplicationGUI();
                        app.Run(args);
                    }
                    catch (InvalidKeyException e)
                    {
                        if (!isRunOnMono)
                        {
                            System.Windows.Forms.MessageBox.Show(e.Message, @"Invalid key!",
                                                                 System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
                        }
                        else
                        {
                            //attempt to display missing key warning in Gtk
                            TraceLabApplicationGUI.DisplayGtkErrorDialog(e.Message, "Warning");
                        }
                    }
                    catch (Exception e)
                    {
                        if (!isRunOnMono)
                        {
                            System.Windows.Forms.MessageBox.Show(e.Message, @"An Exception occurred.",
                                                                 System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                        }
                        else
                        {
                            //attempt to display error in Gtk (this is absolutely CRITICAL error, Gtk Main catches it's own unhandled exceptions)
                            TraceLabApplicationGUI.DisplayGtkErrorDialog(e.Message, "Error");
                        }
                    }
                }
                finally
                {
                    if (!isRunOnMono)
                    {
                        // Allow single instance code to perform cleanup operations
                        SingleInstance.Cleanup();
                    }
                }
            }
        }
Exemplo n.º 15
0
        public static void Main()
        {
            try
            {
                CultureInfo cInf = new CultureInfo(RegistrySettings.Default.UiCulture);
                Loksim3D.WetterEdit.Resources.Strings.Culture = cInf;
            }
            catch (ArgumentException ex)
            {
                MessageBox.Show("Invalid Language Settings " + RegistrySettings.Default.UiCulture + "\n" + ex.Message);
            }


            if (Environment.OSVersion.Version.Major >= 6 && RegistrySettings.Default.DefaultAdminStartMode != RegistrySettings.AdminStartMode.DoNotStartAsAdmin)
            {
                // Unter Vista oder höher prüfen ob wir in das Datenverzeichnis lt. paths.ini schreiben dürfen
                // Wenn nicht schauen wir ob wir als Admin ausgeführt werden
                // Wenn nicht als Admin ausgeführt => User fragen ob als Admin ausführen bzw in Optionen nachschauen was user möchte

                string datadir = L3dFilePath.LoksimDirectory.AbsolutePath;

                try
                {
                    string file = TempFileUtility.GetTempFileName("l3d", 0, datadir /*Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)*/);
                    File.Delete(file);
                }
                catch (Win32Exception ex)
                {
                    if (ex.ErrorCode == TempFileUtility.ERROR_ACCESS_DENIED)
                    {
                        IntPtr tkHandle;
                        IntPtr procHandle = Process.GetCurrentProcess().Handle;
                        Win32Utility.OpenProcessToken(procHandle,
                                                      (uint)System.Security.Principal.TokenAccessLevels.Read, out tkHandle);

                        uint TokenInfLength = 0;
                        bool Result;

                        // first call gets lenght of TokenInformation
                        Result = Win32Utility.GetTokenInformation(tkHandle, Win32Utility.TOKEN_INFORMATION_CLASS.TokenElevation, IntPtr.Zero, TokenInfLength, out TokenInfLength);
                        IntPtr TokenInformation = Marshal.AllocHGlobal((int)TokenInfLength);

                        Result = Win32Utility.GetTokenInformation(tkHandle, Win32Utility.TOKEN_INFORMATION_CLASS.TokenElevation, TokenInformation, TokenInfLength, out TokenInfLength);
                        if (Result)
                        {
                            Win32Utility.TOKEN_ELEVATION TokenElevation = (Win32Utility.TOKEN_ELEVATION)Marshal.PtrToStructure(TokenInformation, typeof(Win32Utility.TOKEN_ELEVATION));
                            TaskDialog dlg = new TaskDialog
                            {
                                Caption               = Strings.UacDlgCaption,
                                InstructionText       = Strings.UacDlgInstructionText,
                                Text                  = Strings.UacDlgText,
                                FooterCheckBoxChecked = false,
                                FooterCheckBoxText    = Strings.UacDlgCheckBoxText,
                                Cancelable            = false,
                            };
                            TaskDialogButton btn = new TaskDialogButton {
                                Text = Strings.UacDlgBtnAdmin, UseElevationIcon = true, Default = true
                            };
                            btn.Click += (sender, e) => dlg.Close(TaskDialogResult.Yes);
                            dlg.Controls.Add(btn);
                            btn = new TaskDialogButton {
                                Text = Strings.UacDlgBtnNoAdmin
                            };
                            btn.Click += (sender, e) => dlg.Close(TaskDialogResult.No);
                            dlg.Controls.Add(btn);
                            if (RegistrySettings.Default.DefaultAdminStartMode == RegistrySettings.AdminStartMode.StartAsAdmin || dlg.Show() == TaskDialogResult.Yes)
                            {
                                if (dlg.FooterCheckBoxChecked.GetValueOrDefault(false))
                                {
                                    RegistrySettings.Default.DefaultAdminStartMode = RegistrySettings.AdminStartMode.StartAsAdmin;
                                }

                                ProcessStartInfo info = new ProcessStartInfo();
                                info.FileName        = System.Reflection.Assembly.GetCallingAssembly().Location;
                                info.UseShellExecute = true;
                                info.Verb            = "runas"; // Provides Run as Administrator
                                info.Arguments       = EscapeCommandLineArguments(Environment.GetCommandLineArgs());
                                Process.Start(info);
                                Marshal.FreeHGlobal(TokenInformation);
                                return;
                            }
                            else if (RegistrySettings.Default.DefaultAdminStartMode == RegistrySettings.AdminStartMode.Ask && dlg.FooterCheckBoxChecked.GetValueOrDefault(false))
                            {
                                RegistrySettings.Default.DefaultAdminStartMode = RegistrySettings.AdminStartMode.DoNotStartAsAdmin;
                            }
                        }
                        Marshal.FreeHGlobal(TokenInformation);
                    }
                }
            }

            // Der Editor soll pro Installation nur 1x gestartet werden können.
            // Hat der User mehrere Editoren in unterschiedlichen Verzeichnissen oder mit unterschiedlichen Namen, kann er diese jeweils 1x starten
            // Deshalb ist in der Unique-ID auch noch die Assembly Location kodiert
            if (SingleInstance <App> .InitializeAsFirstInstance(Unique + "-" + System.Reflection.Assembly.GetCallingAssembly().Location.GetHashCode()))
            {
                var application = new App();

                application.InitializeComponent();
                application.Run();

                // Allow single instance code to perform cleanup operations
                SingleInstance <App> .Cleanup();
            }
        }
Exemplo n.º 16
0
        public static void Main()
        {
            if (Environment.GetCommandLineArgs().Length == 1)
            {
                if (AdminCheck.IsAdministrator())
                {
                    SetDefaults.FileAssociations.SetAssociation();
                }
                else
                {
                    MessageBox.Show("It appears that you are running ImageViewer directly. Please run as administrator if you are trying to set defaults.", "ImageViewer", MessageBoxButton.OK, MessageBoxImage.Information);

                    Environment.Exit(0);
                }
            }
            if (AdminCheck.IsAdministrator() && Default.SetDefaults)
            {
                SetDefaults.FileAssociations.SetAssociation();

                Default.SetDefaults = false;

                Default.Save();

                MessageBox.Show("ImageViewer is now set as a file handler for common images. Please set the Windows default image viewer also.", "ImageViewer", MessageBoxButton.OK, MessageBoxImage.Information);

                Process.Start("ms-settings:defaultapps");

                Environment.Exit(0);
            }
            if (Default.UpgradeRequired)
            {
                Default.Upgrade();

                Default.UpgradeRequired = false;

                if (Default.FirstRun)
                {
                    if (Default.FirstRun)
                    {
                        var results = MessageBox.Show("Would you like me to set this program as the default image viewer for common images?", "ImageViewer", MessageBoxButton.YesNo, MessageBoxImage.Information);
                        if (results == MessageBoxResult.Yes)
                        {
                            Default.SetDefaults = true;

                            ForceSetAssociation = true;
                        }
                        else
                        {
                            Default.SetDefaults = false;
                        }
                    }
                }

                Default.FirstRun = false;

                Default.Save();
            }

            if (Default.KeepDefaults || ForceSetAssociation)
            {
                SetAssociations();
            }

            int args = Environment.GetCommandLineArgs().Length;

            if (args == 1 && Default.SetDefaults)
            {
                MessageBox.Show("This program is meant to be opened by images with this app being the default handler for common image types.", "ImageViewer", MessageBoxButton.OK, MessageBoxImage.Information);

                Environment.Exit(0);
            }
            else if (args == 1)
            {
                var result = MessageBox.Show("This program is meant to be opened by images with this app being the default handler for common image types." + Environment.NewLine + Environment.NewLine + "Would you like me to set this program as the default image viewer for common images?", "ImageViewer", MessageBoxButton.YesNo, MessageBoxImage.Information);
                if (result == MessageBoxResult.Yes)
                {
                    Default.SetDefaults = true;

                    Default.Save();

                    SetAssociations();
                }

                Environment.Exit(0);
            }

            if (SingleInstance <App> .InitializeAsFirstInstance("ImageViewer"))
            {
                App app = new App();
                app.InitializeComponent();
                app.Run();

                SingleInstance <App> .Cleanup();
            }
        }
Exemplo n.º 17
0
        protected override void OnStartup(StartupEventArgs e)
        {
            Current.DispatcherUnhandledException += OnDispatcherUnhandledException;

            base.OnStartup(e);
            if (!SingleInstance <App> .InitializeAsFirstInstance(PhoenixUniqueKey))
            {
                Current.Shutdown();
                return;
            }
            OriginResolution = new Rect {
                Width  = SystemParameters.VirtualScreenWidth,
                Height = SystemParameters.VirtualScreenHeight
            };
            if (Settings.Default.ResetPennding)
            {
                Settings.Default.Reset();
            }
            if (Settings.Default.ModeIndex == -1)
            {
                Utils.UpdateScreenResolution();
            }
            if (string.IsNullOrEmpty(Settings.Default.BackupPath))
            {
                var executionPath = AppDomain.CurrentDomain.BaseDirectory;
                var backupPath    = string.Format(@"{0}Backup", executionPath);

                Settings.Default.BackupPath = backupPath;
                Settings.Default.Save();
            }
            if (!Directory.Exists(Settings.Default.BackupPath))
            {
                Directory.CreateDirectory(Settings.Default.BackupPath,
                                          new DirectorySecurity(AppDomain.CurrentDomain.BaseDirectory,
                                                                AccessControlSections.Owner));
            }
            Utils.SetResolution();
            Utils.EnsureCulture();

            Utils.AddThemeBaseDictionaries();
            try {
                DbContext.Init();
            } catch (Exception ex) {
                Logger.Write(ex);
                MessageWindowHelpers.Show(null, SplashResources.DatabaseInitFailed, MessageBoxButton.OK,
                                          MessageBoxImage.Hand);
                Current.Shutdown();
                return;
            }
            try {
                PropsService.Get(Guid.NewGuid());
            } catch (Exception ex) {
                Logger.Write(ex);
                MessageWindowHelpers.Show(null, SplashResources.DatabaseTestFailed, MessageBoxButton.OK,
                                          MessageBoxImage.Hand);
                Current.Shutdown();
                return;
            }
            try {
                var administratorRole = RolesService.Instanse.GetAdministrator(false);
                if (administratorRole == null)
                {
                    RolesService.Instanse.CreateAdministrator();
                }

                var systemUser = UsersService.Instanse.GetSystemUser(false);
                if (systemUser == null)
                {
                    UsersService.Instanse.CreateSystemUser();
                }
            } catch (Exception exception) {
                Logger.Write(exception);
                MessageWindowHelpers.Show(null, SplashResources.TestCheckIndeedRecordsFailed, MessageBoxButton.OK,
                                          MessageBoxImage.Hand);
            }
        }
Exemplo n.º 18
0
        public static void Main()
        {
            //first code executed upon application start
            string[] args  = Environment.GetCommandLineArgs();
            bool     rflag = false;

            foreach (string arg in args)
            {
                if (arg == "-r")
                {
                    rflag = true;
                }
            }

            //starts MainWindow only if no instance already exists
            if (SingleInstance <App> .InitializeAsFirstInstance(Unique))
            {
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

                var application = new App();
                application.InitializeComponent();
                application.Run( );
                SingleInstance <App> .Cleanup();
            }
            //if -r (restart) flag is used it will simultanoesuly send shutdown command to first instance and
            //start waiting for first instance to close, upto 5sec, before starting MainWindow
            else if (rflag == true)
            {
                SingleInstance <App> .Cleanup();

                for (int i = 0; i <= 20; i++)
                {
                    try
                    {
                        if (SingleInstance <App> .InitializeAsFirstInstance(Unique))
                        {
                            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

                            var application = new App();
                            application.InitializeComponent();
                            application.Run( );
                            break;
                        }
                    }
                    catch
                    {
                        SingleInstance <App> .Cleanup();

                        if (i >= 20)
                        {
                            MessageBox.Show("Timeout waiting for original WiinUSoft instance to close");
                        }
                    }
                    System.Threading.Thread.Sleep(250);
                }
                SingleInstance <App> .Cleanup();
            }

            //code below will be exeucted after MainWindow closes OR
            //immedietly in the case when MainWindow is be created
            //and is executed before termination
        }
Exemplo n.º 19
0
        public static void Main()
        {
            try
            {
                string[] args = Environment.GetCommandLineArgs();

                if (args.Length >= 2)
                {
                    switch (args[1].ToLower())
                    {
                    case "/update":
                        string localPath = (new FileInfo(Process.GetCurrentProcess().MainModule.FileName)).DirectoryName;
                        string oldFile   = localPath + "\\UpdateManager.exe";
                        string tempDir   = Data.UpdatesWorkingDirectory;
                        string newFile   = tempDir + "\\~UpdateManager.exe";

                        try
                        {
                            File.Delete(oldFile);
                            File.Move(newFile, oldFile);
                        }
                        catch { }

                        if (Directory.GetFiles(tempDir, "*", SearchOption.AllDirectories).Length == 0)
                        {
                            Directory.Delete(tempDir, true);
                        }

                        return;

                    case "/nosingleinstance":
                        try { DisableProcessWindowsGhosting(); }
                        catch { }

                        if (Settings.FirstRun)
                        {
                            FirstRun();
                        }

                        args = null;

                        new App().Run();

                        return;

                    case "/setkey":
                        Activation.ActivationGracePeriodStart = DateTime.Now;
                        Activation.Key = args[2];
                        return;

                    case "/activate":
                        string keyHash = args[2];
                        string key     = Activation.Key;
                        if (Encryption.DecryptStringFromBytes(Convert.FromBase64String(keyHash),
                                                              SecurityKeys.GenerateKey(key), SecurityKeys.GenerateIV(key))
                            == key)
                        {
                            Activation.Activate();
                        }
                        return;

                    default:
                        break;
                    }
                }

                if (SingleInstance <App> .InitializeAsFirstInstance(AssemblyAttributeAccessors.AssemblyTitle + "_" + AssemblyAttributeAccessors.AssemblyVersion))
                {
                    try { DisableProcessWindowsGhosting(); }
                    catch { }

                    if (Settings.FirstRun)
                    {
                        FirstRun();
                    }

                    args = null;

                    new App().Run();

                    // Allow single instance code to perform cleanup operations
                    SingleInstance <App> .Cleanup();
                }
            }
            catch (Exception exc)
            {
                // Log the exception
                Log(exc);

                // Restart
                Process.Start(Process.GetCurrentProcess().MainModule.FileName, string.Join(" ", Environment.GetCommandLineArgs()));

                // Shutdown
                Environment.Exit(-1);
            }
        }
Exemplo n.º 20
0
        private void OnStartup(object sender, StartupEventArgs e)
        {
            const string key = "DivvunInstaller";

            AttachConsole(AttachParentProcess);

            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

            SelfLog.Enable(msg => Debug.WriteLine(msg));
            ConfigureLogging();

            Log.Information("Loading Divvun Manager v{version}",
                            ThisAssembly.AssemblyInformationalVersion);

            if (!SingleInstance <PahkatApp> .InitializeAsFirstInstance(key))
            {
                Log.Information("App already running; aborting.");
                Log.CloseAndFlush();
                Current.Shutdown();
            }

            if (!Debugger.IsAttached)
            {
                SentrySdk.Init(options => {
                    options.Release        = ThisAssembly.AssemblyInformationalVersion;
                    options.Dsn            = Divvun.Installer.Properties.Constants.SentryDsn;
                    options.SendDefaultPii = true;
                });

                Current.DispatcherUnhandledException += (o, args) => {
                    Log.Fatal(args.Exception, "Unhandled exception in dispatcher");
                    SentrySdk.CaptureException(args.Exception);
                    PreExit();
                    MessageBox.Show(args.Exception.Message, "Error");
                    Current.Shutdown(1);
                };
            }
            else
            {
                Log.Warning("RUNNING WITH DEBUGGER -- No Sentry and no uncaught exception handling.");
            }

            Settings = Settings.Create();

            // Set the UI language
            Settings.Mutate(file => {
                if (file.Language != null)
                {
                    Strings.Culture = Util.Util.GetCulture(file.Language);
                }
            });

            try {
                PackageStore = new PahkatClient();
            }
            catch (Exception _) {
                MessageBox.Show(
                    "The service responsible for managing installations was not found. It may be currently updating, or has crashed. If problems persist, try rebooting your computer.",
                    "Could not connect to Pahkat Service"
                    );
                Current.Shutdown(1);
            }
        }