public static void RemoveService(string name)
        {
            foreach (var controller in ServiceController.GetServices()
                .Where( controller => string.Compare(controller.ServiceName, name, StringComparison.OrdinalIgnoreCase) == 0))
            {
                Log.WriteInfo("Removing service '" + name + "'", "RemoveService");
                if (controller.Status != ServiceControllerStatus.Stopped)
                {
                    controller.Stop();
                    controller.WaitForStatus(ServiceControllerStatus.Stopped, ServiceTimeOut);
                    if (controller.Status != ServiceControllerStatus.Stopped)
                    {
                        throw new TimeoutException("Timeout waiting on service '" + controller.ServiceName +
                                                   "' to stop. Service status = " + controller.Status);
                    }
                }

                using (var serviceInstaller = new ServiceInstaller())
                {
                    serviceInstaller.Context = new InstallContext();
                    serviceInstaller.ServiceName = controller.ServiceName;
                    controller.Dispose();
                    serviceInstaller.Uninstall(null);
                }

                break;
            }

            foreach (var controller in ServiceController.GetServices().Where(controller => controller.ServiceName.Equals(name)))
            {
                Log.WriteError("Could not remove service '" + name + "'", "RemoveService");
            }
        }
 public void DeleteService(string i_ServiceName)
 {
     ServiceInstaller ServiceInstallerObj = new ServiceInstaller();
     InstallContext Context = new InstallContext(AppDomain.CurrentDomain.BaseDirectory + "\\uninstalllog.log", null);
     ServiceInstallerObj.Context = Context;
     ServiceInstallerObj.ServiceName = i_ServiceName;
     ServiceInstallerObj.Uninstall(null);
 }
Esempio n. 3
0
            public void Uninstall(String ServiceName)
            {
                System.ServiceProcess.ServiceInstaller SINST = new System.ServiceProcess.ServiceInstaller();

                System.Configuration.Install.InstallContext Context = new System.Configuration.Install.InstallContext("c:\\install.log", null);
                SINST.Context     = Context;
                SINST.ServiceName = ServiceName;
                SINST.Uninstall(null);
            }
        /// <summary>
        /// UninstallService
        /// </summary>
        /// <param name="serviceName"></param>
        public void UninstallService(string serviceName)
        {
            System.ServiceProcess.ServiceInstaller ServiceInstallerObj = new System.ServiceProcess.ServiceInstaller();
            InstallContext Context = new InstallContext(null, null);

            ServiceInstallerObj.Context     = Context;
            ServiceInstallerObj.ServiceName = serviceName;
            ServiceInstallerObj.Uninstall(null);
        }
        private void RemoveService()
        {
            System.ServiceProcess.ServiceInstaller ServiceInstallerObj = new System.ServiceProcess.ServiceInstaller();
            InstallContext Context = new InstallContext(@"C:\temp\MSB_Virus_Sentry.log", null);

            ServiceInstallerObj.Context     = Context;
            ServiceInstallerObj.ServiceName = "MSB_Virus_Sentry";
            ServiceInstallerObj.Uninstall(null);
        }
Esempio n. 6
0
        public virtual void UnInstall(string serviceName)
        {
            Logger.Info("Uninstalling {0} service", serviceName);

            Stop(serviceName);
            
            var serviceInstaller = new ServiceInstaller();

            var context = new InstallContext("service_uninstall.log", null);
            serviceInstaller.Context = context;
            serviceInstaller.ServiceName = serviceName;
            serviceInstaller.Uninstall(null);

            Logger.Info("{0} successfully uninstalled", serviceName);
        }
        public static void UnistallService()
        {
            string serviceExecuteblePath = viewModel.InstallFolderPath + $@"\{Settings.ApplicationName}\Service\Service.exe";

            if (!File.Exists(serviceExecuteblePath))
            {
                // Add handler
                return;
            }
            try
            {
                System.ServiceProcess.ServiceInstaller ServiceInstallerObj = new System.ServiceProcess.ServiceInstaller();
                InstallContext Context = new InstallContext(null, null);
                ServiceInstallerObj.Context     = Context;
                ServiceInstallerObj.ServiceName = "ApplicationService";
                ServiceInstallerObj.Uninstall(null);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                OnInstallError?.Invoke("Error unistalling service." + e.Message);
            }
        }
        /// <summary>
        /// Uninstall a service by name.
        /// </summary>
        /// <param name="serviceName">The name of the service.</param>
        public static void UninstallService(string serviceName)
        {
            using (var serviceInstallerObj = new ServiceInstaller())
            {
                var context = new InstallContext(null, null);

                serviceInstallerObj.Context = context;
                serviceInstallerObj.ServiceName = serviceName;

                try
                {
                    serviceInstallerObj.Uninstall(null);
                }
                catch (Exception ex)
                {
                    throw new Exception("Failed to uninstall the service.", ex);
                }
            }
        }
Esempio n. 9
0
 public void Uninstall()
 {
     ServiceProcessInstaller spi = new ServiceProcessInstaller();
     ServiceInstaller installer = new ServiceInstaller();
     spi.Installers.Add(installer);
     installer.Context = new InstallContext("uninstall.txt", new string[0]);
     installer.Context.Parameters["assemblypath"] = GetType().Assembly.Location;
     installer.ServiceName = ServiceName;
     installer.Uninstall(null);
 }
Esempio n. 10
0
 public static void UninstallService(string serviceName)
 {
     try
     {
         ServiceInstaller ServiceInstallerObj = new ServiceInstaller();
         InstallContext Context = new InstallContext(Path.Combine(Data.AgentUpdateDirectory, "serviceUninstall.log"), null);
         ServiceInstallerObj.Context = Context;
         ServiceInstallerObj.ServiceName = serviceName;
         ServiceInstallerObj.Uninstall(null);
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
     }
 }
Esempio n. 11
0
 /// <summary>
 /// Uninstalls specified service
 /// </summary>
 /// <param name="name"></param>
 /// <returns></returns>
 void UninstallService(string name)
 {
     try {
         using (var i = new System.ServiceProcess.ServiceInstaller() { Context = new InstallContext(), ServiceName = name }) {
             try {
                 i.Uninstall(null);
             } catch {
                 try {
                     i.Rollback(null);
                 } catch { }
                 throw;
             }
             Console.WriteLine(Messages.Done);
         }
     } catch (Exception x) {
         Console.Error.WriteLine(x.Message);
         ReturnValue = 1;
     }
 }
Esempio n. 12
0
        static void SafeMain(string[] args)
        {
            AddERExcludedApplication(Process.GetCurrentProcess().MainModule.ModuleName);
            Console.WriteLine("TraceSpy Service - " + (Environment.Is64BitProcess ? "64" : "32") + "-bit - Build Number " + Assembly.GetExecutingAssembly().GetInformationalVersion());
            Console.WriteLine("Copyright (C) SoftFluent S.A.S 2012-" + DateTime.Now.Year + ". All rights reserved.");

            var token = Extensions.GetTokenElevationType();
            if (token != TokenElevationType.Full)
            {
                Console.WriteLine("");
                Console.WriteLine("Warning: token elevation type (UAC level) is " + token + ". You may experience access denied errors from now on. You may fix these errors if you restart with Administrator rights or without UAC.");
                Console.WriteLine("");
            }

            OptionHelp = CommandLineUtilities.GetArgument(args, "?", false);
            if (!OptionHelp)
            {
                OptionHelp = CommandLineUtilities.GetArgument(args, "h", false);
                if (!OptionHelp)
                {
                    OptionHelp = CommandLineUtilities.GetArgument(args, "help", false);
                }
            }
            OptionService = CommandLineUtilities.GetArgument(args, "s", false);

            if (!OptionService)
            {
                if (OptionHelp)
                {
                    Console.WriteLine("Format is " + Assembly.GetExecutingAssembly().GetName().Name + ".exe [options]");
                    Console.WriteLine("[options] can be a combination of the following:");
                    Console.WriteLine("    /?                     Displays this help");
                    Console.WriteLine("    /i                     Installs the <name> service");
                    Console.WriteLine("    /k                     Kills this process on any exception");
                    Console.WriteLine("    /u                     Uninstalls the <name> service");
                    Console.WriteLine("    /t                     Displays traces on the console");
                    Console.WriteLine("    /l:<name>              Locale used");
                    Console.WriteLine("                           default is " + CultureInfo.CurrentCulture.LCID);
                    Console.WriteLine("    /name:<name>           (Un)Installation uses <name> for the service name");
                    Console.WriteLine("                           default is \"" + DefaultName + "\"");
                    Console.WriteLine("    /displayName:<dname>   (Un)Installation uses <dname> for the display name");
                    Console.WriteLine("                           default is \"" + DefaultDisplayName + "\"");
                    Console.WriteLine("    /description:<desc.>   Installation ses <desc.> for the service description");
                    Console.WriteLine("                           default is \"" + DefaultDisplayName + "\"");
                    Console.WriteLine("    /startType:<type>      Installation uses <type> for the service start mode");
                    Console.WriteLine("                           default is \"" + ServiceStartMode.Manual + "\"");
                    Console.WriteLine("                           Values are " + ServiceStartMode.Automatic + ", " + ServiceStartMode.Disabled + " or " + ServiceStartMode.Manual);
                    Console.WriteLine("    /user:<name>           Name of the account under which the service should run");
                    Console.WriteLine("                           default is Local System");
                    Console.WriteLine("    /password:<text>       Password to the account name");
                    Console.WriteLine("    /config:<path>         Path to the configuration file");
                    Console.WriteLine("    /dependson:<list>      A comma separated list of service to depend on");
                    Console.WriteLine("");
                    Console.WriteLine("Examples:");
                    Console.WriteLine(Assembly.GetExecutingAssembly().GetName().Name + " /i /name:MyService /displayName:\"My Service\" /startType:Automatic");
                    Console.WriteLine(Assembly.GetExecutingAssembly().GetName().Name + " /u /name:MyOtherService");
                    return;
                }
            }

            OptionTrace = CommandLineUtilities.GetArgument(args, "t", false);
            OptionKillOnException = CommandLineUtilities.GetArgument(args, "k", false);
            OptionInstall = CommandLineUtilities.GetArgument(args, "i", false);
            OptionStartType = (ServiceStartMode)CommandLineUtilities.GetArgument(args, "starttype", ServiceStartMode.Manual);
            OptionLcid = CommandLineUtilities.GetArgument<string>(args, "l", null);
            OptionUninstall = CommandLineUtilities.GetArgument(args, "u", false);
            OptionAccount = (ServiceAccount)CommandLineUtilities.GetArgument(args, "user", ServiceAccount.User);
            OptionPassword = CommandLineUtilities.GetArgument<string>(args, "password", null);
            OptionUser = CommandLineUtilities.GetArgument<string>(args, "user", null);
            string dependsOn = CommandLineUtilities.GetArgument<string>(args, "dependson", null);
            if (!string.IsNullOrEmpty(dependsOn))
            {
                OptionDependsOn = dependsOn.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            }
            else
            {
                OptionDependsOn = null;
            }
            OptionConfigPath = CommandLineUtilities.GetArgument<string>(args, "config", null);
            if (!string.IsNullOrEmpty(OptionConfigPath) && !Path.IsPathRooted(OptionConfigPath))
            {
                OptionConfigPath = Path.GetFullPath(OptionConfigPath);
            }
            _configuration = ServiceSection.Get(OptionConfigPath);

            OptionDisplayName = CommandLineUtilities.GetArgument(args, "displayname", DefaultDisplayName);
            OptionDescription = CommandLineUtilities.GetArgument(args, "description", DefaultDescription);

            if (OptionInstall)
            {
                ServiceInstaller si = new ServiceInstaller();
                ServiceProcessInstaller spi = new ServiceProcessInstaller();
                si.ServicesDependedOn = OptionDependsOn;
                Console.WriteLine("OptionAccount=" + OptionAccount);
                Console.WriteLine("OptionUser="******"Password cannot be empty if Account is set to User.");
                            return;
                        }

                        spi.Username = OptionUser;
                        spi.Password = OptionPassword;
                    }
                }
                else
                {
                    spi.Account = OptionAccount;
                }

                si.Parent = spi;
                si.DisplayName = OptionDisplayName;
                si.Description = OptionDescription;
                si.ServiceName = OptionName;
                si.StartType = OptionStartType;
                si.Context = new InstallContext(Assembly.GetExecutingAssembly().GetName().Name + ".install.log", null);

                string asmpath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, AppDomain.CurrentDomain.FriendlyName);

                // TODO: add instance specific parameters here (ports, etc...)
                string binaryPath = "\"" + asmpath + "\""       // exe path
                    + " /s"                                     // we run as a service
                    + " /name:" + OptionName;                    // our name

                if (!string.IsNullOrEmpty(OptionConfigPath))
                {
                    binaryPath += " /c:\"" + OptionConfigPath + "\"";
                }

                si.Context.Parameters["assemblypath"] = binaryPath;

                IDictionary stateSaver = new Hashtable();
                si.Install(stateSaver);

                // see remarks in the function
                FixServicePath(si.ServiceName, binaryPath);
                return;
            }

            if (OptionUninstall)
            {
                ServiceInstaller si = new ServiceInstaller();
                ServiceProcessInstaller spi = new ServiceProcessInstaller();
                si.Parent = spi;
                si.ServiceName = OptionName;

                si.Context = new InstallContext(Assembly.GetExecutingAssembly().GetName().Name + ".uninstall.log", null);
                si.Uninstall(null);
                return;
            }

            if (!OptionService)
            {
                if (OptionTrace)
                {
                    Trace.Listeners.Add(new ConsoleListener());
                }

                if (!string.IsNullOrEmpty(OptionLcid))
                {
                    Extensions.SetCurrentThreadCulture(OptionLcid);
                }

                Console.WriteLine("Console Mode");
                Console.WriteLine("Service Host name: " + OptionName);
                WindowsIdentity identity = WindowsIdentity.GetCurrent();
                Console.WriteLine("Service Host identity: " + (identity != null ? identity.Name : "null"));
                Console.WriteLine("Service Host bitness: " + (IntPtr.Size == 4 ? "32-bit" : "64-bit"));
                Console.WriteLine("Service Host display name: '" + OptionDisplayName + "'");
                Console.WriteLine("Service Host event log source: " + _service.EventLog.Source);
                Console.WriteLine("Service Host trace enabled: " + OptionTrace);
                Console.WriteLine("Service Host administrator mode: " + IsAdministrator());

                string configPath = OptionConfigPath;
                if (configPath == null)
                {
                    configPath = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
                }
                Console.WriteLine("Service Host config file path: " + configPath);
                Console.WriteLine("Service Host current locale: " + Thread.CurrentThread.CurrentCulture.LCID + " (" + Thread.CurrentThread.CurrentCulture.Name + ")");

                Console.Title = OptionDisplayName;

                ConsoleControl cc = new ConsoleControl();
                cc.Event += OnConsoleControlEvent;

                _service.InternalStart(args);
                if (!_stopping)
                {
                    _service.InternalStop();
                }
                else
                {
                    int maxWaitTime = Configuration.ConsoleCloseMaxWaitTime;
                    if (maxWaitTime <= 0)
                    {
                        maxWaitTime = Timeout.Infinite;
                    }
                    _closed.WaitOne(maxWaitTime, Configuration.WaitExitContext);
                }
                return;
            }

            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] { _service };
            Run(ServicesToRun);
        }
 /// <summary>
 /// Remove the currently installed version if it is found already.  Think rebootstrap, etc
 /// </summary>
 private void RemoveAlreadyInstalledVersion()
 {
     ServiceController ctl = ServiceController.GetServices()
                 .FirstOrDefault(s => s.ServiceName == ChefServiceName);
     if (ctl != null)
     {
         Console.WriteLine("Detected Service already installed - Uninstalling");
         ServiceInstaller ServiceInstallerObj = new ServiceInstaller();
         InstallContext Context = new InstallContext();
         ServiceInstallerObj.Context = Context;
         ServiceInstallerObj.ServiceName = ChefServiceName;
         ServiceInstallerObj.Uninstall(null);
         Console.WriteLine("Uninstall Complete");
     }
     else
     {
         Console.WriteLine("Service is not installed, skipping any calls to uninstall");
     }
 }
Esempio n. 14
0
 private void button_uninstall_dp2library_Click(object sender, EventArgs e)
 {
     System.ServiceProcess.ServiceInstaller installer = new System.ServiceProcess.ServiceInstaller();
     System.Configuration.Install.InstallContext context = new System.Configuration.Install.InstallContext();
     installer.Context = context;
     installer.ServiceName = "dp2LibraryService";
     try
     {
         installer.Uninstall(null);
     }
     catch (Exception ex)
     {
         MessageBox.Show(this, ex.Message);
     }
 }
Esempio n. 15
0
 public static bool UninstallService(string serviceName)
 {
     try
     {
         var serviceInstallerObj = new ServiceInstaller();
         var context = new InstallContext();
         serviceInstallerObj.Context = context;
         serviceInstallerObj.ServiceName = serviceName;
         serviceInstallerObj.Uninstall(null);
         return true;
     }
     catch (Exception e)
     {
         Logger.Log("TpaMaintenance Log: (Attempt to uninstall TpaService did not succeed. Exception: {0})", LogLevel.Warning, e.Message);
         return false;
     }
 }
Esempio n. 16
0
        public void Uninstall()
        {
            RemoveService();

            var serviceInstaller = new ServiceInstaller();
            var context = new InstallContext("jackettservice_uninstall.log", null);
            serviceInstaller.Context = context;
            serviceInstaller.ServiceName = NAME;
            serviceInstaller.Uninstall(null);

            logger.Info("The service was uninstalled.");
        }
Esempio n. 17
0
        static void Install(bool install, InstallerOptions options)
        {
            var spi = new ServiceProcessInstaller();
            var si = new ServiceInstaller();
            spi.Account = ServiceAccount.NetworkService;
            if (options != null && options.IsUser)
            {
                spi.Account = ServiceAccount.User;
                if (options.UserName != null)
                {
                    spi.Username = options.UserName;
                }
                if (options.Password != null)
                {
                    spi.Password = options.Password;
                }
            }
            si.StartType = ServiceStartMode.Automatic;
            si.ServiceName = "CloudBackup";
            si.DisplayName = "Cloud Backup Service";
            si.Description = "Schedules, run and manage cloud backup";
            si.Parent = spi;

            string path = Assembly.GetEntryAssembly().Location;
            Console.WriteLine("Location : " + path);

            var ic = new InstallContext();
            ic.Parameters.Add("assemblypath", path);
            si.Context = ic;
            spi.Context = ic;

            IDictionary rb = install ? new Hashtable() : null;
            try
            {
                Console.WriteLine("Starting Default Installation");
                if (install)
                {
                    si.Install(rb);
                }
                else
                {
                    si.Uninstall(rb);
                }
            }
            catch (Exception ex)
            {
                log.Fatal(ex);
                if (rb != null)
                {
                    Console.WriteLine("Rollback Default Installation");
                    IDictionary rbc = rb;
                    rb = null;
                    si.Rollback(rbc);
                }
            }
            finally
            {
                if (rb != null)
                {
                    Console.WriteLine("Commit Default Installation");
                    si.Commit(rb);
                }
            }
        }
Esempio n. 18
0
        private static bool UnInstallService(string serviceName)
        {

            bool success = false;
            try
            {
                ServiceUtility.StopStartServices(serviceName, ServiceControllerStatus.StopPending);
                string exeFullPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
                string workingPath = System.IO.Path.GetDirectoryName(exeFullPath);
                string logPath = System.IO.Path.Combine(workingPath, "Install.log");

                ServiceInstaller myServiceInstaller = new ServiceInstaller();
                InstallContext Context = new InstallContext(logPath, null);
                myServiceInstaller.Context = Context;
                myServiceInstaller.ServiceName = serviceName;
                myServiceInstaller.Uninstall(null);                
                success = true;

            }
            catch (Exception ex)
            {

            }
            return success;
        }
Esempio n. 19
0
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>


        static void Main(string[] args)
        {
            if (System.Environment.UserInteractive)
            {
                string parameter = string.Concat(args);
                System.ServiceProcess.ServiceInstaller SINST = new System.ServiceProcess.ServiceInstaller();
                ServiceController SCONTROL = new ServiceController();
                SCONTROL.ServiceName = "appController";
                switch (parameter)
                {
                // http://stackoverflow.com/questions/255056/install-a-net-windows-service-without-installutil-exe
                case "--install":
                    //ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
                    ServiceProcessInstaller processInstaller = new ServiceProcessInstaller();
                    processInstaller.Account = ServiceAccount.LocalSystem;

                    System.Configuration.Install.InstallContext Context = new System.Configuration.Install.InstallContext();
                    string processPath = Process.GetCurrentProcess().MainModule.FileName;
                    if (processPath != null && processPath.Length > 0)
                    {
                        System.IO.FileInfo fi = new System.IO.FileInfo(processPath);

                        String   path    = String.Format("/assemblypath={0}", fi.FullName);
                        String[] cmdline = { path };
                        Context = new System.Configuration.Install.InstallContext("", cmdline);
                    }


                    SINST.Context = Context;
                    //SINST.DisplayName = String.Format("{0} - {1}", "appController", InstanceID);
                    //SINST.Description = String.Format("{0} - {1}", "appController", InstanceID);
                    //SINST.ServiceName = String.Format("{0}_{1}", "appController", InstanceID);

                    SINST.ServiceName = "appController";
                    SINST.StartType   = ServiceStartMode.Automatic;
                    SINST.Parent      = processInstaller;

                    SINST.ServicesDependedOn = null;
                    System.Collections.Specialized.ListDictionary state = new System.Collections.Specialized.ListDictionary();
                    SINST.Install(state);

                    //// http://www.dotnet247.com/247reference/msgs/43/219565.aspx
                    //using (RegistryKey oKey = Registry.LocalMachine.OpenSubKey(String.Format(@"SYSTEM\CurrentControlSet\Services\{0}_{1}", "", InstanceID), true))
                    //{
                    //    try
                    //    {
                    //        Object sValue = oKey.GetValue("ImagePath");
                    //        oKey.SetValue("ImagePath", sValue);
                    //    }
                    //    catch (Exception Ex)
                    //    {
                    //        MessageBox.Show(Ex.Message);
                    //    }
                    //}
                    break;

                case "--uninstall":
                    //ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });
                    //http://www.theblacksparrow.com/


                    SINST.Context = new System.Configuration.Install.InstallContext(
                        Environment.GetEnvironmentVariable("temp") + "\\install.log",
                        null);
                    //SINST.ServiceName = String.Format("{0}_{1}", ServiceName, InstanceID);
                    SINST.ServiceName = "appController";
                    SINST.Uninstall(null);
                    break;

                case "--start":
                    if (SCONTROL.Status == ServiceControllerStatus.Stopped)
                    {
                        SCONTROL.Start();
                    }
                    break;

                case "--stop":
                    if (SCONTROL.Status == ServiceControllerStatus.Running)
                    {
                        SCONTROL.Stop();
                    }
                    break;
                }
            }
            else
            {
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[]
                {
                    new MyService()
                };
                ServiceBase.Run(ServicesToRun);
            }
        }