public static ServiceReturnCode DeleteService(string serviceName, string machineName)
        {
            ServiceReturnCode result = ServiceReturnCode.UnknownFailure;

            ServiceUtilWmiHelper helper  = new ServiceUtilWmiHelper(machineName);
            ManagementObject     service = helper.GetInstance(string.Format("Win32_Service.Name='{0}'", serviceName));

            try
            {
                ManagementBaseObject mbo = service.InvokeMethod("Delete", null, null);

                result = (ServiceReturnCode)Enum.Parse(typeof(ServiceReturnCode), mbo["ReturnValue"].ToString());
            }
            catch (ManagementException mex)
            {
                //if ErrorCode == ManagementStatus.NotFound, eat the error.
                result = ServiceReturnCode.ServiceNotFound;

                //otherwise, throw whatever happened
                if (mex.ErrorCode != ManagementStatus.NotFound)
                {
                    throw mex;
                }
            }

            return(result);
        }
Exemplo n.º 2
0
        public override DeploymentResult Execute()
        {
            var result = new DeploymentResult();

            if (UserName.ShouldPrompt())
            {
                UserName = _prompt.Prompt("Win Service '{0}' UserName".FormatWith(ServiceName));
            }

            if (Password.ShouldPrompt())
            {
                Password = _prompt.Prompt("Win Service '{0}' For User '{1}' Password".FormatWith(ServiceName, UserName));
            }

            ServiceReturnCode returnCode = WmiService.Create(MachineName, ServiceName, ServiceDisplayName, ServiceLocation,
                                                             StartMode, UserName, Password, Dependencies);

            if (returnCode != ServiceReturnCode.Success)
            {
                result.AddAlert("Create service returned {0}".FormatWith(returnCode.ToString()));
            }
            else
            {
                result.AddGood("Create service succeeded.");
            }

            return(result);
        }
Exemplo n.º 3
0
        private void Uninstall()
        {
            bool targetLocal = this.TargetingLocalMachine(RemoteExecutionAvailable);

            if (!this.ServiceDoesExist())
            {
                this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Service does not exist: {0} on '{1}'", this.ServiceDisplayName, this.MachineName));
                return;
            }

            if (this.Stop())
            {
                try
                {
                    ManagementObject wmi = this.RetrieveManagementObject(targetLocal);

                    object[]          paramList  = new object[] { };
                    object            result     = wmi.InvokeMethod("Delete", paramList);
                    ServiceReturnCode returnCode = (ServiceReturnCode)Convert.ToInt32(result, CultureInfo.InvariantCulture);
                    if (returnCode != ServiceReturnCode.Success)
                    {
                        this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Uninstall Service failed with code: '{0}'", returnCode));
                    }
                    else
                    {
                        this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Uninstall Service succeeded for '{0}' on '{1}'", this.ServiceDisplayName, this.MachineName));
                    }
                }
                catch (Exception ex)
                {
                    this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Uninstall Service [{0} on {1}] failed with error '{2}'", this.ServiceDisplayName, this.MachineName, ex.Message));
                }
            }
        }
Exemplo n.º 4
0
        public override DeploymentResult Execute()
        {
            var result = new DeploymentResult();

            ServiceReturnCode returnCode = WmiService.Delete(MachineName, ServiceName);

            return(result);
        }
        public static ServiceReturnCode CreateService(string serviceName, string machineName, string displayName, string pathName, ServiceStartMode startMode,
                                                      string startName = null, string password = null, string parameters = null,
                                                      WindowsServiceType serviceType      = WindowsServiceType.OwnProcess, ErrorControlAction errorControl = ErrorControlAction.UserIsNotified,
                                                      bool interactWithDesktop            = false, string loadOrderGroup = null,
                                                      string[] loadOrderGroupDependencies = null, string[] svcDependencies = null)
        {
            ServiceReturnCode result = ServiceReturnCode.UnknownFailure;

            ServiceUtilWmiHelper helper  = new ServiceUtilWmiHelper(machineName);
            ManagementClass      mc      = helper.GetManagementClass("Win32_Service");
            ManagementBaseObject inparms = mc.GetMethodParameters("Create");
            string execPath = pathName;

            if (startMode == ServiceStartMode.Unchanged)
            {
                startMode = ServiceStartMode.Automatic;
            }

            if (!string.IsNullOrEmpty(parameters))
            {
                execPath = string.Format("{0} {1}", pathName, parameters);
            }

            inparms["Name"]                       = serviceName;
            inparms["DisplayName"]                = displayName;
            inparms["PathName"]                   = execPath;
            inparms["ServiceType"]                = serviceType;
            inparms["ErrorControl"]               = errorControl;
            inparms["StartMode"]                  = startMode.ToString();
            inparms["DesktopInteract"]            = interactWithDesktop;
            inparms["StartName"]                  = startName;
            inparms["StartPassword"]              = password;
            inparms["LoadOrderGroup"]             = loadOrderGroup;
            inparms["LoadOrderGroupDependencies"] = loadOrderGroupDependencies;
            inparms["ServiceDependencies"]        = svcDependencies;

            try
            {
                ManagementBaseObject mbo = mc.InvokeMethod("Create", inparms, null);
                result = (ServiceReturnCode)Enum.Parse(typeof(ServiceReturnCode), mbo["ReturnValue"].ToString());

                if (result == ServiceReturnCode.Success)
                {
                    UpdateServiceDescriptionWithVersion(serviceName, machineName, pathName);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(result);
        }
Exemplo n.º 6
0
        private void Install()
        {
            bool targetLocal = this.TargetingLocalMachine(RemoteExecutionAvailable);

            // check to see if the exe path has been provided
            if (this.ServicePath == null)
            {
                this.Log.LogError("ServicePath was not provided.");
                return;
            }

            if (string.IsNullOrEmpty(this.User))
            {
                this.Log.LogError("User was not provided.");
                return;
            }

            if (string.IsNullOrEmpty(this.ServiceName))
            {
                this.Log.LogError("ServiceName was not provided.");
                return;
            }

            // check to see if the correct path has been provided
            if (targetLocal && (System.IO.File.Exists(this.ServicePath.GetMetadata("FullPath")) == false))
            {
                this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "ServicePath does not exist: {0}", this.ServicePath));
                return;
            }

            System.Collections.Generic.List <string> serviceDependencies = new System.Collections.Generic.List <string>();
            if (null != this.ServiceDependencies)
            {
                foreach (ITaskItem dep in this.ServiceDependencies)
                {
                    serviceDependencies.Add(dep.ItemSpec);
                }
            }

            ServiceReturnCode ret = this.Install(this.MachineName, this.ServiceName, this.ServiceDisplayName, this.ServicePath.ToString(), ServiceStartMode.Automatic, this.User, this.Password, serviceDependencies.ToArray(), false, this.RemoteUser, this.RemoteUserPassword);

            if (ret != ServiceReturnCode.Success)
            {
                this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Install Service failed with code: '{0}'", ret));
            }
            else
            {
                this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Install Service succeeded for '{0}' on '{1}'", this.ServiceDisplayName, this.MachineName));
            }
        }
        /// <summary>
        /// Sets the StartMode of a Windows service.
        /// </summary>
        /// <param name="serviceName">The internal service name. Ex:"Print Spooler" is "Spooler".</param>
        /// <param name="machineName">The server on which the service is running.</param>
        /// <param name="startMode">The value to set.</param>
        /// <returns>Enumerated value as returned from Wmi call.</returns>
        public static ServiceReturnCode ChangeStartMode(string serviceName, string machineName, ServiceStartMode startMode)
        {
            ServiceReturnCode result = ServiceReturnCode.UnknownFailure;

            ManagementObjectCollection services = GetServicesByServiceName(serviceName, machineName);

            foreach (ManagementObject service in services)
            {
                ManagementBaseObject inparms = service.GetMethodParameters("ChangeStartMode");
                inparms["StartMode"] = startMode.ToString();
                ManagementBaseObject mbo = service.InvokeMethod("ChangeStartMode", inparms, null);
                result = (ServiceReturnCode)Enum.Parse(typeof(ServiceReturnCode), mbo["ReturnValue"].ToString());
            }

            return(result);
        }
Exemplo n.º 8
0
        public override DeploymentResult Execute()
        {
            var result = new DeploymentResult();

            if (!ServiceExists())
            {
                result.AddNote("Cannot delete service '{0}', service does not exist".FormatWith(ServiceName));
            }
            else
            {
                ServiceReturnCode returnCode = WmiService.Delete(MachineName, ServiceName);
                if (returnCode != ServiceReturnCode.Success)
                {
                    result.AddAlert("Deleting service '{0}' failed: '{1}'".FormatWith(ServiceName, returnCode));
                }
            }
            return(result);
        }
Exemplo n.º 9
0
        private void InstallService(bool shouldInstall)
        {
            string exePath = txtPath.Text;

            if (string.IsNullOrEmpty(exePath))
            {
                MessageBox.Show("Path to executable is required", "Error", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);
                return;
            }
            ServiceReturnCode installStatus = ServiceReturnCode.NotSupported;
            BackgroundWorker  worker        = new BackgroundWorker();

            worker.DoWork += (s, dwe) =>
            {
                if (shouldInstall)
                {
                    installStatus = WmiService.Instance.Install(Controller.MachineName, _serviceName, _serviceName, exePath, ServiceUtils.ServiceStartMode.Automatic, "LocalSystem", null, null);
                }
                else
                {
                    installStatus = WmiService.Instance.Uninstall(Controller.MachineName, _serviceName);
                }
                Thread.Sleep(5000);
            };
            worker.RunWorkerCompleted += (s, rwe) =>
            {
                busyIndicator.IsBusy = false;
                if (rwe.Error != null)
                {
                    MessageBox.Show(rwe.Error.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);
                }
                else if (installStatus != ServiceReturnCode.Success)
                {
                    MessageBox.Show(installStatus.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);
                }
                RefreshStatus();
            };
            busyIndicator.IsBusy = true;
            worker.RunWorkerAsync();
        }
        public ServiceReturnCode ChangeStartMode(string svcName, ServiceStartMode startMode)
        {
            ServiceReturnCode retCode = ServiceReturnCode.UnknownFailure;
            string            host    = Scope.Path.Server;

            try
            {
                ObjectQuery query = new ObjectQuery("SELECT Name,ProcessId,State,Started, StartMode FROM Win32_service WHERE name='" + svcName + "'");
                ManagementObjectCollection queryCollection = Query(query, WmiPath.Root);

                foreach (ManagementObject service in queryCollection)
                {
                    ManagementBaseObject mboIn = service.GetMethodParameters("ChangeStartMode");
                    mboIn["StartMode"] = startMode.ToString();
                    ManagementBaseObject mbo = service.InvokeMethod("ChangeStartMode", mboIn, null);
                    retCode = (ServiceReturnCode)Enum.Parse(typeof(ServiceReturnCode), mbo["ReturnValue"].ToString());
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(retCode);
        }
Exemplo n.º 11
0
    public void ProcessServiceRequest(ServiceAction action, Service service, int timeout)
    {
        string[] loadOrderGroupDependencies = service.LoadOrderGroupDependencies?.ToArray<String>();
        string[] serviceDependencies = service.ServiceDependencies?.ToArray<String>();

        ServiceConfig status = null;
        ServiceReturnCode rc = ServiceReturnCode.NotSupported;
        bool success = _isDryRun;

        switch( action )
        {
            case ServiceAction.Create:
            {
                    if (!_isDryRun)
                    {
                        rc = ServiceUtil.CreateService(service.Name, service.Server, service.DisplayName, service.Description, service.BinPath,
                                                        service.StartMode, service.StartName, service.StartPassword,
                                                        service.Type, service.OnError, service.InteractWithDesktop, service.LoadOrderGroup,
                                                        loadOrderGroupDependencies, serviceDependencies);
                        if (_config.StartOnCreate == true)
                            success = ServiceUtil.Start(service.Name, service.Server, timeout, service.StartMode);
                        status = ServiceUtil.QueryService(service.Name, service.Server);
                    }
                    else
                    {
                        // DryRun : Return mocked up ServiceConfig with values that WOULD have been created.
                        ServiceConfig sc = new ServiceConfig();
                        sc.Name = service.Name;
                        sc.ServerName = service.Server;
                        sc.DisplayName = service.DisplayName;
                        sc.Description = service.Description;
                        sc.PathName = service.BinPath;
                        sc.StartMode = service.StartMode;
                        sc.StartName = service.StartName;
                        sc.ServiceType = service.Type.ToString();
                        sc.ErrorControl = service.OnError.ToString();
                        sc.DesktopInteract = service.InteractWithDesktop;
                        status = sc;
                    }

                    break;
            }
            case ServiceAction.Delete:
            {
                if (!_isDryRun)
                {
                    rc = ServiceUtil.DeleteService(service.Name, service.Server);
                }
                else
                {
                    status = ServiceUtil.QueryService(service.Name, service.Server);
                }
                break;
            }
            case ServiceAction.Query:
            {
                status = ServiceUtil.QueryService( service.Name, service.Server );
                break;
            }
            case ServiceAction.Start:
            {
                if( !_isDryRun )
                    success = ServiceUtil.Start( service.Name, service.Server, timeout, service.StartMode, service.StartParameters?.ToArray<String>() );
                status = ServiceUtil.QueryService( service.Name, service.Server );
                break;
            }
            case ServiceAction.Stop:
            {
                if( !_isDryRun )
                    success = ServiceUtil.Stop( service.Name, service.Server, timeout, service.StartMode );
                status = ServiceUtil.QueryService( service.Name, service.Server );
                break;
            }
            case ServiceAction.Restart:
            {
                if( !_isDryRun )
                {
                    success = ServiceUtil.Stop( service.Name, service.Server, timeout, ServiceStartMode.Unchanged );
                    Thread.Sleep( 5000 );
                    success = ServiceUtil.Start( service.Name, service.Server, timeout, service.StartMode );
                }
                status = ServiceUtil.QueryService( service.Name, service.Server );
            }
            break;
            case ServiceAction.StartMode:
            {
                if( !_isDryRun )
                    rc = ServiceUtil.ChangeStartMode( service.Name, service.Server, service.StartMode );
                status = ServiceUtil.QueryService( service.Name, service.Server );
                break;
            }
        }

        if( status != null )
        {
            OnLogMessage( action.ToString(), "Name : [" + status.ServiceName + "] Status : [" + status.State + "]" );
            _results.Add( status );
        }
    }