public string ActionCheck(string controllerName) { SC_USER user = _sessionProvider.Get <SC_USER>(Strings.Authorization.UserSessionKey); StringBuilder strBuilder = new StringBuilder(); controllerName = controllerName.ToLower(); var lst = _action.GetAll(user.IdUser).Where(k => k.FullPath.ToLower().IndexOf(controllerName) != -1).ToList(); strBuilder.Append("Bu sayfada size özel bazı kısıtlamalar bulunmaktadır : "); for (int i = 0; i < lst.Count; i++) { SC_ACTION obj = lst[i]; strBuilder.Append(obj.ActionDesc); if (i != lst.Count - 1) { strBuilder.Append(", "); } } if (lst.Count == 0) { return(string.Empty); } throw new NotificationException(strBuilder.ToString()); }
static SC_ACTION GetScAction(ServiceRecoveryAction action, uint restartServiceAfter) { var scAction = new SC_ACTION(); SC_ACTION_TYPE actionType = default(SC_ACTION_TYPE); switch (action) { case ServiceRecoveryAction.TakeNoAction: actionType = SC_ACTION_TYPE.None; break; case ServiceRecoveryAction.RestartService: actionType = SC_ACTION_TYPE.RestartService; break; case ServiceRecoveryAction.RestartComputer: actionType = SC_ACTION_TYPE.RebootComputer; break; case ServiceRecoveryAction.RunProgram: actionType = SC_ACTION_TYPE.RunCommand; break; } scAction.Type = actionType; scAction.Delay = restartServiceAfter; return(scAction); }
public unsafe void ChangeServiceConfig2_ErrorsProperly() { Assert.False(ChangeServiceConfig2(SafeServiceHandle.Null, ServiceInfoLevel.SERVICE_CONFIG_DESCRIPTION, null)); string rebootMessage = "Rebooting now."; fixed(char *pRebootMessage = rebootMessage.ToCharArrayWithNullTerminator()) { var actions = new SC_ACTION[] { new SC_ACTION { Type = SC_ACTION_TYPE.SC_ACTION_REBOOT, Delay = 2000 }, new SC_ACTION { Type = SC_ACTION_TYPE.SC_ACTION_REBOOT, Delay = 2000 }, }; fixed(SC_ACTION *pActions = &actions[0]) { var failureActions = new SERVICE_FAILURE_ACTIONS { lpRebootMsg = pRebootMessage, cActions = 2, lpsaActions = pActions, }; Assert.False(ChangeServiceConfig2(SafeServiceHandle.Null, ServiceInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS_FLAG, &failureActions)); } } }
public SERVICE_FAILURE_ACTIONS(ServiceFailureActions sfa) { if (sfa.ResetPeriod.TotalSeconds > 0) { dwResetPeriod = Convert.ToUInt32(sfa.ResetPeriod.TotalSeconds); } else { dwResetPeriod = 0; } if (sfa.RebootMessage.Length > 0) { rebootMsg = Marshal.StringToHGlobalUni(sfa.RebootMessage); } else { rebootMsg = IntPtr.Zero; } if (sfa.Command.Length > 0) { command = Marshal.StringToHGlobalUni(sfa.Command); } else { command = IntPtr.Zero; } if (sfa.HasActionsDefined) { numActions = (uint)sfa.Actions.Length; //Allocate space for the unmanaged array SC_ACTION nativeAction; int sizeSCACTION = Marshal.SizeOf(typeof(SC_ACTION)); actions = Marshal.AllocHGlobal(sizeSCACTION * sfa.Actions.Length); //Nowe we need to copy the elements to the new array (but we have to track where we place it) IntPtr pElement = actions; for (int nIdx = 0; nIdx < numActions; ++nIdx) { //Copy the action data nativeAction = new SC_ACTION(sfa.Actions[nIdx]); //The destination is actual calculated from the base of our pointer pElement = (IntPtr)(actions.ToInt64() + (sizeSCACTION * nIdx)); Marshal.StructureToPtr(nativeAction, pElement, false); } ; } else { numActions = 0; actions = IntPtr.Zero; }; }
/// <summary> /// Configures the service to auto-restart on failure /// </summary> public void SetRestartOnFailure(int restartAttempts, int restartDelay, int resetFailuresDelay) { SC_ACTION[] actions = new SC_ACTION[3] { new SC_ACTION { Delay = Math.Max(0, Math.Min(int.MaxValue, restartDelay)), Type = SC_ACTION_TYPE.SC_ACTION_RESTART }, new SC_ACTION { Delay = Math.Max(0, Math.Min(int.MaxValue, restartDelay)), Type = SC_ACTION_TYPE.SC_ACTION_RESTART }, new SC_ACTION { Delay = Math.Max(0, Math.Min(int.MaxValue, restartDelay)), Type = SC_ACTION_TYPE.SC_ACTION_RESTART }, }; for (int i = Math.Max(0, restartAttempts); i < actions.Length; i++) { actions[i] = new SC_ACTION { Delay = 0, Type = SC_ACTION_TYPE.SC_ACTION_NONE } } ; GCHandle hdata = GCHandle.Alloc(actions, GCHandleType.Pinned); try { SERVICE_FAILURE_ACTIONS cfg = new SERVICE_FAILURE_ACTIONS(); cfg.dwResetPeriod = Math.Max(-1, Math.Min(int.MaxValue, resetFailuresDelay)); cfg.lpRebootMsg = cfg.lpCommand = IntPtr.Zero; cfg.cActions = actions.Length; cfg.lpsaActions = hdata.AddrOfPinnedObject(); SetServiceConfig(SERVICE_CONFIG_INFO.FAILURE_ACTIONS, cfg); } finally { hdata.Free(); } }
public bool IsActionAuthentication(RequestContext context) { SC_USER user = _sessionProvider.Get <SC_USER>(Strings.Authorization.UserSessionKey); //TN_COMPANY company = _sessionProvider.Get<TN_COMPANY>(Strings.Authorization.CompanySessionKey); if (user == null) { return(true); } // Cache Key tanımlanır. Her kullanıcı ve firma için farklı olması gerekiyor. string cacheMenuKey = "SC_ACTION_" + "User" + user.IdUser.ToString(); List <SC_ACTION> _lstAction = _cacheProvider.Get <List <SC_ACTION> >(cacheMenuKey); if (_lstAction == null) { _lstAction = _definitionBusiness.GetAll <SC_ACTION>().ToList(); _cacheProvider.Set(cacheMenuKey, _lstAction); } string fullPath = context.HttpContext.Request.FilePath; SC_ACTION objAction = _lstAction.FirstOrDefault(k => k.FullPath == fullPath); if (objAction != null) { var lstAction = _action.GetAll(user.IdUser); SC_ACTION objActionResult = null; if (lstAction != null) { objActionResult = lstAction.FirstOrDefault(k => k.IdAction == objAction.IdAction); } if (objActionResult != null) { throw new NotAuthorizationActionException(); } } return(true); }
public static void SetRecoveryOptions(IntPtr service, SC_ACTION[] actions, bool applyOnErrorStop = false, uint failureResetSeconds = 3600, string command = null, string rebootMsg = null) { var recovery = new SERVICE_FAILURE_ACTIONS(); var defaultAction = new SC_ACTION(SC_ACTION_TYPE.SC_ACTION_NONE, 0); recovery.cActions = 3; var size = Marshal.SizeOf(typeof(SC_ACTION)); recovery.lpsaActions = Marshal.AllocHGlobal((System.Int32)(size * recovery.cActions)); for (int ix = 0; ix < recovery.cActions; ++ix) { var action = (actions != null && ix < actions.Length) ? actions[ix] : defaultAction; Marshal.StructureToPtr(action, IntPtr.Add(recovery.lpsaActions, ix * size), false); } recovery.dwResetPeriod = failureResetSeconds; // time to reset failure counter, seconds recovery.lpCommand = command; // command to execute recovery.lpRebootMsg = rebootMsg; // reboot message (we don't use it) try { if (!ChangeServiceConfig2(service, SERVICE_INFO_LEVEL.FAILURE_ACTIONS, ref recovery)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } } finally { // clean up so no memory leak // Note, does nothing when given IntPtr.Zero Marshal.FreeHGlobal(recovery.lpsaActions); } // Set whether or not to apply recovery actions if service stops itself with non-0 Win32ExitCode var failure_actions_flag = new SERVICE_FAILURE_ACTIONS_FLAG(); failure_actions_flag.fFailureActionsOnNonCrashFailures = applyOnErrorStop; ChangeServiceConfig2(service, SERVICE_INFO_LEVEL.FAILURE_ACTIONS_FLAG, ref failure_actions_flag); }
private static ServiceRecoveryAction getServiceRecoveryAction(SC_ACTION action) { ServiceRecoveryAction serviceRecoveryAction = default(ServiceRecoveryAction); switch (action.Type) { case SC_ACTION_TYPE.None: serviceRecoveryAction = ServiceRecoveryAction.TakeNoAction; break; case SC_ACTION_TYPE.RestartService: serviceRecoveryAction = ServiceRecoveryAction.RestartTheService; break; case SC_ACTION_TYPE.RebootComputer: serviceRecoveryAction = ServiceRecoveryAction.RestartTheComputer; break; case SC_ACTION_TYPE.RunCommand: serviceRecoveryAction = ServiceRecoveryAction.RunAProgram; break; } return(serviceRecoveryAction); }
void SetRestartOnFailure(string serviceName) { const int actionCount = 2; const uint delay = 60000; var service = IntPtr.Zero; var failureActionsPtr = IntPtr.Zero; var actionPtr = IntPtr.Zero; try { service = OpenService(serviceName, SERVICE_ACCESS_RIGHTS.SERVICE_CHANGE_CONFIG | SERVICE_ACCESS_RIGHTS.SERVICE_START); actionPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SC_ACTION)) * actionCount); var action1 = new SC_ACTION { Type = SC_ACTION_TYPE.SC_ACTION_RESTART, Delay = delay }; Marshal.StructureToPtr(action1, actionPtr, false); var action2 = new SC_ACTION { Type = SC_ACTION_TYPE.SC_ACTION_NONE, Delay = delay }; Marshal.StructureToPtr(action2, (IntPtr)((long)actionPtr + Marshal.SizeOf(typeof(SC_ACTION))), false); var failureActions = new SERVICE_FAILURE_ACTIONS { dwResetPeriod = 0, cActions = actionCount, lpsaActions = actionPtr }; failureActionsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SERVICE_FAILURE_ACTIONS))); Marshal.StructureToPtr(failureActions, failureActionsPtr, false); var changeResult = ChangeServiceConfig2( service, ServiceConfig2InfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, failureActionsPtr); if (changeResult == 0) { throw new Win32Exception(Marshal.GetLastWin32Error(), "Unable to change the Service configuration."); } } finally { // Clean up if (failureActionsPtr != IntPtr.Zero) { Marshal.FreeHGlobal(failureActionsPtr); } if (actionPtr != IntPtr.Zero) { Marshal.FreeHGlobal(actionPtr); } if (service != IntPtr.Zero) { CloseServiceHandle(service); } } }
static SC_ACTION GetScAction(ServiceRecoveryAction action, uint restartServiceAfter) { var scAction = new SC_ACTION(); SC_ACTION_TYPE actionType = default(SC_ACTION_TYPE); switch (action) { case ServiceRecoveryAction.TakeNoAction: actionType = SC_ACTION_TYPE.None; break; case ServiceRecoveryAction.RestartService: actionType = SC_ACTION_TYPE.RestartService; break; case ServiceRecoveryAction.RestartComputer: actionType = SC_ACTION_TYPE.RebootComputer; break; case ServiceRecoveryAction.RunProgram: actionType = SC_ACTION_TYPE.RunCommand; break; } scAction.Type = actionType; scAction.Delay = restartServiceAfter; return scAction; }
public static void InstallAndStart(string serviceName, string displayName, string fileName) { IntPtr scm = OpenSCManager(ScmAccessRights.AllAccess); try { IntPtr service = OpenService(scm, serviceName, ServiceAccessRights.AllAccess); if (service == IntPtr.Zero) service = CreateService(scm, serviceName, displayName, ServiceAccessRights.AllAccess, SERVICE_WIN32_OWN_PROCESS, ServiceBootFlag.AutoStart, ServiceError.Normal, fileName, null, IntPtr.Zero, null, null, null); if (service == IntPtr.Zero) throw new ApplicationException("Failed to install service."); // set restart options try { SC_ACTION action = new SC_ACTION(); action.Type = SC_ACTION_TYPE.RestartService; action.Delay = (uint)TimeSpan.FromSeconds(10).TotalMilliseconds; IntPtr lpsaActions = Marshal.AllocHGlobal(Marshal.SizeOf(action) * 2); if (lpsaActions == IntPtr.Zero) { throw new Exception(String.Format("Unable to allocate memory for service action, error was: 0x{0:X}", Marshal.GetLastWin32Error())); } Marshal.StructureToPtr(action, lpsaActions, false); IntPtr nextAction = (IntPtr)(lpsaActions.ToInt64() + Marshal.SizeOf(action)); action.Type = SC_ACTION_TYPE.RestartService; Marshal.StructureToPtr(action, nextAction, false); action.Delay = (uint)TimeSpan.FromSeconds(30).TotalMilliseconds; SERVICE_FAILURE_ACTIONS failureActions = new SERVICE_FAILURE_ACTIONS(); failureActions.dwResetPeriod = (int)TimeSpan.FromDays(1).TotalSeconds; failureActions.lpRebootMsg = ""; failureActions.lpCommand = ""; failureActions.cActions = 2; failureActions.lpsaActions = lpsaActions; IntPtr lpInfo = Marshal.AllocHGlobal(Marshal.SizeOf(failureActions)); if (lpInfo == IntPtr.Zero) { Marshal.FreeHGlobal(lpsaActions); throw new Exception(String.Format("Unable to allocate memory, error was: 0x{0:X}", Marshal.GetLastWin32Error())); } Marshal.StructureToPtr(failureActions, lpInfo, false); if (!ChangeServiceConfig2(service, 2, lpInfo)) { Marshal.FreeHGlobal(lpInfo); Marshal.FreeHGlobal(lpsaActions); int err = Marshal.GetLastWin32Error(); if (err == 1072) { throw new Exception(String.Format("Can't set service config. Service " + serviceName + " is marked for delete. Restart machine to clear this up.", err)); } else { throw new Exception(String.Format("Error setting service config, error was: {0}", err)); } } Marshal.FreeHGlobal(lpInfo); Marshal.FreeHGlobal(lpsaActions); } finally { } try { StartService(service); } finally { CloseServiceHandle(service); } } finally { CloseServiceHandle(scm); } }
public static extern void CopyMemory(IntPtr pDst, SC_ACTION[] pSrc, int ByteLen);
public static string Delete(SC_ACTION obj) { return(string.Format("{0} idli ve {1} adlı Sayfa İçi Yetki Tanımı silindi.", obj.IdAction, obj.ActionName)); }
public static string Insert(SC_ACTION obj) { return(string.Format("{0} idli ve {1} adlı Sayfa İçi Yetki Tanımı eklendi.", obj.IdAction, obj.ActionName)); }
public static string Update(SC_ACTION obj) { return(string.Format("{0} idli ve {1} adlı Sayfa İçi Yetki Tanımı güncellendi.", obj.IdAction, obj.ActionName)); }
public static extern void CopyMemory(IntPtr dst, SC_ACTION[] src, int length);
public static void SetServiceRecoveryOptions( string serviceName, [NotNull] ServiceRecoveryOptions recoveryOptions) { if (recoveryOptions == null) { throw new ArgumentNullException("recoveryOptions"); } bool requiresShutdownPriveleges = recoveryOptions.FirstFailureAction == ServiceRecoveryAction.RestartComputer || recoveryOptions.SecondFailureAction == ServiceRecoveryAction.RestartComputer || recoveryOptions.SubsequentFailureAction == ServiceRecoveryAction.RestartComputer; if (requiresShutdownPriveleges) { GrantShutdownPrivileges(); } int actionCount = 3; var restartServiceAfter = (uint)TimeSpan.FromMinutes( recoveryOptions.RestartServiceWaitMinutes).TotalMilliseconds; IntPtr failureActionsPointer = IntPtr.Zero; IntPtr actionPointer = IntPtr.Zero; ServiceController controller = null; try { // Open the service controller = new ServiceController(serviceName); // Set up the failure actions var failureActions = new SERVICE_FAILURE_ACTIONS(); failureActions.dwResetPeriod = (int)TimeSpan.FromDays(recoveryOptions.ResetFailureCountWaitDays).TotalSeconds; failureActions.cActions = (uint)actionCount; failureActions.lpRebootMsg = recoveryOptions.RestartSystemMessage; // allocate memory for the individual actions actionPointer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SC_ACTION)) * actionCount); ServiceRecoveryAction[] actions = { recoveryOptions.FirstFailureAction, recoveryOptions.SecondFailureAction, recoveryOptions.SubsequentFailureAction }; for (int i = 0; i < actions.Length; i++) { ServiceRecoveryAction action = actions[i]; SC_ACTION scAction = GetScAction(action, restartServiceAfter); Marshal.StructureToPtr(scAction, (IntPtr)((Int64)actionPointer + (Marshal.SizeOf(typeof(SC_ACTION))) * i), false); } failureActions.lpsaActions = actionPointer; string command = recoveryOptions.RunProgramCommand; if (command != null) { failureActions.lpCommand = command; } failureActionsPointer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SERVICE_FAILURE_ACTIONS))); Marshal.StructureToPtr(failureActions, failureActionsPointer, false); // Make the change bool success = ChangeServiceConfig2(controller.ServiceHandle.DangerousGetHandle(), SERVICE_CONFIG_FAILURE_ACTIONS, failureActionsPointer); // Check that the change occurred if (!success) { throw new Win32Exception(Marshal.GetLastWin32Error(), "Unable to change the Service configuration."); } } finally { if (failureActionsPointer != IntPtr.Zero) { Marshal.FreeHGlobal(failureActionsPointer); } if (actionPointer != IntPtr.Zero) { Marshal.FreeHGlobal(actionPointer); } if (controller != null) { controller.Dispose(); } //log.Debug(m => m("Done setting service recovery options.")); } }
public static void ServiceQuery(string host, string svcname) { bool success; IntPtr dbHandle; IntPtr svcHandle; IntPtr ptr; UInt32 dwBytesNeeded; QUERY_SERVICE_CONFIG qconf; SERVICE_FAILURE_ACTIONS qfail; int failStructOffset; QUERY_SERVICE_STATUS_PROCESS qproc; if (host == "") { dbHandle = OpenSCManager(null, null, SC_MANAGER_ALL_ACCESS); } else { dbHandle = OpenSCManager(host, null, SC_MANAGER_ALL_ACCESS); } svcHandle = OpenService(dbHandle, svcname, SERVICE_QUERY_CONFIG); if (svcHandle == IntPtr.Zero) { throw new System.Runtime.InteropServices.ExternalException("Couldn't open the service"); } ptr = Marshal.AllocHGlobal(4096); success = QueryServiceConfig(svcHandle, ptr, 4096, out dwBytesNeeded); if (success == false) { throw new System.Runtime.InteropServices.ExternalException("Couldn't query the service"); } qconf = new QUERY_SERVICE_CONFIG(); // copy ptr to query_service_config struct Marshal.PtrToStructure(ptr, qconf); Marshal.FreeHGlobal(ptr); //reset states success = false; dwBytesNeeded = 0; success = QueryServiceConfig2(svcHandle, SERVICE_CONFIG_FAILURE_ACTIONS, IntPtr.Zero, 0, out dwBytesNeeded); //the first call of this function will get the number of bytes needed for the struct ptr = Marshal.AllocHGlobal((int)dwBytesNeeded); success = QueryServiceConfig2(svcHandle, SERVICE_CONFIG_FAILURE_ACTIONS, ptr, dwBytesNeeded, out dwBytesNeeded); qfail = new SERVICE_FAILURE_ACTIONS(); Marshal.PtrToStructure(ptr, qfail); SC_ACTION[] actions = new SC_ACTION[qfail.cActions]; failStructOffset = 0; Marshal.FreeHGlobal(ptr); //reset states success = false; dwBytesNeeded = 0; success = QueryServiceStatusEx(svcHandle, SC_STATUS_PROCESS_INFO, IntPtr.Zero, 0, out dwBytesNeeded);//again first call gets buffer size required for struct ptr = Marshal.AllocHGlobal((int)dwBytesNeeded); success = QueryServiceStatusEx(svcHandle, SC_STATUS_PROCESS_INFO, ptr, dwBytesNeeded, out dwBytesNeeded); qproc = new QUERY_SERVICE_STATUS_PROCESS(); Marshal.PtrToStructure(ptr, qproc); Marshal.FreeHGlobal(ptr); //reset states success = false; dwBytesNeeded = 0; for (int i = 0; i < qfail.cActions; i++) { SC_ACTION act = new SC_ACTION(); act.type = Marshal.ReadInt32(qfail.lpsaActions, failStructOffset); failStructOffset += sizeof(Int32); act.dwDelay = (UInt32)Marshal.ReadInt32(qfail.lpsaActions, failStructOffset); failStructOffset += sizeof(Int32); actions[i] = act; } Console.WriteLine("Service Name:\t" + svcname); Console.WriteLine("Service Type:\t" + qproc.dwServiceType); Console.WriteLine("State:\t" + qproc.dwCurrentState); Console.WriteLine("PID:\t" + qproc.dwProcessId); Console.WriteLine(); Console.WriteLine("Start Type:\t" + qconf.dwStartType); Console.WriteLine("Error Control:\t" + qconf.dwErrorControl); Console.WriteLine("BinPath:\t" + qconf.lpBinaryPathName); Console.WriteLine("Display Name:\t" + qconf.lpDisplayName); Console.WriteLine("Dependencies:\t" + qconf.lpDependencies); Console.WriteLine("Reset Period:\t" + qfail.dwResetPeriod); Console.WriteLine("Reboot Message:\t" + qfail.lpRebootMsg); Console.WriteLine("Failure Command Line:\t" + qfail.lpCommand); Console.WriteLine("Failure Actions:\t"); for (int i = 0; i < actions.Length; i++) { Console.Write("{0} -- Delay = {1}", actions[i].type, actions[i].dwDelay); } }
public static void InstallAndStart(string serviceName, string displayName, string fileName) { IntPtr scm = OpenSCManager(ScmAccessRights.AllAccess); try { IntPtr service = OpenService(scm, serviceName, ServiceAccessRights.AllAccess); if (service == IntPtr.Zero) { service = CreateService(scm, serviceName, displayName, ServiceAccessRights.AllAccess, SERVICE_WIN32_OWN_PROCESS, ServiceBootFlag.AutoStart, ServiceError.Normal, fileName, null, IntPtr.Zero, null, null, null); } if (service == IntPtr.Zero) { throw new ApplicationException("Failed to install service."); } // set restart options try { SC_ACTION action = new SC_ACTION(); action.Type = SC_ACTION_TYPE.RestartService; action.Delay = (uint)TimeSpan.FromSeconds(10).TotalMilliseconds; IntPtr lpsaActions = Marshal.AllocHGlobal(Marshal.SizeOf(action) * 2); if (lpsaActions == IntPtr.Zero) { throw new Exception(String.Format("Unable to allocate memory for service action, error was: 0x{0:X}", Marshal.GetLastWin32Error())); } Marshal.StructureToPtr(action, lpsaActions, false); IntPtr nextAction = (IntPtr)(lpsaActions.ToInt64() + Marshal.SizeOf(action)); action.Type = SC_ACTION_TYPE.RestartService; Marshal.StructureToPtr(action, nextAction, false); action.Delay = (uint)TimeSpan.FromSeconds(30).TotalMilliseconds; SERVICE_FAILURE_ACTIONS failureActions = new SERVICE_FAILURE_ACTIONS(); failureActions.dwResetPeriod = (int)TimeSpan.FromDays(1).TotalSeconds; failureActions.lpRebootMsg = ""; failureActions.lpCommand = ""; failureActions.cActions = 2; failureActions.lpsaActions = lpsaActions; IntPtr lpInfo = Marshal.AllocHGlobal(Marshal.SizeOf(failureActions)); if (lpInfo == IntPtr.Zero) { Marshal.FreeHGlobal(lpsaActions); throw new Exception(String.Format("Unable to allocate memory, error was: 0x{0:X}", Marshal.GetLastWin32Error())); } Marshal.StructureToPtr(failureActions, lpInfo, false); if (!ChangeServiceConfig2(service, 2, lpInfo)) { Marshal.FreeHGlobal(lpInfo); Marshal.FreeHGlobal(lpsaActions); int err = Marshal.GetLastWin32Error(); if (err == 1072) { throw new Exception(String.Format("Can't set service config. Service " + serviceName + " is marked for delete. Restart machine to clear this up.", err)); } else { throw new Exception(String.Format("Error setting service config, error was: {0}", err)); } } Marshal.FreeHGlobal(lpInfo); Marshal.FreeHGlobal(lpsaActions); } finally { } try { StartService(service); } finally { CloseServiceHandle(service); } } finally { CloseServiceHandle(scm); } }
public static ServiceRecoveryOptions GetServiceRecoveryOptions(string serviceName) { Exceptions.ThrowHelper.ThrowArgumentNullIfNull(serviceName, "serviceName"); Exceptions.ThrowHelper.ThrowArgumentOutOfRangeIfEmpty(serviceName, "serviceName"); Log.Debug("Getting service recovery options..."); // 8KB is the largest buffer supported by QueryServiceConfig2 const int bufferSize = 1024 * 8; IntPtr bufferPtr = IntPtr.Zero; ServiceRecoveryOptions recoveryOptions; ServiceController controller = null; try { // Open the service controller = new ServiceController(serviceName); uint dwBytesNeeded; // Allocate memory for struct bufferPtr = Marshal.AllocHGlobal(bufferSize); int queryResult = QueryServiceConfig2( controller.ServiceHandle.DangerousGetHandle(), SERVICE_CONFIG_FAILURE_ACTIONS, bufferPtr, bufferSize, out dwBytesNeeded); if (queryResult == 0) { throw new Win32Exception(Marshal.GetLastWin32Error(), "Unable to query the Service configuration."); } // Cast the buffer to a QUERY_SERVICE_CONFIG struct SERVICE_FAILURE_ACTIONS config = (SERVICE_FAILURE_ACTIONS)Marshal.PtrToStructure(bufferPtr, typeof(SERVICE_FAILURE_ACTIONS)); recoveryOptions = new ServiceRecoveryOptions { DaysToResetFailAcount = (int) TimeSpan.FromSeconds(config.dwResetPeriod).TotalDays, RebootMessage = config.lpRebootMsg, CommandToLaunchOnFailure = config.lpCommand }; int actionCount = config.cActions; if (actionCount != 0) { uint millisecondsToRestartService = 0; SC_ACTION[] actions = new SC_ACTION[actionCount]; for (int i = 0; i < config.cActions; i++) { SC_ACTION action = (SC_ACTION)Marshal.PtrToStructure( (IntPtr)(config.lpsaActions.ToInt32() + (Marshal.SizeOf(typeof(SC_ACTION)) * i)), typeof(SC_ACTION)); actions[i] = action; millisecondsToRestartService = action.Delay; } recoveryOptions.FirstFailureAction = GetServiceRecoveryAction(actions[0]); recoveryOptions.SecondFailureAction = GetServiceRecoveryAction(actions[1]); recoveryOptions.SubsequentFailureActions = GetServiceRecoveryAction(actions[2]); recoveryOptions.MinutesToRestartService = (int)TimeSpan.FromMilliseconds(millisecondsToRestartService).TotalMinutes; } } finally { // Clean up if (bufferPtr != IntPtr.Zero) { Marshal.FreeHGlobal(bufferPtr); } if (controller != null) { controller.Close(); } Log.Debug("Done getting service recovery options."); } return recoveryOptions; }
private static ServiceRecoveryAction GetServiceRecoveryAction(SC_ACTION action) { ServiceRecoveryAction serviceRecoveryAction = default(ServiceRecoveryAction); switch (action.Type) { case SC_ACTION_TYPE.None: serviceRecoveryAction = ServiceRecoveryAction.TakeNoAction; break; case SC_ACTION_TYPE.RestartService: serviceRecoveryAction = ServiceRecoveryAction.RestartTheService; break; case SC_ACTION_TYPE.RebootComputer: serviceRecoveryAction = ServiceRecoveryAction.RestartTheComputer; break; case SC_ACTION_TYPE.RunCommand: serviceRecoveryAction = ServiceRecoveryAction.RunAProgram; break; } return serviceRecoveryAction; }
public static ServiceRecoveryOptions GetServiceRecoveryOptions( string serviceName) { ThrowHelper.ThrowArgumentNullIfNull(serviceName, "serviceName"); ThrowHelper.ThrowArgumentOutOfRangeIfEmpty(serviceName, "serviceName"); log.Debug(m => m("Getting service recovery options...")); // 8KB is the largest buffer supported by QueryServiceConfig2 const int bufferSize = 1024 * 8; IntPtr bufferPtr = IntPtr.Zero; ServiceRecoveryOptions recoveryOptions; ServiceController controller = null; try { // Open the service controller = new ServiceController(serviceName); uint dwBytesNeeded; // Allocate memory for struct bufferPtr = Marshal.AllocHGlobal(bufferSize); int queryResult = QueryServiceConfig2( controller.ServiceHandle.DangerousGetHandle(), SERVICE_CONFIG_FAILURE_ACTIONS, bufferPtr, bufferSize, out dwBytesNeeded); if (queryResult == 0) { throw new Win32Exception(Marshal.GetLastWin32Error(), "Unable to query the Service configuration."); } // Cast the buffer to a QUERY_SERVICE_CONFIG struct SERVICE_FAILURE_ACTIONS config = (SERVICE_FAILURE_ACTIONS)Marshal.PtrToStructure(bufferPtr, typeof(SERVICE_FAILURE_ACTIONS)); recoveryOptions = new ServiceRecoveryOptions(); recoveryOptions.DaysToResetFailAcount = (int) TimeSpan.FromSeconds(config.dwResetPeriod).TotalDays; recoveryOptions.RebootMessage = config.lpRebootMsg; recoveryOptions.CommandToLaunchOnFailure = config.lpCommand; int actionCount = config.cActions; if (actionCount != 0) { uint millisecondsToRestartService = 0; SC_ACTION[] actions = new SC_ACTION[actionCount]; for (int i = 0; i < config.cActions; i++) { SC_ACTION action = (SC_ACTION)Marshal.PtrToStructure( (IntPtr)(config.lpsaActions.ToInt32() + (Marshal.SizeOf(typeof(SC_ACTION)) * i)), typeof(SC_ACTION)); actions[i] = action; millisecondsToRestartService = action.Delay; } recoveryOptions.FirstFailureAction = getServiceRecoveryAction(actions[0]); recoveryOptions.SecondFailureAction = getServiceRecoveryAction(actions[1]); recoveryOptions.SubsequentFailureActions = getServiceRecoveryAction(actions[2]); recoveryOptions.MinutesToRestartService = (int)TimeSpan.FromMilliseconds(millisecondsToRestartService).TotalMinutes; } } finally { // Clean up if (bufferPtr != IntPtr.Zero) { Marshal.FreeHGlobal(bufferPtr); } if (controller != null) { controller.Close(); } log.Debug(m => m("Done getting service recovery options.")); } return(recoveryOptions); }