public void GetDataServer_ReturnsDataComputerStatus() { var service = new WindowsService(null, null); var data = service.GetDataServer(); Assert.NotNull(data); }
protected override void OnSourceInitialized(EventArgs e) { base.OnSourceInitialized(e); var hwnd = new WindowInteropHelper(this).Handle; WindowsService.SetWindowExTransparent(hwnd); }
/// <summary> /// Maintains the aspect ratio of <see cref="ImageWindow.Image"/> /// <para></para> /// Using <see cref="WindowsService.ShowWindowContentWhileDraggingIsEnabled"/> determines the approach in keeping the aspect ratio in order to minimize flickering while resizing /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void AssociatedObjectSizeChangedMaintainAspectRatio(object sender, SizeChangedEventArgs e) { if (sender is ImageWindow window) { double aspectRatio = window.Image.Source.Width / window.Image.Source.Height; if (WindowsService.ShowWindowContentWhileDraggingIsEnabled()) { window.Height = e.NewSize.Height; window.Width = e.NewSize.Height * aspectRatio; } else { double percentWidthChange = Math.Abs(e.NewSize.Width - e.PreviousSize.Width) / e.PreviousSize.Width; double percentHeightChange = Math.Abs(e.NewSize.Height - e.PreviousSize.Height) / e.PreviousSize.Height; if (percentWidthChange > percentHeightChange) { window.Height = e.NewSize.Width / aspectRatio; } else { window.Width = e.NewSize.Height * aspectRatio; } } } }
public static void Start(string[] args) { using (WindowsService service = new WindowsService()) { ServiceBase.Run(service); } }
public void StartIfNotRunning_StartsTheWindowsService() { StopService(WindowsService.MongoDB); WindowsService.StartIfNotRunning(WindowsService.MongoDB); Assert.That(IsTestServiceRunning(WindowsService.MongoDB), Is.True); }
public CommandSet() { _resetEvent = new ManualResetEvent(false); _daemon = new MyServiceDaemon(new SimpleLogger(), _resetEvent); var config = new WindowsServiceConfiguration("aa1") { CommandLineArguments = "windows-service --start" }; _service = new WindowsService(_daemon, config); }
private bool FailureActionsChanged(WindowsService service) { if (this.Template.OnFirstFailure != null && this.Template.OnFirstFailure != service.FailureActions.Actions.Cast <ServiceControllerAction?>().FirstOrDefault()?.Type) { return(true); } if (this.Template.OnSecondFailure != null && this.Template.OnSecondFailure != service.FailureActions.Actions.Cast <ServiceControllerAction?>().Skip(1).FirstOrDefault()?.Type) { return(true); } if (this.Template.OnSubsequentFailures != null && this.Template.OnSubsequentFailures != service.FailureActions.Actions.Cast <ServiceControllerAction?>().Skip(2).FirstOrDefault()?.Type) { return(true); } if (this.Template.OnFailureProgramPath != null && this.Template.OnFailureProgramPath != service.FailureActions.Command) { return(true); } if (this.Template.RebootMessage != null && this.Template.RebootMessage != service.FailureActions.RebootMessage) { return(true); } if (this.Template.RestartDelay != null && this.Template.RestartDelay != service.FailureActions.ResetPeriod) { return(true); } return(false); }
private static bool ConsoleCloseCheck(ControlSignalType ctrlType) { _forceClosed = true; // Set the flag incase the user pressed Ctrl+C or break etc, exit the main thread if (_pipeProxy == null) { return(true); // We are already shutdown } Log.WriteSystemEventLog("MCEBuddy engine app shutting down", EventLogEntryType.Information); Console.WriteLine("\r\n\n\n\nStopping..."); try { if (_pipeProxy != null) { _pipeProxy.StopBySystem(); } } catch { } try { if (_host != null) { _host.Abort(); // incase we are in faulted state with some resource being held otherwise close takes a long time } } catch { } _pipeProxy = null; // We are done here, free to start another engine _host = null; Console.WriteLine("\r\nStopped"); // Restart the the Windows we stopped earlier Log.WriteSystemEventLog("Trying to start MCEBuddy engine service.", EventLogEntryType.Information); WindowsService.StartService(GlobalDefs.MCEBUDDY_SERVICE_NAME); Log.WriteSystemEventLog("MCEBuddy engine app shutdown complete.", EventLogEntryType.Information); return(true); }
public async static Task MainAsync(string[] args) { var host = new Host(); // pass this command line option to run as a windows service if (args.Contains("--run-as-service")) { using (var windowsService = new WindowsService(host)) { ServiceBase.Run(windowsService); return; } } Console.Title = host.EndpointName; var tcs = new TaskCompletionSource <object>(); Console.CancelKeyPress += (sender, e) => { e.Cancel = true; tcs.SetResult(null); }; await host.Start(); await Console.Out.WriteLineAsync("Press Ctrl+C to exit..."); await tcs.Task; await host.Stop(); }
private void OnWindowsServiceStart(string[] args) { if (Arguments == null) { Arguments = new ServiceArguments(args); CurrentApplicationInfo.Init(ServiceName, Arguments.InstanceName, InfraVersion); } try { if (Arguments.ServiceStartupMode != ServiceStartupMode.WindowsService) { throw new InvalidOperationException($"Cannot start in {Arguments.ServiceStartupMode} mode when starting as a Windows service."); } if (Environment.UserInteractive == false) { throw new InvalidOperationException( "This Windows service requires to be run with 'user interactive' enabled to correctly read certificates. " + "Either the service wasn't configure with the 'Allow service to interact with desktop' option enabled " + "or the OS is ignoring the checkbox due to a registry settings. " + "Make sure both the checkbox is checked and following registry key is set to DWORD '0':\n" + @"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Windows\NoInteractiveServices"); } WindowsService.RequestAdditionalTime(60000); OnStart(); } catch { WindowsService.ExitCode = 1064; // "An exception occurred in the service when handling the control request." (net helpmsg 1064) throw; } }
private void UpdateNames() { foreach (var w in Windows) { w.Name = WindowsService.GetWindowName(w.HWnd); } }
public void AppStartup(object sender, StartupEventArgs e) { _bootstrapper.Initialize(); var windowService = new WindowsService(); windowService.ShowDialog(new ShellViewModel(), "Hai....."); }
private void Error(string function) { int error = Marshal.GetLastWin32Error(); string message; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, null, (uint)error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), out message, 0, 0); WindowsService.WriteLog(string.Format("Error in {0}: {1} ({2})", function, message, error)); }
public void ExecuteWindowsService() { var ws = new WindowsService(); var _eventHandle = new MyEventWaitHandler(false, EventResetMode.AutoReset, "WindowsApplicationMode"); ws.Execute(_eventHandle); _eventHandle.Set(); }
public Service() { _Service = AppDomain.CurrentDomain.GetData("FairburnWindowsService") as WindowsService; string connectionString = AppSettings.GetString("AgentTemplateDbConnectionString"); int commandTimeoutSeconds = AppSettings.GetInt32("AgentTemplateDbCommandTimeoutSeconds", 30); _Db = new DatabaseConnection(connectionString, commandTimeoutSeconds); }
private static void StartInteractive() { var svc = new WindowsService(); var host = new ConsoleHost(svc); host.Run(); Console.WriteLine("Press <ENTER> to exit."); Console.ReadLine(); }
internal WindowsServiceAttribute GetAttribute(WindowsService service) { var attribute = service.GetType().GetAttribute<WindowsServiceAttribute>(); if (attribute != null) return attribute; _logger.Error(Strings.EXCEPTION_ServiceMustBeMarkedWithAttribute, service.GetType().FullName); throw new ArgumentException(string.Format(Strings.EXCEPTION_ServiceMustBeMarkedWithAttribute, service.GetType().FullName)); }
public string FindLatipiumDir(string user) { if (IsService) { IntPtr accessToken = AccessToken; try { IntPtr path; uint error = SHGetKnownFolderPath(KNOWNFOLDERID.RoamingAppData, 0, accessToken, out path); switch (error) { case S_OK: try { string dir = Path.Combine(Marshal.PtrToStringAuto(path), "latipium"); Directory.CreateDirectory(dir); string username; string domain; if (GetUser(accessToken, out username, out domain)) { NTAccount account = new NTAccount(domain, username); DirectorySecurity acl = Directory.GetAccessControl(dir); if (!acl.GetAccessRules(true, true, typeof(NTAccount)).OfType <FileSystemAccessRule>() .Any(r => r.IdentityReference == account && r.FileSystemRights == FileSystemRights.FullControl && r.AccessControlType == AccessControlType.Allow)) { acl.AddAccessRule(new FileSystemAccessRule(account, FileSystemRights.FullControl, AccessControlType.Allow)); } Directory.SetAccessControl(dir, acl); } return(dir); } finally { Marshal.FreeCoTaskMem(path); } case E_FAIL: WindowsService.WriteLog("Error in SHGetKnownFolderPath: Unspecified failure (2147500037)"); break; case E_INVALIDARG: WindowsService.WriteLog("Error in SHGetKnownFolderPath: One or more arguments are not valid (2147942487)"); break; default: WindowsService.WriteLog(string.Format("Error in SHGetKnownFolderPath: ({0})", error)); break; } } finally { CloseHandle(accessToken); } return(null); } else { string dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "latipium"); Directory.CreateDirectory(dir); return(dir); } }
public static void Main(string[] args) { var ws = new WindowsService(); var command = new RootCommand(ws.Console); var engine = new CommandEngine(command); ws.Start(args); engine.Run(args); }
public string GetWindowsServiceFolderPath(WindowsService service, bool useDebugFolderIfDevelopmentInstallation) { var path = EwlStatics.CombinePaths(generalInstallationLogic.Path, service.Name); if (runtimeConfiguration.InstallationType == InstallationType.Development) { path = EwlStatics.CombinePaths(path, EwlStatics.GetProjectOutputFolderPath(useDebugFolderIfDevelopmentInstallation)); } return(path); }
public bool GetFreeLanServiceStatus() { WindowsService freeLanService = windowsServices.GetServiceByName("FreeLAN Service"); if (freeLanService == null) { return(false); } return(freeLanService.Status == ServiceControllerStatus.Running); }
private ICommand Initialize_CloseAppCommand() { return(new DelegateCommand(() => { if (selectedwindow != null) { WindowsService.Close(selectedwindow.HWnd); } })); }
/// <summary> /// Creates and configures a service. /// </summary> public static void Example_CreateService() { // // Ensure the registry key exists. // var Service = WindowsService.FromServiceName("mydriver"); Service.CreateRegistryKey(); // // Write values to the service's registry key. // Service.WriteRegistryValue("ImagePath", $"System32\\drivers\\mydriver.sys"); Service.WriteRegistryValue("Type", 1); Service.WriteRegistryValue("ErrorControl", 1); Service.WriteRegistryValue("Start", 1); Service.WriteRegistryValue("Group", "System Reserved"); Service.WriteRegistryValue("DisplayName", $"@mydriver.inf,%mydriver_ServiceDesc%;Custom Example Driver", RegistryValueKind.ExpandString); Service.WriteRegistryValue("Owners", new[] { $"mydriver.inf" }); Service.WriteRegistryValue("DependOnService", new[] { "myotherdriver" }); // // Writes values to a sub-key of the service's registry key. // Service.WriteRegistryValue("Parameters\\MyCustomParameter", 69); // // Start the service as a kernel driver. // var KernelService = WindowsServiceKernel.FromService(Service); var ReturnStatus = KernelService.TryStartDriver(); if (ReturnStatus == 0x00000000 || ReturnStatus == 0xC000010E /* DRIVER_ALREADY_STARTED */) { // // The service has started. // We will now stop it. // KernelService.TryStopDriver(); } Console.WriteLine($"[*] CreateService: 0x{ReturnStatus:X8}"); // // Delete the registry key. // Service.DeleteRegistryKey(); }
public void WindowsServiceHandler() { var request = new WindowsService { ServiceName = "Dhcp" }; //new WindowsServiceMonitor().Handle(request); Assert.AreSame(State.Ok, request.State); }
public WindowsServiceObject(WindowsService service) { this.CanStop = true; this.CanShutdown = true; this.CanPauseAndContinue = false; this.AutoLog = true; this.ServiceName = service.Name; this.Svc = service; }
private ICommand Initialize_PlaceAppNormalCommand() { return(new DelegateCommand(() => { if (selectedwindow != null) { selectedwindow.OnTop = false; WindowsService.RemoveFromTop(selectedwindow.HWnd); } })); }
internal ServiceMetadata GetMetadata(WindowsService service) { var attribute = GetAttribute(service); return new ServiceMetadata { Service = service, Quiet = false, ServiceName = attribute.ServiceName, Silent = false }; }
private void serviceInstaller_AfterUninstall(object sender, InstallEventArgs e) { //MessageBox.Show("Called After Uninstall"); //Stop the service if running WindowsService.StopService(engineName, 10000); //Delete the installation directory completely to avoid any artifacts string installPath = Context.Parameters["TARGETDIR"].Replace(@"\\", @"\").Trim(); DeleteDirectory(installPath); }
/// <summary> /// Initialize a new instance of the <see cref="SettingsSecurityUserControlViewModel"/> class. /// </summary> internal SettingsSecurityUserControlViewModel() { if (!IsInDesignMode) { _windowsService = ServiceLocator.GetService <WindowsService>(); } _settingProvider = new ServiceSettingProvider(); InitializeCommands(); Messenger.Default.Register <Message>(this, MessageIdentifiers.RaisePropertyChangedOnAllSettingsUserControl, RaiseAllPropertyChanged); }
private void RefreshWindowsEnumeration() { List <WindowInformation> windowsinformationupdated = new List <WindowInformation>(); WindowsService.EnumerateWindows((wi) => { windowsinformationupdated.Add(wi); if (WindowsService.IsLastWindow(wi.HWnd)) { UpdateList(windowsinformationupdated); } }); }
private ICommand Initialize_PlaceAppOnTopCommand() { return(new DelegateCommand(() => { if (selectedwindow != null) { lastWindowOnTop = selectedwindow; selectedwindow.OnTop = true; WindowsService.Focus(selectedwindow.HWnd); WindowsService.SetOnTop(selectedwindow.HWnd); } })); }
private void OnMoveToEnabledButton(object sender, RoutedEventArgs e) { int indexToMove = ListBoxWindowsServicesOff.SelectedIndex; if (indexToMove == -1) { return; } WindowsService item = windowsServicesDisabled[indexToMove]; MoveFromDisabledToEnabled(item); }
/// <summary> /// Main entry point of the application /// </summary> static void Main( string[ ] args ) { if ( !Environment.UserInteractive ) { using ( var service = new WindowsService( ) ) { ServiceBase.Run( service ); } } else { Start( args ); } }
/// <summary> /// Determines whether the specified service is installed on the specified machine. /// </summary> /// <param name="machineName">Name of the machine.</param> /// <param name="service">The service.</param> /// <returns> /// True if the service is installed, otherwise False. /// </returns> public static bool IsServiceInstalled(string machineName, WindowsService service) { LoggingUtils.WriteInfo("Checking if Service is Installed", "Machine Name", machineName, "Service", service.ToString()); string serviceName = service.ToString(); ServiceController[] serviceControllers = string.IsNullOrEmpty(machineName) ? ServiceController.GetServices() : ServiceController.GetServices(machineName); foreach (ServiceController serviceController in serviceControllers) { if (serviceController.ServiceName == serviceName) { return true; } } return false; }
public static bool StartService(WindowsService service, string[] args) { LoggingUtils.WriteInfo("Starting Service", "Name", service.ToString()); string serviceName = service.ToString(); // Get a list of all running services ServiceController[] serviceControllers = ServiceController.GetServices(); foreach (ServiceController serviceController in serviceControllers) { if (serviceController.ServiceName == serviceName) { // If specified service is not already running if (serviceController.Status != ServiceControllerStatus.Running) { try { // Start the service, optionally passing parameters if (args != null) serviceController.Start(args); else serviceController.Start(); // Wait up to 5 minutes for service to start serviceController.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 5, 0)); return (serviceController.Status == ServiceControllerStatus.Running); } catch { return false; } } return true; } } return false; }
public ServiceRunner(WindowsService windowsService) { _windowsService = windowsService; }
/// <summary> /// Main entry point of the application /// </summary> static void Main( string[ ] args ) { FileTarget baseLogTarget = LogManager.Configuration.FindTargetByName( "BaseLog" ) as FileTarget; if ( baseLogTarget != null ) { baseLogTarget.FileName = baseLogTarget.FileName.Render( new LogEventInfo { TimeStamp = DateTime.Now } ); } if ( !Environment.UserInteractive ) { using ( var service = new WindowsService( ) ) { ServiceBase.Run( service ); } } else { Start( args ); } }
public static bool StopService(WindowsService service) { LoggingUtils.WriteInfo("Stopping Service", "Name", service.ToString()); string serviceName = service.ToString(); // Get a list of all running services ServiceController[] serviceControllers = ServiceController.GetServices(); foreach (ServiceController serviceController in serviceControllers) { if (serviceController.ServiceName == serviceName) { // If specified service is running if (serviceController.Status == ServiceControllerStatus.Running) { try { // Stop service and wait up to 2 minutes for termination serviceController.Stop(); serviceController.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 2, 0)); return (serviceController.Status == ServiceControllerStatus.Stopped); } catch { return false; } } break; } } return true; }
/// <summary> /// Starts the specified service. /// </summary> /// <param name="service">The service.</param> /// <returns>True if successful, otherwise False.</returns> public static bool StartService(WindowsService service) { return StartService(service, null); }
public abstract ServiceHarness WrapService(WindowsService service);
public override ServiceHarness WrapService(WindowsService service) { return ServiceHarness.WrapService(service); }