Debug windows service in visual studio

Debugging Using Visual Studio

Starting with Windows Driver Kit (WDK)В 8, the driver development environment and the Windows debuggers are integrated into Microsoft Visual Studio. In this integrated environment, most of the tools you need for coding, building, packaging, testing, debugging, and deploying a driver are available in the Visual Studio user interface.

This feature is not available in WindowsВ 10, version 1507 and later versions of the WDK.

To get the integrated environment, first install Visual Studio, and then install the Windows Driver Kit (WDK). For more information, see Download the Windows Driver Kit (WDK).

Typically kernel-mode debugging requires two computers. The debugger runs on the host computer, and the code being debugged runs on the target computer. The target computer is also called the test computer. You can do user-mode debugging on a single computer, but in some cases you might want to debug a user-mode process that is running on a separate target computer.

In the Visual Studio environment, you can configure target computers for kernel-mode and user-mode debugging. You can establish a kernel-mode debugging session. You can attach to a user-mode process or launch and debug a user mode process on the host computer or a target computer. You can analyze dump files. In Visual Studio you can sign, deploy, install, and load a driver on a target computer.

These topics show you how to use Visual Studio to perform several of the tasks involved in debugging a driver.

How to: Debug Windows Service Applications

A service must be run from within the context of the Services Control Manager rather than from within Visual Studio. For this reason, debugging a service is not as straightforward as debugging other Visual Studio application types. To debug a service, you must start the service and then attach a debugger to the process in which it is running. You can then debug your application by using all of the standard debugging functionality of Visual Studio.

You should not attach to a process unless you know what the process is and understand the consequences of attaching to and possibly killing that process. For example, if you attach to the WinLogon process and then stop debugging, the system will halt because it can’t operate without WinLogon.

You can attach the debugger only to a running service. The attachment process interrupts the current functioning of your service; it doesn’t actually stop or pause the service’s processing. That is, if your service is running when you begin debugging, it is still technically in the Started state as you debug it, but its processing has been suspended.

After attaching to the process, you can set breakpoints and use these to debug your code. Once you exit the dialog box you use to attach to the process, you are effectively in debug mode. You can use the Services Control Manager to start, stop, pause and continue your service, thus hitting the breakpoints you’ve set. You can later remove this dummy service after debugging is successful.

This article covers debugging a service that’s running on the local computer, but you can also debug Windows Services that are running on a remote computer. See Remote Debugging.

Debugging the OnStart method can be difficult because the Services Control Manager imposes a 30-second limit on all attempts to start a service. For more information, see Troubleshooting: Debugging Windows Services.

To get meaningful information for debugging, the Visual Studio debugger needs to find symbol files for the binaries that are being debugged. If you are debugging a service that you built in Visual Studio, the symbol files (.pdb files) are in the same folder as the executable or library, and the debugger loads them automatically. If you are debugging a service that you didn’t build, you should first find symbols for the service and make sure they can be found by the debugger. See Specify Symbol (.pdb) and Source Files in the Visual Studio Debugger. If you’re debugging a system process or want to have symbols for system calls in your services, you should add the Microsoft Symbol Servers. See Debugging Symbols.

To debug a service

Build your service in the Debug configuration.

Install your service. For more information, see How to: Install and Uninstall Services.

Start your service, either from Services Control Manager, Server Explorer, or from code. For more information, see How to: Start Services.

Start Visual Studio with administrative credentials so you can attach to system processes.

(Optional) On the Visual Studio menu bar, choose Tools, Options. In the Options dialog box, choose Debugging, Symbols, select the Microsoft Symbol Servers check box, and then choose the OK button.

On the menu bar, choose Attach to Process from the Debug or Tools menu. (Keyboard: Ctrl+Alt+P)

The Processes dialog box appears.

Select the Show processes from all users check box.

In the Available Processes section, choose the process for your service, and then choose Attach.

The process will have the same name as the executable file for your service.

The Attach to Process dialog box appears.

Choose the appropriate options, and then choose OK to close the dialog box.

You are now in debug mode.

Set any breakpoints you want to use in your code.

Access the Services Control Manager and manipulate your service, sending stop, pause, and continue commands to hit your breakpoints. For more information about running the Services Control Manager, see How to: Start Services. Also, see Troubleshooting: Debugging Windows Services.

Debugging Tips for Windows Services

Attaching to the service’s process allows you to debug most, but not all, the code for that service. For example, because the service has already been started, you cannot debug the code in the service’s OnStart method or the code in the Main method that is used to load the service this way. One way to work around this limitation is to create a temporary second service in your service application that exists only to aid in debugging. You can install both services, and then start this dummy service to load the service process. Once the temporary service has started the process, you can use the Debug menu in Visual Studio to attach to the service process.

Try adding calls to the Sleep method to delay action until you’re able to attach to the process.

Try changing the program to a regular console application. To do this, rewrite the Main method as follows so it can run both as a Windows Service and as a console application, depending on how it’s started.

How to: Run a Windows Service as a console application

Add a method to your service that runs the OnStart and OnStop methods:

Rewrite the Main method as follows:

In the Application tab of the project’s properties, set the Output type to Console Application.

Choose Start Debugging (F5).

To run the program as a Windows Service again, install it and start it as usual for a Windows Service. It’s not necessary to reverse these changes.

Читайте также:  Назначение реестра windows это

In some cases, such as when you want to debug an issue that occurs only on system startup, you have to use the Windows debugger. Download the Windows Driver Kit (WDK) and see How to debug Windows Services.

How to Debug a Windows Service in Visual Studio

I am writing a C# Windows Service to manage two System Services that will help prevent Microsoft from upgrading W10AU (Anniversary Update) to W10CU (Creators Update). Recently Microsoft «made an error» and forced updates from v1607 to v17xx even if the user has a Metered Con-nection and had updates disabled or delayed or blocked.

I first wrote a simple C# service ‘CronService’ based on a tutorial. I have it working, but would like to be able to debug in VS2017. I have debugged DLLs before by loading the DLL, setting breakpoints in the code and then doing ‘Run with debug’. This is harder.

This is not as easy as it appears! If you follow the above instructions you will find all breakpoints are disabled «Breakpoint will not be hit. Symbols are not loaded.» If you look further, you will find that you have to jump thru hoops by writing another dummy service or ??

Following one of the suggestions worked for me. Instead of

you code Main() as

then add a function RunInteractive() which you can get from the above link. This method uses Reflection to invoke OnStart() and OnStop().

You still need to compile, install and start the service in the normal way. To debug, follow these steps:-

have the project open in VS2017

start cron.exe from cmd line; the service should be Running

the cmd window will say «Press any key to stop the service»

set breakpoints; they are not disabled!

you can even set a breakpoint in OnStart() and OnStop()

[>] Start with debug

breakpoints will be hit!

to stop debugging press any key in cmd window

Debugging

One of the key features of Visual Studio Code is its great debugging support. VS Code’s built-in debugger helps accelerate your edit, compile and debug loop.

Debugger extensions

VS Code has built-in debugging support for the Node.js runtime and can debug JavaScript, TypeScript, or any other language that gets transpiled to JavaScript.

For debugging other languages and runtimes (including PHP, Ruby, Go, C#, Python, C++, PowerShell and many others), look for Debuggers extensions in our VS Code Marketplace or select Install Additional Debuggers in the top-level Run menu.

Below are several popular extensions which include debugging support:

Tip: The extensions shown above are dynamically queried. Select an extension tile above to read the description and reviews to decide which extension is best for you.

Start debugging

The following documentation is based on the built-in Node.js debugger, but most of the concepts and features are applicable to other debuggers as well.

It is helpful to first create a sample Node.js application before reading about debugging. You can follow the Node.js walkthrough to install Node.js and create a simple «Hello World» JavaScript application ( app.js ). Once you have a simple application set up, this page will take you through VS Code debugging features.

Run view

To bring up the Run view, select the Run icon in the Activity Bar on the side of VS Code. You can also use the keyboard shortcut ⇧⌘D (Windows, Linux Ctrl+Shift+D ) .

The Run view displays all information related to running and debugging and has a top bar with debugging commands and configuration settings.

If running and debugging is not yet configured (no launch.json has been created), VS Code shows the Run start view.

Run menu

The top-level Run menu has the most common run and debug commands:

Launch configurations

To run or debug a simple app in VS Code, select Run and Debug on the Debug start view or press F5 and VS Code will try to run your currently active file.

However, for most debugging scenarios, creating a launch configuration file is beneficial because it allows you to configure and save debugging setup details. VS Code keeps debugging configuration information in a launch.json file located in a .vscode folder in your workspace (project root folder) or in your user settings or workspace settings.

To create a launch.json file, click the create a launch.json file link in the Run start view.

VS Code will try to automatically detect your debug environment, but if this fails, you will have to choose it manually:

Here is the launch configuration generated for Node.js debugging:

If you go back to the File Explorer view ( ⇧⌘E (Windows, Linux Ctrl+Shift+E ) ), you’ll see that VS Code has created a .vscode folder and added the launch.json file to your workspace.

Note: You can debug a simple application even if you don’t have a folder open in VS Code, but it is not possible to manage launch configurations and set up advanced debugging. The VS Code Status Bar is purple if you do not have a folder open.

Note that the attributes available in launch configurations vary from debugger to debugger. You can use IntelliSense suggestions ( ⌃Space (Windows, Linux Ctrl+Space ) ) to find out which attributes exist for a specific debugger. Hover help is also available for all attributes.

Do not assume that an attribute that is available for one debugger automatically works for other debuggers too. If you see green squiggles in your launch configuration, hover over them to learn what the problem is and try to fix them before launching a debug session.

Review all automatically generated values and make sure that they make sense for your project and debugging environment.

Launch versus attach configurations

In VS Code, there are two core debugging modes, Launch and Attach, which handle two different workflows and segments of developers. Depending on your workflow, it can be confusing to know what type of configuration is appropriate for your project.

If you come from a browser Developer Tools background, you might not be used to «launching from your tool,» since your browser instance is already open. When you open DevTools, you are simply attaching DevTools to your open browser tab. On the other hand, if you come from a server or desktop background, it’s quite normal to have your editor launch your process for you, and your editor automatically attaches its debugger to the newly launched process.

The best way to explain the difference between launch and attach is to think of a launch configuration as a recipe for how to start your app in debug mode before VS Code attaches to it, while an attach configuration is a recipe for how to connect VS Code’s debugger to an app or process that’s already running.

VS Code debuggers typically support launching a program in debug mode or attaching to an already running program in debug mode. Depending on the request ( attach or launch ), different attributes are required, and VS Code’s launch.json validation and suggestions should help with that.

Add a new configuration

To add a new configuration to an existing launch.json , use one of the following techniques:

  • Use IntelliSense if your cursor is located inside the configurations array.
  • Press the Add Configuration button to invoke snippet IntelliSense at the start of the array.
  • Choose Add Configuration option in the Run menu.

VS Code also supports compound launch configurations for starting multiple configurations at the same time; for more details, please read this section.

In order to start a debug session, first select the configuration named Launch Program using the Configuration dropdown in the Run view. Once you have your launch configuration set, start your debug session with F5 .

Alternatively you can run your configuration through the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ), by filtering on Debug: Select and Start Debugging or typing ‘debug ‘ , and selecting the configuration you want to debug.

Читайте также:  Где находиться установщик windows

As soon as a debugging session starts, the DEBUG CONSOLE panel is displayed and shows debugging output, and the Status Bar changes color (orange for default color themes):

In addition, the debug status appears in the Status Bar showing the active debug configuration. By selecting the debug status, a user can change the active launch configuration and start debugging without needing to open the Run view.

Debug actions

Once a debug session starts, the Debug toolbar will appear on the top of the editor.

  • Continue / Pause F5
  • Step Over F10
  • Step Into F11
  • Step Out ⇧F11 (Windows, Linux Shift+F11 )
  • Restart ⇧⌘F5 (Windows, Linux Ctrl+Shift+F5 )
  • Stop ⇧F5 (Windows, Linux Shift+F5 )

Tip: Use the setting debug.toolBarLocation to control the location of the debug toolbar. It can either be the default floating , docked to the Run view or hidden . A floating debug toolbar can be dragged horizontally and also down to the editor area.

Run mode

In addition to debugging a program, VS Code supports running the program. The Debug: Run (Start Without Debugging) action is triggered with ⌃F5 (Windows, Linux Ctrl+F5 ) and uses the currently selected launch configuration. Many of the launch configuration attributes are supported in ‘Run’ mode. VS Code maintains a debug session while the program is running, and pressing the Stop button terminates the program.

Tip: The Run action is always available, but not all debugger extensions support ‘Run’. In this case, ‘Run’ will be the same as ‘Debug’.

Breakpoints

Breakpoints can be toggled by clicking on the editor margin or using F9 on the current line. Finer breakpoint control (enable/disable/reapply) can be done in the Run view’s BREAKPOINTS section.

  • Breakpoints in the editor margin are normally shown as red filled circles.
  • Disabled breakpoints have a filled gray circle.
  • When a debugging session starts, breakpoints that cannot be registered with the debugger change to a gray hollow circle. The same might happen if the source is edited while a debug session without live-edit support is running.

The Reapply All Breakpoints command sets all breakpoints again to their original location. This is helpful if your debug environment is «lazy» and «misplaces» breakpoints in source code that has not yet been executed.

Optionally breakpoints can be shown in the editor’s overview ruler by enabling the setting debug.showBreakpointsInOverviewRuler :

Logpoints

A Logpoint is a variant of a breakpoint that does not «break» into the debugger but instead logs a message to the console. Logpoints are especially useful for injecting logging while debugging production servers that cannot be paused or stopped.

A Logpoint is represented by a «diamond» shaped icon. Log messages are plain text but can include expressions to be evaluated within curly braces (‘<>‘).

Just like regular breakpoints, Logpoints can be enabled or disabled and can also be controlled by a condition and/or hit count.

Note: Logpoints are supported by VS Code’s built-in Node.js debugger, but can be implemented by other debug extensions. The Python and Java extensions, for example, support Logpoints.

Data inspection

Variables can be inspected in the VARIABLES section of the Run view or by hovering over their source in the editor. Variable values and expression evaluation are relative to the selected stack frame in the CALL STACK section.

Variable values can be modified with the Set Value action from the variable’s context menu. Additionally, you can use the Copy Value action to copy the variable’s value, or Copy as Expression action to copy an expression to access the variable.

Variables and expressions can also be evaluated and watched in the Run view’s WATCH section.

Variable names and values can be filtered by typing while the focus is on the VARIABLES section

Launch.json attributes

There are many launch.json attributes to help support different debuggers and debugging scenarios. As mentioned above, you can use IntelliSense ( ⌃Space (Windows, Linux Ctrl+Space ) ) to see the list of available attributes once you have specified a value for the type attribute.

The following attributes are mandatory for every launch configuration:

  • type — the type of debugger to use for this launch configuration. Every installed debug extension introduces a type: node for the built-in Node debugger, for example, or php and go for the PHP and Go extensions.
  • request — the request type of this launch configuration. Currently, launch and attach are supported.
  • name — the reader-friendly name to appear in the Debug launch configuration dropdown.

Here are some optional attributes available to all launch configurations:

  • presentation — using the order , group , and hidden attributes in the presentation object you can sort, group, and hide configurations and compounds in the Debug configuration dropdown and in the Debug quick pick.
  • preLaunchTask — to launch a task before the start of a debug session, set this attribute to the label of a task specified in tasks.json (in the workspace’s .vscode folder). Or, this can be set to $ to use your default build task.
  • postDebugTask — to launch a task at the very end of a debug session, set this attribute to the name of a task specified in tasks.json (in the workspace’s .vscode folder).
  • internalConsoleOptions — this attribute controls the visibility of the Debug Console panel during a debugging session.
  • debugServer — for debug extension authors only: this attribute allows you to connect to a specified port instead of launching the debug adapter.
  • serverReadyAction — if you want to open a URL in a web browser whenever the program under debugging outputs a specific message to the debug console or integrated terminal. For details see section Automatically open a URI when debugging a server program below.

Many debuggers support some of the following attributes:

  • program — executable or file to run when launching the debugger
  • args — arguments passed to the program to debug
  • env — environment variables (the value null can be used to «undefine» a variable)
  • envFile — path to dotenv file with environment variables
  • cwd — current working directory for finding dependencies and other files
  • port — port when attaching to a running process
  • stopOnEntry — break immediately when the program launches
  • console — what kind of console to use, for example, internalConsole , integratedTerminal , or externalTerminal

Variable substitution

VS Code makes commonly used paths and other values available as variables and supports variable substitution inside strings in launch.json . This means that you do not have to use absolute paths in debug configurations. For example, $ gives the root path of a workspace folder, $ the file open in the active editor, and $ the environment variable ‘Name’. You can see a full list of predefined variables in the Variables Reference or by invoking IntelliSense inside the launch.json string attributes.

Platform-specific properties

Launch.json supports defining values (for example, arguments to be passed to the program) that depend on the operating system where the debugger is running. To do so, put a platform-specific literal into the launch.json file and specify the corresponding properties inside that literal.

Below is an example that passes «args» to the program differently on Windows:

Valid operating properties are «windows» for Windows, «linux» for Linux and «osx» for macOS. Properties defined in an operating system specific scope override properties defined in the global scope.

Please note that the type property cannot be placed inside a platform-specific section, because type indirectly determines the platform in remote debugging scenarios, and that would result in a cyclic dependency.

In the example below debugging the program always stops on entry except on macOS:

Global launch configuration

VS Code supports adding a «launch» object inside your User settings. This «launch» configuration will then be shared across your workspaces. For example:

Advanced breakpoint topics

Conditional breakpoints

A powerful VS Code debugging feature is the ability to set conditions based on expressions, hit counts, or a combination of both.

  • Expression condition: The breakpoint will be hit whenever the expression evaluates to true .
  • Hit count: The ‘hit count’ controls how many times a breakpoint needs to be hit before it will ‘break’ execution. Whether a ‘hit count’ is respected and the exact syntax of the expression vary among debugger extensions.

You can add a condition and/or hit count when creating a source breakpoint (with the Add Conditional Breakpoint action) or when modifying an existing one (with the Edit Condition action). In both cases, an inline text box with a dropdown menu opens where you can enter expressions:

Condition and hit count editing support is also supported for function and exception breakpoints. You can initiate condition editing from the context menu, or the new inline Edit Condition action.

An example of condition editing in the BREAKPOINTS view:

If a debugger does not support conditional breakpoints, the Add Conditional Breakpoint and Edit Condition actions will be missing.

Inline breakpoints

Inline breakpoints will only be hit when the execution reaches the column associated with the inline breakpoint. This is particularly useful when debugging minified code which contains multiple statements in a single line.

An inline breakpoint can be set using ⇧F9 (Windows, Linux Shift+F9 ) or through the context menu during a debug session. Inline breakpoints are shown inline in the editor.

Inline breakpoints can also have conditions. Editing multiple breakpoints on a line is possible through the context menu in the editor’s left margin.

Function breakpoints

Instead of placing breakpoints directly in source code, a debugger can support creating breakpoints by specifying a function name. This is useful in situations where source is not available but a function name is known.

A function breakpoint is created by pressing the + button in the BREAKPOINTS section header and entering the function name. Function breakpoints are shown with a red triangle in the BREAKPOINTS section.

Data breakpoints

If a debugger supports data breakpoints they can be set from the VARIABLES view and will get hit when the value of the underlying variable changes. Data breakpoints are shown with a red hexagon in the BREAKPOINTS section.

Debug Console REPL

Expressions can be evaluated with the Debug Console REPL (Read-Eval-Print Loop) feature. To open the Debug Console, use the Debug Console action at the top of the Debug pane or use the View: Debug Console command ( ⇧⌘Y (Windows, Linux Ctrl+Shift+Y ) ). Expressions are evaluated after you press Enter and the Debug Console REPL shows suggestions as you type. If you need to enter multiple lines, use Shift+Enter between the lines and then send all lines for evaluation with Enter . Debug Console input uses the mode of the active editor, which means that the Debug Console input supports syntax coloring, indentation, auto closing of quotes, and other language features.

Note: You must be in a running debug session to use the Debug Console REPL.

Redirect input/output to/from the debug target

Redirecting input/output is debugger/runtime specific, so VS Code does not have a built-in solution that works for all debuggers.

Here are two approaches you might want to consider:

Launch the program to debug («debug target») manually in a terminal or command prompt and redirect input/output as needed. Make sure to pass the appropriate command line options to the debug target so that a debugger can attach to it. Create and run an «attach» debug configuration that attaches to the debug target.

If the debugger extension you are using can run the debug target in VS Code’s Integrated Terminal (or an external terminal), you can try to pass the shell redirect syntax (for example » «) as arguments.

Here’s an example launch.json configuration:

This approach requires that the » preLaunchTask can be specified that is run before the individual debug sessions are started.

Compound launch configurations are displayed in the launch configuration dropdown menu.

Remote debugging

VS Code does not itself support remote debugging: this is a feature of the debug extension you are using, and you should consult the extension’s page in the Marketplace for support and details.

There is, however, one exception: the Node.js debugger included in VS Code supports remote debugging. See the Node.js Debugging topic to learn how to configure this.

Automatically open a URI when debugging a server program

Developing a web program typically requires opening a specific URL in a web browser in order to hit the server code in the debugger. VS Code has a built-in feature «serverReadyAction» to automate this task.

Here is an example of a simple Node.js Express application:

This application first installs a «Hello World» handler for the «/» URL and then starts to listen for HTTP connections on port 3000. The port is announced in the Debug Console and typically the developer would now type http://localhost:3000 into their browser application.

The serverReadyAction feature makes it possible to add a structured property serverReadyAction to any launch config and select an «action» to be performed:

Here the pattern property describes the regular expression for matching the program’s output string that announces the port. The pattern for the port number is put into parenthesis so that it is available as a regular expression capture group. In this example, we are extracting only the port number, but it is also possible to extract a full URI.

The uriFormat property describes how the port number is turned into a URI. The first %s is substituted by the first capture group of the matching pattern.

The resulting URI is then opened outside of VS Code («externally») with the standard application configured for the URI’s scheme.

Trigger Debugging via Chrome

Alternatively, the action can be set to debugWithChrome . In this case, VS Code starts a Chrome debug session for the URI (which requires that the Debugger for Chrome extension is installed). In this mode, a webRoot property can be added that is passed to the Chrome debug session.

To simplify things a bit, most properties are optional and we use the following fallback values:

  • pattern: «listening on.* (https?://\\S+|3+)» which matches the commonly used messages «listening on port 3000» or «Now listening on: https://localhost:5001».
  • uriFormat: «http://localhost:%s»
  • webRoot: «$«

Triggering an Arbitrary Launch Config

In some cases you may need to configure additional options for the Chrome debug session—or use a different debugger entirely. You can do this by setting action to startDebugging , with a name property set to the name of the launch configuration to start when the pattern is matched.

The named launch configuration must be in the same file or folder as the one with the serverReadyAction .

Here the serverReadyAction feature in action:

Next steps

To learn about VS Code’s Node.js debugging support, take a look at:

  • Node.js — Describes the Node.js debugger, which is included in VS Code.
  • TypeScript — The Node.js debugger also supports TypeScript debugging.

To see tutorials on the basics of Node.js debugging, check out these videos:

  • Intro Video — Debugging — Showcases the basics of debugging.
  • Getting started with Node.js debugging — Shows how to attach a debugger to a running Node.js process.

To learn about debugging support for other programming languages via VS Code extensions:

To learn about VS Code’s task running support, go to:

  • Tasks — Describes how to run tasks with Gulp, Grunt and Jake, and how to show errors and warnings.

To write your own debugger extension, visit:

  • Debugger Extension — Uses a mock sample to illustrate the steps required to create a VS Code debug extension.
Читайте также:  Выключить linux через время
Оцените статью