Exemplo n.º 1
0
            public virtual void UnpackRetryUpdater(IAbsoluteFilePath sourceFile, IAbsoluteDirectoryPath outputFolder,
                                                   bool overwrite = false, bool fullPath = true)
            {
                if (sourceFile == null)
                {
                    throw new ArgumentNullException(nameof(sourceFile));
                }
                if (outputFolder == null)
                {
                    throw new ArgumentNullException(nameof(outputFolder));
                }

                FileUtil.Ops.AddIORetryDialog(() => {
                    try {
                        Unpack(sourceFile, outputFolder, overwrite, fullPath);
                    } catch (UnauthorizedAccessException) {
                        if (!UacHelper.CheckUac())
                        {
                            throw;
                        }
                        UnpackUpdater(sourceFile, outputFolder, overwrite, fullPath);
                    } catch (IOException) {
                        if (!UacHelper.CheckUac())
                        {
                            throw;
                        }
                        UnpackUpdater(sourceFile, outputFolder, overwrite, fullPath);
                    }
                });
            }
Exemplo n.º 2
0
        public static void UpdateExecPath()
        {
            using (var adapter = new TaskSchedulerWrapper())
            {
                if (adapter.CheckExecPathIsCorrect())
                {
                    return;
                }

                if (adapter.CheckTaskExists())
                {
                    if (UacHelper.IsRunningAsAdmin() == false)
                    {
                        // we can do nothing if the app is not started in admin mode
                        return;
                    }

                    adapter.DeleteTaskIfNeeded();
                    adapter.CreateTask();
                }
                else
                {
                    ShortcutHelper.CreateStartupShortcut();
                }
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Install HID Guardian
        /// </summary>
        /// <remarks>Must be executed in administrative mode.</remarks>
        public static void InstallHidGuardian(ProcessWindowStyle style = ProcessWindowStyle.Hidden)
        {
            // Extract files first.
            ExtractHidGuardianFiles(true);
            var folder   = GetHidGuardianPath();
            var paString = Environment.Is64BitOperatingSystem ? "x64" : "x86";
            var infFile  = string.Format("{0}\\{1}", paString, "HidGuardian.inf");
            var exePath  = Path.Combine(folder, GetDevConPath());

            UacHelper.RunElevated(
                exePath,
                "install " + infFile + " " + HidGuardianHardwareId,
                style, true);
            UacHelper.RunElevated(
                exePath,
                "classfilter HIDClass upper -HidGuardian",
                style, true);
            // Fix registry permissions.
            var canModify = ViGEm.HidGuardianHelper.CanModifyParameters(true);

            // Fix missing white list key.
            if (canModify)
            {
                ViGEm.HidGuardianHelper.FixWhiteListRegistryKey();
            }
        }
Exemplo n.º 4
0
 private static void _AddToAutostart()
 {
     if (UacHelper.IsRunningAsAdmin())
     {
         ShortcutHelper.DeleteStartupShortcut();
     }
     else
     {
         ShortcutHelper.CreateStartupShortcut();
     }
 }
Exemplo n.º 5
0
        public App() : base()
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            this.DispatcherUnhandledException          += Current_DispatcherUnhandledException;

            LogHelper.Debug("Starting Console: " + Environment.CommandLine);
            CommonHelper.OverrideSettingsFile("WFN.config");

            if (Settings.Default.AlwaysRunAs && !UacHelper.CheckProcessElevated())
            {
                RestartAsAdmin();
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Must bve used to uninstall device when this app is 32-bit, but runs on 64-bit windows.
        /// This is because SetupDiCallClassInstaller throws ERROR_IN_WOW64 (ex.ErrorCode = 0xE0000235)
        /// when application architecture do not match OS architecture.
        /// </summary>
        /// <param name="deviceId">
        /// Device Hardware ID ("HID\VID_046D&PID_C219") or
        /// Device Instance ID prefixed with '@' (@"HID\VID_046D&PID_C219\7&29C26453&0&0000").
        /// </param>
        /// <remarks>Must be executed in administrative mode.</remarks>
        public static void UnInstallDevice(string deviceId, ProcessWindowStyle style = ProcessWindowStyle.Hidden)
        {
            // Extract files first.
            ExtractHidGuardianFiles(true);
            var folder  = GetHidGuardianPath();
            var exePath = Path.Combine(folder, GetDevConPath());

            UacHelper.RunElevated(
                exePath,
                "remove \"" + deviceId + "\"",
                style, true);
            // Make sure that device is re-inserted.
            DeviceDetector.ScanForHardwareChanges();
        }
Exemplo n.º 7
0
 public void UnpackSingleGzipWithFallbackAndRetry(IAbsoluteFilePath sourceFile, IAbsoluteFilePath destFile)
 {
     FileUtil.Ops.AddIORetryDialog(() => {
         try {
             UnpackSingleGzip(sourceFile, destFile);
         } catch (UnauthorizedAccessException) {
             if (!UacHelper.CheckUac())
             {
                 throw;
             }
             UnpackSingleZipWithUpdaters(sourceFile, destFile);
         }
     });
 }
Exemplo n.º 8
0
 public static int AcquireServer(string ipAddress)
 {
     // ToDo: Which result do you expect? You need a proper approval/confirmation handling!
     HubProxy.Invoke <bool>("ShutDownServer", ipAddress, Server.Port);
     if (UacHelper.IsElevated() == false)
     {
         if (UacHelper.RestartWithAdminRights("serverRole") == false)
         {
             return(0);
         }
         Process.GetCurrentProcess().Kill();
     }
     return(1);
 }
Exemplo n.º 9
0
        /// <summary>
        /// Uninstall HID Guardian.
        /// </summary>
        /// <remarks>Must be executed in administrative mode.</remarks>
        public static void UninstallHidGuardian(ProcessWindowStyle style = ProcessWindowStyle.Hidden)
        {
            // Extract files first.
            ExtractHidGuardianFiles(false);
            var folder  = GetHidGuardianPath();
            var exePath = Path.Combine(folder, GetDevConPath());

            UacHelper.RunElevated(
                exePath,
                "remove " + HidGuardianHardwareId,
                style, true);
            UacHelper.RunElevated(
                exePath,
                "classfilter HIDClass upper !HidGuardian",
                style, true);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Install Virtual driver.
        /// </summary>
        /// <remarks>Must be executed in administrative mode.</remarks>
        public static void InstallViGEmBus(ProcessWindowStyle style = ProcessWindowStyle.Hidden)
        {
            // Extract files first.
            ExtractViGemBusFiles(true);
            var folder   = GetViGEmBusPath();
            var exePath  = Path.Combine(folder, GetDevConPath());
            var osString = JocysCom.ClassLibrary.Controls.IssuesControl.IssueHelper.GetRealOSVersion().Major >= 10
                                ? "Win10" : "WinVS";
            var infFile = string.Format("{0}\\{1}", osString, "ViGEmBus.inf");

            UacHelper.RunElevated(
                exePath,
                // Use last ID.
                "install " + infFile + " " + ViGEmBusHardwareIds.Last(),
                style, true);
        }
Exemplo n.º 11
0
 public void DeleteWithUpdaterFallbackAndRetry(string source)
 {
     AddIORetryDialog(() => {
         try {
             DeleteIfExists(source);
         } catch (UnauthorizedAccessException ex) {
             this.Logger()
             .FormattedWarnException(ex,
                                     "Exception during delete, trying through updater if not elevated");
             if (!UacHelper.CheckUac())
             {
                 throw;
             }
             DeleteWithUpdater(source);
         }
     }, source);
 }
Exemplo n.º 12
0
                public void MoveDirectoryWithUpdaterFallbackAndRetry(IAbsoluteDirectoryPath source,
                                                                     IAbsoluteDirectoryPath destination)
                {
                    AddIORetryDialog(() => {
                        if (IsSameRoot(source, destination))
                        {
                            try {
                                var tmp = destination + GenericTools.TmpExtension;
                                Directory.Move(source.ToString(), tmp);
                                Directory.Move(tmp, destination.ToString());
                            } catch (UnauthorizedAccessException ex) {
                                this.Logger()
                                .FormattedWarnException(ex,
                                                        "Exception during move directory, trying through updater if not elevated");
                                if (!UacHelper.CheckUac())
                                {
                                    throw;
                                }
                                MoveDirectoryWithUpdater(source, destination);
                            }
                        }
                        else
                        {
                            var doneCopy = false;
                            try {
                                CopyDirectoryWithRetry(source, destination, true);
                                doneCopy = true;
                            } catch (UnauthorizedAccessException ex) {
                                this.Logger()
                                .FormattedWarnException(ex,
                                                        "Exception during move directory, trying through updater if not elevated");
                                if (!UacHelper.CheckUac())
                                {
                                    throw;
                                }
                                MoveDirectoryWithUpdater(source, destination);
                            }

                            if (doneCopy)
                            {
                                DeleteWithUpdaterFallbackAndRetry(source.ToString());
                            }
                        }
                    }, source.ToString(), destination.ToString());
                }
Exemplo n.º 13
0
 public void MoveWithUpdaterFallbackAndRetry(IAbsoluteFilePath source, IAbsoluteFilePath destination,
                                             bool overwrite = true, bool checkMd5 = false)
 {
     AddIORetryDialog(() => {
         try {
             Move(source, destination, overwrite, checkMd5);
         } catch (UnauthorizedAccessException ex) {
             this.Logger()
             .FormattedWarnException(ex,
                                     "Exception during move file, trying through updater if not elevated");
             if (!UacHelper.CheckUac())
             {
                 throw;
             }
             MoveWithUpdater(source, destination, overwrite);
         }
     }, source.ToString(), destination.ToString());
 }
Exemplo n.º 14
0
        private void ButtonUnRegister_Click(object sender, EventArgs e)
        {
            if (!UacHelper.IsRunAsAdmin())
            {
                MessageBox.Show("You need administrator rights to unregister a DLL!", "Administrator ?", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            labelResult.BorderStyle = BorderStyle.None;
            labelResult.BackColor   = this.BackColor;
            labelResult.Text        = string.Empty;
            fct_box.Text            = string.Empty;
            SetToViewRegFile();

            Logger.Instance.AdddLog(LogType.Debug, "Start to unregister DLLs!", this);
            GetUiInput();

            if (comboBoxNetLink.SelectedItem == null || string.IsNullOrWhiteSpace((comboBoxNetLink.SelectedItem as NetItem).FullPath) || !System.IO.File.Exists((comboBoxNetLink.SelectedItem as NetItem).FullPath))
            {
                Logger.Instance.AdddLog(LogType.Error, "Framework link ?", this);
                return;
            }
            if (Setting.FileItems == null || Setting.FileItems.Count == 0)
            {
                Logger.Instance.AdddLog(LogType.Error, "Missing DLL file link ?", this);
                return;
            }

            Cursor.Current          = Cursors.WaitCursor;
            labelResult.BorderStyle = BorderStyle.FixedSingle;
            if (DllRegister.UnRegister(Setting, timeId))
            {
                labelResult.Text      = "OK!";
                labelResult.BackColor = Color.ForestGreen;
            }

            else
            {
                labelResult.Text      = "ERROR";
                labelResult.BackColor = Color.Red;
            }

            Cursor.Current = Cursors.Default;
        }
Exemplo n.º 15
0
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            Log.Info($@"WinHue {Assembly.GetExecutingAssembly().GetName().Version} started");
            Log.Info($"User is running as administrator : {UacHelper.IsProcessElevated()}");

            MainForm.MainWindow wnd = new MainForm.MainWindow();

            double height = SystemParameters.WorkArea.Height * 0.75 >= MainWindow.MinHeight
                ? SystemParameters.WorkArea.Height * 0.75
                : MainWindow.MinHeight;

            double width = SystemParameters.WorkArea.Width * 0.75 >= MainWindow.MinWidth
                ? SystemParameters.WorkArea.Width * 0.75
                : MainWindow.MinWidth;

            MainWindow.Height = height;
            MainWindow.Width  = width;

            switch (WinHueSettings.settings.StartMode)
            {
            case 0:
                wnd.Show();
                wnd.WindowState = WindowState.Normal;
                break;

            case 1:
                wnd.Show();
                wnd.WindowState = WindowState.Minimized;
                break;

            case 2:
                wnd.Show();
                wnd.Hide();
                break;

            default:
                wnd.Show();
                wnd.WindowState = WindowState.Normal;
                break;
            }
        }
Exemplo n.º 16
0
 public void CopyDirectoryWithUpdaterFallbackAndRetry(IAbsoluteDirectoryPath sourceFolder,
                                                      IAbsoluteDirectoryPath outputFolder, bool overwrite = false)
 {
     AddIORetryDialog(() => {
         try {
             CopyDirectory(sourceFolder, outputFolder, overwrite);
         } catch (UnauthorizedAccessException ex) {
             this.Logger()
             .FormattedWarnException(ex,
                                     "Exception during copy directory, trying through updater if not elevated");
             if (!UacHelper.CheckUac())
             {
                 throw;
             }
             CopyDirectoryWithUpdater(sourceFolder, outputFolder, overwrite);
         } catch (IOException) {
             if (!UacHelper.CheckUac())
             {
                 throw;
             }
             CopyDirectoryWithUpdater(sourceFolder, outputFolder, overwrite);
         }
     }, sourceFolder.ToString(), outputFolder.ToString());
 }
Exemplo n.º 17
0
        private static void _AddToAutostart()
        {
            using (var adapter = new TaskSchedulerWrapper())
            {
                if (adapter.CheckExecPathIsCorrect())
                {
                    // There is nothing to do if a task is already created and the
                    // execution path is correct even if admin rights are not
                    // applied to the app at the moment.
                    return;
                }

                if (UacHelper.IsRunningAsAdmin())
                {
                    ShortcutHelper.DeleteStartupShortcut();
                    adapter.DeleteTaskIfNeeded();
                    adapter.CreateTask();
                }
                else
                {
                    ShortcutHelper.CreateStartupShortcut();
                }
            }
        }
            public DisconnectMessageBox()
            {
                this.reconnectButton.Text    = @"Erneut verbinden";
                this.getServerButton.Text    = @"Server werden";
                this.connectOtherButton.Text = @"Mit anderem Server verbinden";

                this.reconnectButton.Click += async(a, b) =>
                {
                    this.ChangeButtonIsEnabled(false);
                    var success = await CommunicationProxy.ConnectToServer(BsaContext.GetURL(), 8081);

                    if (success)
                    {
                        this.Close();
                    }

                    this.ChangeButtonIsEnabled(true);
                };

                this.getServerButton.Click += (a, b) =>
                {
                    this.ChangeButtonIsEnabled(false);
                    if (UacHelper.RestartWithAdminRights("") == false)
                    {
                        this.ChangeButtonIsEnabled(true);
                        return;
                    }

                    Process.GetCurrentProcess().Kill();
                };

                this.connectOtherButton.Click += async(a, b) =>
                {
                    this.ChangeButtonIsEnabled(false);
                    var success = await this.ConnectToServerAsync();

                    if (success == false)
                    {
                        this.ChangeButtonIsEnabled(true);
                    }
                    else
                    {
                        this.Close();
                    }
                };

                var l = new Label {
                    Text = @"Die Verbindung zum Server ist getrennt. Was möchten Sie jetzt tun?"
                };

                l.SetBounds(100, 30, 450, 50);
                this.reconnectButton.SetBounds(50, 100, 150, 50);
                this.getServerButton.SetBounds(250, 100, 150, 50);
                this.connectOtherButton.SetBounds(450, 100, 150, 50);

                this.connectOtherButton.Anchor = this.connectOtherButton.Anchor | AnchorStyles.Right;
                this.reconnectButton.Anchor    = AnchorStyles.Bottom | AnchorStyles.Right;
                this.getServerButton.Anchor    = AnchorStyles.Bottom | AnchorStyles.Right;
                this.Text       = @"Fehler";
                this.ClientSize = new Size(650, 200);
                this.Controls.AddRange(new Control[] { l, this.reconnectButton, this.getServerButton, this.connectOtherButton });
                this.FormBorderStyle = FormBorderStyle.FixedDialog;
                this.StartPosition   = FormStartPosition.CenterScreen;
                this.MinimizeBox     = false;
                this.MaximizeBox     = false;

                this.ShowDialog();
            }
Exemplo n.º 19
0
 public string GetCombinedStartupParameters() => UacHelper.GetStartupParameters().CombineParameters();
Exemplo n.º 20
0
        private void ButtonRegister_Click(object sender, EventArgs e)
        {
            if ((checkBoxInstallinGAC.Checked || !checkBoxRegistry.Checked) && !UacHelper.IsRunAsAdmin())
            {
                MessageBox.Show("You need administrator rights to register a DLL!", "Administrator ?", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }


            labelResult.BorderStyle = BorderStyle.None;
            labelResult.BackColor   = this.BackColor;
            labelResult.Text        = string.Empty;
            fct_box.Text            = string.Empty;
            SetToViewRegFile();

            Logger.Instance.AdddLog(LogType.Debug, "Start to register DLLs!", this);

            GetUiInput();

            #region project name
            //test project name --set to default?
            if (string.IsNullOrWhiteSpace(Setting.ProjectName) &&
                FileListcomboBox.SelectedItem != null &&
                !string.IsNullOrWhiteSpace((FileListcomboBox.SelectedItem as FileItem).FullPath))
            {
                textBoxPName.Text = "Register_" + System.IO.Path.GetFileNameWithoutExtension((FileListcomboBox.SelectedItem as FileItem).FullPath);
            }
            else
            {
                textBoxPName.Text = "Register_DLL";
            }
            Setting.ProjectName = textBoxPName.Text;
            #endregion

            #region Regasm.exe & file links ?
            if (Setting.FileItems == null || Setting.FileItems.Count == 0)
            {
                Logger.Instance.AdddLog(LogType.Error, "Missing DLL file link ?", this);
                MessageBox.Show("Please select DLL files (add button)!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (comboBoxNetLink.SelectedItem == null || string.IsNullOrWhiteSpace((comboBoxNetLink.SelectedItem as NetItem).FullPath) || !System.IO.File.Exists((comboBoxNetLink.SelectedItem as NetItem).FullPath))
            {
                Logger.Instance.AdddLog(LogType.Error, "Framework link ?", this);
                MessageBox.Show("Regasm.exe link is not set?", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            #endregion

            Cursor.Current = Cursors.WaitCursor;


            #region Register DLL
            if (DllRegister.Register(Setting, timeId))
            {
                labelResult.Text      = "OK!";
                labelResult.BackColor = Color.ForestGreen;
            }
            else
            {
                labelResult.Text      = "ERROR";
                labelResult.BackColor = Color.Red;
            }

            #endregion

            labelResult.BorderStyle = BorderStyle.FixedSingle;
            Cursor.Current          = Cursors.Default;
        }
Exemplo n.º 21
0
        public void ConfigureAndRun()
        {
            HostFactory.Run(
                config =>
            {
                NancyHost nancyHost = null;

                config.Service <ISchedulerManager>(
                    service =>
                {
                    service.ConstructUsing(settings => _schedulerManager);

                    service.WhenStarted(
                        (schedulerManager, hostControl) =>
                    {
                        schedulerManager.Start();

                        nancyHost = new NancyHost(
                            _nancySelfHostUri,
                            new Bootstrapper(new InteractiveModule(hostControl)));
                        nancyHost.Start();

                        return(true);
                    });

                    service.WhenStopped(
                        schedulerManager =>
                    {
                        schedulerManager.Stop();
                        nancyHost?.Stop();
                    });

                    service.AfterStoppingService(_ => nancyHost?.Dispose());
                });

                config.SetServiceName(_serviceName);
                config.SetDisplayName(_serviceDisplayName);

                config.RunAsNetworkService();
                config.StartAutomatically();

                config.UseLog4Net();
                config.EnableShutdown();

                config.AddCommandLineSwitch("squirrel", _ => { });
                config.AddCommandLineDefinition("firstrun", _ => Environment.Exit(0));
                config.AddCommandLineDefinition("updated", version =>
                {
                    // nancy self host
                    var url = new UriBuilder(_nancySelfHostUri)
                    {
                        Host = "+", Path = _serviceName
                    }.ToString();
                    UacHelper.RunElevated("netsh", $"http add urlacl url=\"{url}\" user=\"Everyone\"");

                    // topshelf
                    config.UseHostBuilder((env, settings) => new UpdateHostBuilder(env, settings, version));
                });
                config.AddCommandLineDefinition("obsolete", _ => Environment.Exit(0));
                config.AddCommandLineDefinition("install", _ => Environment.Exit(0));
                config.AddCommandLineDefinition("uninstall", _ =>
                {
                    // nancy self host
                    var url = new UriBuilder(_nancySelfHostUri)
                    {
                        Host = "+", Path = _serviceName
                    }.ToString();
                    UacHelper.RunElevated("netsh", $"http delete urlacl url=\"{url}\"");

                    // topshelf
                    config.UseHostBuilder((env, settings) => new StopAndUninstallHostBuilder(env, settings));
                });
            });
        }
Exemplo n.º 22
0
        private void GetInfo()
        {
            string message = string.Empty;

            // Get and display whether the primary access token of the process belongs
            // to user account that is a member of the local Administrators group even
            // if it currently is not elevated (IsUserInAdminGroup).
            try
            {
                message += "Is user in admin group:" + UacHelper.IsUserInAdminGroup().ToString();
            }
            catch
            {
                message += "Is user in admin group:N/A";
            }

            // Get and display whether the process is run as administrator or not
            // (IsRunAsAdmin).
            try
            {
                message += " |Run as admin:" + UacHelper.IsRunAsAdmin().ToString();
            }
            catch
            {
                message += " |Run as admin:N/A";
            }


            // Get and display the process elevation information (IsProcessElevated)
            // and integrity level (GetProcessIntegrityLevel). The information is not
            // available on operating systems prior to Windows Vista.
            if (Environment.OSVersion.Version.Major >= 6)
            {
                // Running Windows Vista or later (major version >= 6).

                try
                {
                    message += " |Is process elevated:" + UacHelper.IsProcessElevated().ToString();
                }
                catch
                {
                    message += " |Is process elevated:N/A";
                }

                try
                {
                    // Get and display the process integrity level.
                    int IL = UacHelper.GetProcessIntegrityLevel();
                    message += " |Integrity level:";

                    switch (IL)
                    {
                    case NativeMethods.SECURITY_MANDATORY_UNTRUSTED_RID:
                        message += "Untrusted"; break;

                    case NativeMethods.SECURITY_MANDATORY_LOW_RID:
                        message += "Low"; break;

                    case NativeMethods.SECURITY_MANDATORY_MEDIUM_RID:
                        message += "Medium"; break;

                    case NativeMethods.SECURITY_MANDATORY_HIGH_RID:
                        message += "High"; break;

                    case NativeMethods.SECURITY_MANDATORY_SYSTEM_RID:
                        message += "System"; break;

                    default:
                        message += "Unknown"; break;
                    }
                }
                catch
                {
                    message += "|Integrity level:N/A";
                }
            }
            else
            {
                message += " |Is process elevated:N/A |Integrity level:N/A";
            }
            Logger.Instance.AdddLog(LogType.Warn, message, this);
        }