private void StartSubProcessAsAdmin(AutoStartEntry autoStart, string parameterName)
        {
            Logger.Trace("StartSubProcessAsAdmin called");
            string path = Path.GetTempFileName();

            try {
                using (Stream stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None)) {
                    IFormatter formatter = new BinaryFormatter();
                    formatter.Serialize(stream, autoStart);
                }

                var info = new ProcessStartInfo(
                    AutoStartService.CurrentExePath,
                    $"{parameterName} {path}")
                {
                    Verb = "runas", // indicates to elevate privileges
                };

                var process = new Process {
                    EnableRaisingEvents = true, // enable WaitForExit()
                    StartInfo           = info
                };

                process.Start();
                process.WaitForExit();
                if (process.ExitCode != 0)
                {
                    throw new Exception("Sub process failed to execute");
                }
            } finally {
                File.Delete(path);
            }
        }
 public void Disable(AutoStartEntry autoStart)
 {
     Task.Run(() => {
         Logger.Info("Should disable {@autoStart}", autoStart);
         try {
             AppStatus.IncrementRunningActionCount();
             if (!MessageService.ShowConfirm("Confirm disable", $"Are you sure you want to disable auto start \"{autoStart.Value}\"?"))
             {
                 return;
             }
             if (AutoStartService.IsAdminRequiredForChanges(autoStart))
             {
                 StartSubProcessAsAdmin(autoStart, DisableParameterName);
                 autoStart.ConfirmStatus = ConfirmStatus.Disabled;
             }
             else
             {
                 AutoStartService.DisableAutoStart(autoStart);
             }
             MessageService.ShowSuccess("Auto start disabled", $"\"{autoStart.Value}\" has been disabled.");
         } catch (Exception e) {
             var message = "Failed to disable";
             var err     = new Exception(message, e);
             Logger.Error(err);
             MessageService.ShowError(message, e);
         } finally {
             AppStatus.DecrementRunningActionCount();
         }
     });
 }
 public void RevertRemove(AutoStartEntry autoStart)
 {
     Task.Run(() => {
         Logger.Info("Should remove {@autoStart}", autoStart);
         try {
             AppStatus.IncrementRunningActionCount();
             if (!MessageService.ShowConfirm("Confirm add", $"Are you sure you want to add \"{autoStart.Value}\" as auto start?"))
             {
                 return;
             }
             if (AutoStartService.IsAdminRequiredForChanges(autoStart))
             {
                 StartSubProcessAsAdmin(autoStart, RevertRemoveParameterName);
                 autoStart.ConfirmStatus = ConfirmStatus.Reverted;
             }
             else
             {
                 AutoStartService.AddAutoStart(autoStart);
             }
             MessageService.ShowSuccess("Auto start added", $"\"{autoStart.Value}\" has been added to auto starts.");
         } catch (Exception e) {
             var message = "Failed to revert remove";
             var err     = new Exception(message, e);
             Logger.Error(err);
             MessageService.ShowError(message, e);
         } finally {
             AppStatus.DecrementRunningActionCount();
         }
     });
 }
 public void RemoveAutoStart(AutoStartEntry autoStartEntry, bool dryRun = false)
 {
     Logger.Trace("RemoveAutoStart called for {AutoStartEntry} (dryRun: {DryRun})", autoStartEntry, dryRun);
     if (autoStartEntry == null)
     {
         throw new ArgumentNullException("AutoStartEntry is required");
     }
     if (autoStartEntry is FolderAutoStartEntry folderAutoStartEntry)
     {
         string fullPath = $"{folderAutoStartEntry.Path}{Path.DirectorySeparatorChar}{folderAutoStartEntry.Value}";
         if (File.Exists(fullPath))
         {
             if (dryRun)
             {
                 return;
             }
             File.Delete(fullPath);
             Logger.Info("Removed {Value} from {Path}", folderAutoStartEntry.Value, folderAutoStartEntry.Path);
         }
         else
         {
             throw new FileNotFoundException($"File \"{fullPath}\" not found");
         }
     }
     else
     {
         throw new ArgumentException("AutoStartEntry is not of type folderAutoStartEntry");
     }
 }
Exemple #5
0
        private void ToggleEnable(AutoStartEntry autoStart, bool enable)
        {
            var task = TaskService.Instance.GetTask(autoStart.Path);

            if (task == null)
            {
                throw new InvalidOperationException($"Task {autoStart.Path} not found");
            }
            if (task.Enabled == enable)
            {
                return;
            }
            task.Enabled = enable;
            var currentAutoStart = GetAutoStartEntry(task);

            LastAutoStartEntries.AddOrUpdate(
                autoStart.Path,
                (key) => {
                return(currentAutoStart);
            },
                (key, oldValue) => {
                return(currentAutoStart);
            }
                );
            if (enable)
            {
                EnableHandler(currentAutoStart);
            }
            else
            {
                DisableHandler(currentAutoStart);
            }
        }
Exemple #6
0
 public void RemoveAutoStart(AutoStartEntry autoStartEntry, bool dryRun = false)
 {
     Logger.Trace("RemoveAutoStart called for {AutoStartEntry} (dryRun: {DryRun})", autoStartEntry, dryRun);
     if (autoStartEntry == null)
     {
         throw new ArgumentNullException("AutoStartEntry is required");
     }
     if (autoStartEntry is ScheduledTaskAutoStartEntry ScheduledTaskAutoStartEntry)
     {
         var task = TaskService.Instance.GetTask(autoStartEntry.Path);
         if (task != null)
         {
             if (dryRun)
             {
                 return;
             }
             task.Folder.DeleteTask(task.Name);
             Logger.Info("Removed {Value} from {Path}", ScheduledTaskAutoStartEntry.Value, ScheduledTaskAutoStartEntry.Path);
             bool removed = lastAutoStartEntries.TryRemove(ScheduledTaskAutoStartEntry.Path, out AutoStartEntry removedAutoStart);
             if (removed)
             {
                 RemoveHandler(removedAutoStart);
             }
         }
         else
         {
             throw new ArgumentException("Task not found");
         }
     }
     else
     {
         throw new ArgumentException("AutoStartEntry is not of type ScheduledTaskAutoStartEntry");
     }
 }
 public bool IsEnabled(AutoStartEntry autoStart)
 {
     if (RegistryDisableService == null)
     {
         return(true);
     }
     return(RegistryDisableService.CanBeDisabled(autoStart));
 }
 public void DisableAutoStart(AutoStartEntry autoStart)
 {
     if (RegistryDisableService == null)
     {
         throw new NotImplementedException();
     }
     RegistryDisableService.DisableAutoStart(autoStart);
 }
 public bool CanBeDisabled(AutoStartEntry autoStart)
 {
     try {
         DisableAutoStart(autoStart, true);
         return(true);
     } catch (Exception) {
         return(false);
     }
 }
 public bool CanBeRemoved(AutoStartEntry autoStart)
 {
     Logger.Trace("CanBeRemoved called for {Value} in {Path}", autoStart.Value, autoStart.Path);
     try {
         RemoveAutoStart(autoStart, true);
     } catch (Exception) {
         return(false);
     }
     return(true);
 }
 public bool CanBeRemoved(AutoStartEntry autoStart)
 {
     Logger.Trace("CanBeRemoved called for {AutoStartEntry}", autoStart);
     try {
         RemoveAutoStart(autoStart, true);
         return(true);
     } catch (Exception) {
         return(false);
     }
 }
Exemple #12
0
        public bool IsEnabled(AutoStartEntry autoStart)
        {
            var task = TaskService.Instance.GetTask(autoStart.Path);

            if (task == null)
            {
                return(false);
            }
            return(task.Enabled);
        }
 private void RemoveHandler(AutoStartEntry removedAutostart)
 {
     Logger.Trace("RemoveHandler called");
     if (AutoStartService.IsOwnAutoStart(removedAutostart))
     {
         Logger.Info("Own auto start removed");
         AppStatus.HasOwnAutoStart = false;
     }
     NotificationService.ShowRemovedAutoStartEntryNotification(removedAutostart);
 }
 private void AddHandler(AutoStartEntry addedAutostart)
 {
     Logger.Trace("AddHandler called");
     if (AutoStartService.IsOwnAutoStart(addedAutostart))
     {
         Logger.Info("Own auto start added");
         AppStatus.HasOwnAutoStart = true;
     }
     NotificationService.ShowNewAutoStartEntryNotification(addedAutostart);
 }
        protected ServiceController GetServiceController(AutoStartEntry autoStart)
        {
            var serviceControllers = GetServiceControllers();

            foreach (var sc in serviceControllers)
            {
                if (autoStart.Path == sc.ServiceName)
                {
                    return(sc);
                }
            }
            throw new KeyNotFoundException($"{autoStart.Path} not found");
        }
 public bool IsEnabled(AutoStartEntry autoStart)
 {
     if (!(autoStart is ServiceAutoStartEntry))
     {
         throw new ArgumentException("AutoStartEntry has invalid type");
     }
     try {
         var sc = GetServiceController(autoStart);
         return(IsEnabled(sc));
     } catch (Exception) {
         return(false);
     }
 }
 public void ConfirmRemove(AutoStartEntry autoStart)
 {
     Task.Run(() => {
         try {
             AppStatus.IncrementRunningActionCount();
             Logger.Trace("ConfirmRemove called");
             AutoStartService.ConfirmRemove(autoStart);
         } catch (Exception e) {
             var message = $"Failed to confirm remove of {autoStart}";
             var err     = new Exception(message, e);
             Logger.Error(err);
             MessageService.ShowError(message, e);
         } finally {
             AppStatus.DecrementRunningActionCount();
         }
     });
 }
 public void DisableAutoStart(AutoStartEntry autoStart)
 {
     Logger.Trace("DisableAutoStart called for AutoStartEntry {AutoStartEntry}", autoStart);
     if (!(autoStart is ServiceAutoStartEntry))
     {
         throw new ArgumentException("AutoStartEntry must be of type ServiceAutoStartEntry");
     }
     // https://stackoverflow.com/a/35063366
     // https://docs.microsoft.com/en-us/windows/win32/cimwin32prov/changestartmode-method-in-class-win32-service?redirectedfrom=MSDN
     using (var m = new ManagementObject(string.Format("Win32_Service.Name=\"{0}\"", autoStart.Path))) {
         uint returnCode = (uint)m.InvokeMethod("ChangeStartMode", new object[] { "Disabled" });
         if (returnCode != 0)
         {
             throw new Exception($"Failed to disable auto start (return code: {returnCode})");
         }
     }
 }
        public void EnableAutoStart(AutoStartEntry autoStart)
        {
            Logger.Trace("EnableAutoStart called for AutoStartEntry {AutoStartEntry}", autoStart);
            if (!(autoStart is ServiceAutoStartEntry))
            {
                throw new ArgumentException("AutoStartEntry must be of type ServiceAutoStartEntry");
            }
            var serviceAutoStart = (ServiceAutoStartEntry)autoStart;
            var targetMode       = serviceAutoStart.EnabledStartMode.Value.ToString();

            using (var m = new ManagementObject(string.Format("Win32_Service.Name=\"{0}\"", autoStart.Path))) {
                uint returnCode = (uint)m.InvokeMethod("ChangeStartMode", new object[] { targetMode });
                if (returnCode != 0)
                {
                    throw new Exception($"Failed to disable auto start (Return code: {returnCode})");
                }
            }
        }
 public void ShowDisabledAutoStartEntryNotification(AutoStartEntry autostart)
 {
     try {
         Logger.Trace("ShowDisabledAutoStartEntryNotification called for {@autostart}", autostart);
         new ToastContentBuilder()
         .AddArgument("action", "viewAdd")
         .AddArgument("id", autostart.Id.ToString())
         .AddAppLogoOverride(new Uri($"{assetDirectoryPath}RemoveIcon.png"), ToastGenericAppLogoCrop.None)
         .AddText("Autostart disabled", AdaptiveTextStyle.Title)
         .AddText(autostart.Value)
         .AddAttributionText($"Via {autostart.Category}")
         .AddButton("Ok", ToastActivationType.Background, new ToastArguments().Add("action", "confirmDisable").Add("id", autostart.Id.ToString()).ToString())
         .AddButton("Enable", ToastActivationType.Background, new ToastArguments().Add("action", "enable").Add("id", autostart.Id.ToString()).ToString())
         .AddButton("Remove", ToastActivationType.Background, new ToastArguments().Add("action", "revertRemove").Add("id", autostart.Id.ToString()).ToString())
         .Show();
         Logger.Trace("ShowDisabledAutoStartEntryNotification finished");
     } catch (Exception e) {
         var err = new Exception("Failed to show disabled auto start notification", e);
         Logger.Error(err);
     }
 }
 /// <summary>
 /// Handles auto starts if command line parameters are set
 /// </summary>
 /// <param name="args">Command line parameters</param>
 /// <returns>True, if parameters were set, correctly handled and the program can be closed</returns>
 private bool HandleCommandLineParameters(string[] args)
 {
     for (int i = 0; i < args.Length; i++)
     {
         var arg = args[i];
         if (string.Equals(arg, RevertAddParameterName, StringComparison.OrdinalIgnoreCase))
         {
             Logger.Info("Adding should be reverted");
             AutoStartEntry autoStartEntry = LoadAutoStartFromParameter(args, i);
             AutoStartService.RemoveAutoStart(autoStartEntry);
             Logger.Info("Finished");
             return(true);
         }
         else if (string.Equals(arg, RevertRemoveParameterName, StringComparison.OrdinalIgnoreCase))
         {
             Logger.Info("Removing should be reverted");
             AutoStartEntry autoStartEntry = LoadAutoStartFromParameter(args, i);
             AutoStartService.AddAutoStart(autoStartEntry);
             Logger.Info("Finished");
             return(true);
         }
         else if (string.Equals(arg, EnableParameterName, StringComparison.OrdinalIgnoreCase))
         {
             Logger.Info("Auto start should be enabled");
             AutoStartEntry autoStartEntry = LoadAutoStartFromParameter(args, i);
             AutoStartService.EnableAutoStart(autoStartEntry);
             Logger.Info("Finished");
             return(true);
         }
         else if (string.Equals(arg, DisableParameterName, StringComparison.OrdinalIgnoreCase))
         {
             Logger.Info("Auto start should be disabled");
             AutoStartEntry autoStartEntry = LoadAutoStartFromParameter(args, i);
             AutoStartService.DisableAutoStart(autoStartEntry);
             Logger.Info("Finished");
             return(true);
         }
     }
     return(false);
 }
 private void RemoveHandler(AutoStartEntry e)
 {
     Logger.Trace("RemoveHandler called");
     Remove?.Invoke(e);
 }
 public bool CanBeDisabled(AutoStartEntry autoStart)
 {
     return(IsEnabled(autoStart));
 }
 public void RemoveAutoStart(AutoStartEntry autoStart)
 {
     Logger.Trace("RemoveAutoStart called for AutoStartEntry {AutoStartEntry}", autoStart);
     throw new NotImplementedException();
 }
 public void Open(AutoStartEntry autoStart)
 {
     Logger.Trace("Open called for AutoStartEntry {AutoStartEntry}", autoStart);
     throw new NotImplementedException();
 }
 private void DisableHandler(AutoStartEntry e)
 {
     Logger.Trace("DisableHandler called");
     Disable?.Invoke(e);
 }
 private void EnableHandler(AutoStartEntry enabledAutostart)
 {
     Logger.Trace("EnableHandler called");
     NotificationService.ShowEnabledAutoStartEntryNotification(enabledAutostart);
 }
 public bool IsAdminRequiredForChanges(AutoStartEntry autoStart)
 {
     return(true);
 }
 private void DisableHandler(AutoStartEntry disabledAutostart)
 {
     Logger.Trace("DisableHandler called");
     NotificationService.ShowDisabledAutoStartEntryNotification(disabledAutostart);
 }
 private void AddHandler(AutoStartEntry e)
 {
     Logger.Trace("AddHandler called");
     Add?.Invoke(e);
 }