How to start both Angular app and WebApi service from VSCode on F5 or Ctrl+F5 - visual-studio-code

I have top-level folder Homepage with the following structure:
--Homepage
----Client <- Angular app, created with `ng new` command
----Server <- .NET Core WebApi, created with `dotnet new webapi` command
I open VSCode at Homepage level:
I have these extensions installed:
Question
If I want to use single VSCode environment to work on both projects, Client and Server, is it possible to bind F5 (or Ctrl+F5) to start both projects together?
Client app I start using ng serve (it will run on http port 4200)
Server app I start using dotnet run (it will run on https port 5001)
I have just one common .vscode folder on Homepage (root level):
By default, when first created, the content of launch.json was this:
{
// Use IntelliSense to find out which attributes exist for C# debugging
// Use hover for the description of the existing attributes
// For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
"version": "0.2.0",
"configurations": [
{
"name": ".NET Core Launch (web)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/Server/bin/Debug/netcoreapp2.1/Server.dll",
"args": [],
"cwd": "${workspaceFolder}/Server",
"stopAtEntry": false,
"internalConsoleOptions": "openOnSessionStart",
"launchBrowser": {
"enabled": true,
"args": "${auto-detect-url}",
"windows": {
"command": "cmd.exe",
"args": "/C start ${auto-detect-url}"
},
"osx": {
"command": "open"
},
"linux": {
"command": "xdg-open"
}
},
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"sourceFileMap": {
"/Views": "${workspaceFolder}/Views"
}
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach",
"processId": "${command:pickProcess}"
}
,]
}
So, when I press F5 it builds and start the Server app, the page opens at https://localhost:5001, from there I can navigate to https://localhost:5001/api/values and see WebApi works.
But the Client app doesn't start at all.
So, I thought if I add Debugger for Chrome extension's settings to launch.json, it should work, so I clicked on Add Configuration and added corresponding section:
{
"type": "chrome",
"request": "launch",
"name": "Launch Chrome",
"url": "http://localhost:4200",
"webRoot": "${workspaceFolder}"
},
I changed port from 8080 to 4200, since ng serve hosts on port 4200
But it does not start the Client app.
Please advice. Thanks

I have similar (node.js for API) and spent quite some times couldn't resolved, for example use && or &. Result is either API up or Angular up, never the both.
Anyway I finally realized have both Api and UI in the same folder/project/solution is not practical. An API is not specific to an UI, it's a universal DLL/service, should be siting somewhere by itself. So I separated them into two diff folders and have 2 VSC instances to run them:
start the API in debug mode
in 2nd VSC, run ng serve and let it take time to build
when ng says "Compiled successfully" go to launch.json to start the debug entry associated with Chrome
they work perfectly.

Related

VSCode - How to specify which project to debug - Azure Functions

My question is a noobie question.
I have an azure function app project, along with a test project. Initially, I start with just the function application project and then I just recently re-org the project folders and added the associated test.csproj
The folder structure I have right now looks like this:
Since moving the function app into the "src" folder, when I want to just run locally, I make sure that from my powershell terminal, I do the following:
cd src
func start
And everything works really well. But if I want to step through the code / debug, hitting F5 doesn't work because it doesn't know which project I'm trying to debug.
Can you tell me how I can debug either project from the parent folder that I'm in ?
I've tried to change my launch.json from this:
{
"version": "0.2.0",
"configurations": [
{
"name": "Attach to .NET Functions",
"type": "coreclr",
"request": "attach",
"processId": "${command:azureFunctions.pickProcess}"
}
]
}
To this:
{
"version": "0.2.0",
"configurations": [
{
"name": "FunctionApp",
"type": "coreclr",
"request": "attach",
"processId": "${command:azureFunctions.pickProcess}",
"program": "${workspaceFolder}/src/bin/Debug/net6.0/bin/widgets.dll",
"cwd": "${workspaceFolder}/src"
}
]
}
And now I see a Green play button with the name "FunctionApp" in my "Run and Debug" bar across the top, but when I try to run it, I get an error that says:
Executing task: C:\Program Files\dotnet\dotnet.exe clean /property:GenerateFullPaths=true /consoleloggerparameters:NoSummary <
Microsoft (R) Build Engine version 17.0.0+c9eb9dd64 for .NET Copyright
(C) Microsoft Corporation. All rights reserved.
MSBUILD : error MSB1003: Specify a project or solution file. The
current working directory does not contain a project or solution file.
The terminal process "C:\Program Files\dotnet\dotnet.exe 'clean',
'/property:GenerateFullPaths=true',
'/consoleloggerparameters:NoSummary'" terminated with exit code: 1.
Terminal will be reused by tasks, press any key to close it.
EDIT 1
I tried to follow this example:
https://i.stack.imgur.com/a7ZVk.png
I also changed all references in my task.json from "process" to "shell" based on this post: Debugging Azure Function with vscode
So presently, this is what the two files look like:
launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "Attach to .NET Functions",
"type": "coreclr",
"request": "attach",
"processId": "${command:azureFunctions.pickProcess}"
}
]
}
tasks.json
Just showing what I understand is the relevant section...
{
"version": "2.0.0",
"tasks": [
{
"label": "host function",
"command": "func host start",
"type": "shell",
"options": {
"cwd": "${workspaceFolder}/src"
}
},
But the error I'm getting is this:
Failed to detect running Functions host within "60" seconds. You may
want to adjust the "azureFunctions.pickProcessTimeout" setting.
When I try Run -> Start with debugging, the application starts, and I can trigger my API... but it doesn't stop at any of the breakpoints.
So the complete solution was to
a) Revert my launch.json back to the original version which looks like this:
{
"version": "0.2.0",
"configurations": [
{
"name": "Attach to .NET Functions",
"type": "coreclr",
"request": "attach",
"processId": "${command:azureFunctions.pickProcess}"
}
]
}
b) added new section to my tasks.json:
{
"label": "host function",
"command": "func host start",
"type": "shell",
"options": {
"cwd": "${workspaceFolder}/src"
}
},
c) Then I changed ALL references to "process" to "shell" in the tasks.json.
d) Lastly, to fix the error with azureFunctions.pickProcessTimeout, I did the following:
File -> Preferences -> Settings -> search for the specific setting and increased from 60 seconds to 180

Debug FastAPI application in VSCode

i'm trying to debug an application (a web api) that use FastAPI (uvicorn)
I'm also using poetry and set the projev virtual environment in vscode.
i read this tutorial to setup uvicorn and this one to setup vscode but i think i'm doing something wrong in set it up.
I tried to setup the launch.json both as python: module and python: current file
The problem seems that it doesn't recognize the project structure cause when i run the debug it stopped in an import statement with this error:
Exception has occurred: ImportError
attempted relative import with no known parent package
This is my current launch.json configuration:
"configurations": [
{
"name": "Python: local debug",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/src/topic_service/service/__init__.py",
"args" : ["--port", "8000"]
},
]
I also tried to add a .env file setting PYTHONPATH:
PYTHONPATH=.:${PYTHONPATH}
Locally i run the application as follow:
poetry run uvicorn src.main:app --port 8080 --reload
Does anyone know how to correctly setup vscode to debug an uvicorn application?
Thank you
UPDATE:
I also tried what this article says. the debugger seems to start but nothing happen (no breakpoint is triggered)
Try this configuration.
{
"name": "Python: Module",
"type": "python",
"request": "launch",
"module": "uvicorn",
"args": ["src.main:app","--reload"]
}
Likewise you provide uvicorn module with necessary args during development of FastAPI application, you need to configure your launch.json located in .vscode directory with respective values.
I did a write up for custom project configurations to debug FastAPI in VS Code here
Suppose you issue the following command to run FastAPI on uvicorn server with args mentioned as below
uvicorn main:app --reload --port 8000
then your launch.json should have module with value of uvicorn and each of the args separated by space as items of the args array.
"module": "uvicorn",
"type": "python",
"request": "launch",
"args": [
"main:app",
"--reload",
"--port",
"8000"
],
"env": {
"usersecret": "some$Ecret",
}
You can have this launch.json file in .vscode and then modify the args array in the JSON configuration as per your project structure.
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python: FastAPI",
"type": "python",
"request": "launch",
"module": "uvicorn",
"env": {
"db_username": "postgres",
"db_password": "secret",
"host_server": "localhost",
"database_name": "fastapi",
"ssl_mode": "prefer",
"db_server_port": "5432"
},
"args": [
"main:app",
"--reload",
"--port",
"8000"
]
}
]
}
For me worked with this configurations:
On Debug section on VSCode, choose create launch.json option. Probally it will open launch.json on .vscode folder in your root folder explorer
like this, inside of launch.json put this:
"version": "0.2.0",
"configurations": [
{
"name": "Python: FastAPI",
"type": "python",
"request": "launch",
"module": "uvicorn",
"cwd": "${workspaceFolder}/<folder to your main.py>",
"args": [
"main:app",
"--reload",
"--port", //these arg are optional
"3003"
]
}
]
}
Now , just run your debugger and have a nice day!
Edit: The cwd ensure that your debbuger will find the right path to your main.py file. So, for whos use multiple debuggers or uses outside vsCode with launch.json it's a nice choice use it.
The quick and easy way: launch debugger F5 and then select FastAPI Debug Configuration:
(p.s. this works on the VSCode Insiders; haven't tried it on a regular version)
The way i debug is quite basic, hope it helps
i have .py file with this config:
import uvicorn
from app.main import api
if __name__ == "__main__":
dev = 1
if dev==0:
#use this one
uvicorn.run(api, host="127.0.0.1", port=5000, log_level="info")
if dev == 1:
#or this one
uvicorn.run('app.main:api', host="127.0.0.1", port=5000, log_level="info", reload=True, debug=True)
if dev == 2:
uvicorn.run('app.main:api', host="127.0.0.1", port=5000, log_level="info", workers=2)
and run the file with the vscode debugger, the important thing is to run the app with the debug flag because otherwise the debugger skips the breakpoints (at least in my case)

Remote debugging C++ with VsCode

I have gdbserver attached to a process and working fine on a remote machine, port 9999. On my local machine, from command line:
$ gdb
(gdb) target remote localhost:9999
works just fine. I am trying to configure Vs Code debugger so that I can have a GDB frontend for this case. Here is my launch JSON.
"version": "0.2.0",
"configurations": [
{
"name": "GDB",
"type": "cppdbg",
"request": "attach",
"miDebuggerServerAddress": "localhost:9999",
"program": "path-to-cross-compiled-binary-with-same-debug-symbols",
"linux": {
"MIMode": "gdb",
},
}
]
There are couple of issues here. First of all, why "program"? In this case, gdb doesn't need any program name to start. Program is already running on remote, gdbserver is already attached to it. I just want gdb client to connect to port 9999. But anyways, moving on.
It wants me to give a processId. This also does not make sense, I am already attached on remote. The fun part is:
If you leave out processId, Vs Code says "unable to parse the process id"
If you specify a processId, Vs Code says "processId cannot be used with miDebuggerServerAddress"
Of course, if I am using a debugger server address, server is already attached to PID and it makes sense that processId can't be used in this case. But if I leave it out, VS Code gives the 1. error. This is cyclic in a way.
Anyone is able to attach to a remote process in VS Code C++ debugger with gdbserver address, that is my question. What is wrong with my launch file?
You need to use the "launch" request instead of "attach". I also needed to add the default "cwd" option.
"request": "launch",
"cwd": "${workspaceFolder}",
You may also need to define "additionalSOLibSearchPath".
My launch config now looks like this:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
// "processId": "${command:pickProcess}",
"name": "(gdb) Remote Attach",
"type": "cppdbg",
"request": "launch",
"program": ".\\src\\binaryfolder\\app.nostrip",
"additionalSOLibSearchPath": "arm-none-linux-gnueabi/libc/lib;./lib;C:\\DeviceSDK\\win-2.8.15\\sdk\\toolchains\\arm-4.4.1\\arm-none-linux-gnueabi\\libc\\lib;C:\\DeviceSDK\\win-2.8.15\\sdk\\platforms\\201205\\lib",
// "processId": "${command:pickProcess}",
"MIMode": "gdb",
"cwd": "${workspaceFolder}",
"miDebuggerPath": "C:\\DeviceSDK\\win-2.8.15\\sdk\\toolchains\\arm-4.4.1\\bin\\arm-none-linux-gnueabi-gdb.exe",
"miDebuggerServerAddress": "192.168.205.88:51000",
"miDebuggerArgs": " -ex 'handle all print nostop noignore'",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true,
}
]
},
]
}
See CppTools issue 321

Visual Studio Code Task is Prepending the working directory to the command

I'm trying to setup visual studio code for rust to do debugging. In my launch.json file I have
{
"version": "0.2.0",
"configurations": [
{
"name": "(Windows) Launch",
"type": "cppvsdbg",
"request": "launch",
"program": "${workspaceRoot}/target/debug/vscode-rust-debug-example.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceRoot}",
"environment": [],
"externalConsole": true,
"preLaunchTask": "localcargobuildtask"
}
]
}
and in my tasks.json I have
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "localcargobuildtask",
"command": "echo hi",
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
Where "echo hi" is in my tasks I eventually want to have something like "cargo build" or "cargo test" or whatever. But this is just a starting step.
But when I press F5 the output I get is
> Executing task: C:\programs\VSCodeWorkspaces\RustProjects\vscode-rust-debug-example-debug-config-included\echo hi <
The terminal process terminated with exit code: 2
Terminal will be reused by tasks, press any key to close it.
Rather than running "echo" from where ever the terminal finds it (working directory first, then check global path variable like you would expect) it is actually looking for a program named "echo" in my root folder of the workspace.
How do I tell visual studio code "No I don't want you to run workspace/echo, I want you to run echo in workspace" ? Or is there another more direct way to tell visual studio code "compile this before you debug it" ?
The answer to this question How to debug Rust unit tests on Windows?
suggests that changing
"command": "cargo build",
into
"command": "cargo",
"args": [
"build"
],
in the tasks.json file works and somehow it does. Maybe the editor is configured to search the %path% for single word commands, or maybe some plugin I installed overwrote the "cargo" command. Maybe the reason echo wasn't found is because it is a terminal command, not a program. Maybe the error message was a lie and it was only reporting that it couldn't find workspacefolder\command despite checking %path%? Or maybe none of that. I have no idea. It is some pretty idiosyncratic behavior.

Terminate another task from within a postDebugTask - VS Code

I have a debug launch configuration (launch.json) like below.
{
"version": "0.2.0",
"configurations": [
{
"name": "Current TS File",
"type": "node",
"request": "launch",
"preLaunchTask": "Pre Debug Task",
"postDebugTask": "Stop Watch Styles",
"args": ["${relativeFile}"],
"runtimeArgs": ["--nolazy", "-r", "ts-node/register"],
"sourceMaps": true,
"cwd": "${workspaceRoot}",
"protocol": "inspector",
}
]
}
My tasks configuration (tasks.json) is like
{
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "next:copy",
"label": "Copy Files",
"problemMatcher": []
},
{
"type": "npm",
"script": "styles:tsw",
"label": "Watch Styles",
"problemMatcher": [],
},
{
"label": "Pre Debug Task",
"isBackground": true,
"dependsOn" :[
"Copy Files",
"Watch Styles"
]
},
{
"label": "Stop Watch Styles",
// No sure what should come here
}
]
}
Trying to stop watch process in postDebugTask, is there a way to Terminate Task by providing name (Watch Styles) as parameter in tasks.json. Watch styles is a continuously running process, please suggest if there is any other approach to terminate a task after debugging is complete.
This will terminate all tasks after debug stops
Or in this case, just build_runner watch...
launch.json
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Flutter",
"request": "launch",
"type": "dart",
"flutterMode": "debug",
"preLaunchTask": "flutter: build_runner watch",
"postDebugTask": "Terminate All Tasks"
}
]
}
tasks.json
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "Terminate All Tasks",
"command": "echo ${input:terminate}",
"type": "shell",
"problemMatcher": []
}
],
"inputs": [
{
"id": "terminate",
"type": "command",
"command": "workbench.action.tasks.terminate",
"args": "terminateAll"
}
]
}
More info here: https://code.visualstudio.com/docs/editor/variables-reference#_command-variables
This works for me:
{
"label": "postdebugKill",
"type": "process",
"command":[
"${command:workbench.action.tasks.terminate}",
"${command:workbench.action.acceptSelectedQuickOpenItem}",
],
},
The first "${command:workbench.action.tasks.terminate}" will bring up a panel asking you to select which task to terminate. So if you had multiple running tasks and wanted to choose one you would use this command only.
The second "${command:workbench.action.acceptSelectedQuickOpenItem}" will terminate the selected task in that panel mentioned above. (So you will not even see the terminate panel.) If you have only one running task when you call the postdebugKill task, it will be selected automatically and thus terminated. Otherwise whichever task is listed first will be terminated. Again, if you have more than one other task running and you want to select which to terminate don't include this second command.
I don't know of any way to list, perhaps via an args option a label name for which task to terminate if running. It would be nice to have this functionality.
[postdebugKill name can be whatever you want.]
To call a postdebug task your launch.json config might look like this:
{
"type": "node",
"request": "launch",
"name": "Gulp: serve",
"program": "${workspaceFolder}/node_modules/gulp/bin/gulp.js",
"args": [
"serve"
],
// "preLaunchTask": "someTask",
"postDebugTask": "postdebugKill"
},
Upon stopping that "Gulp: serve" debugging session, the task "postdebugKill" will be triggered. And so if I had used the "preLaunchTask" to start a task or had simply started a task running before launching the "Gulp: serve" debugging session - that preLaunchTask would be terminated.
The ability to run vscode commands in a task was recently added to vscode. Some minimal info here: using a command in a task doc.
[I'll add another answer because the new additional info is extensive.]
It seems there is an issue with running a preLaunchTask and then launching a debugging session. See particularly debugging does not work on first try. It appears to be fixed though in an insiders edition and may be released in early February 2019. terminal not sending onLineData.
In the meantime there is a suggested fix within one of the issues that I have lost the link to and that is a problemMatcher which will signal to the debugger that the dependent tasks have completed.
In my watching task I used this:
"problemMatcher": [
{
"base": "$tsc-watch",
"background": {
"activeOnStart": true,
"beginsPattern": "Using gulpfile ~\\OneDrive\\experimental\\gulpfile.js",
"endsPattern": "Starting 'watch'..."
}
}
],
I chose that because when I manually start the gulp:watch task I get this in the terminal:
[22:27:48] Using gulpfile ~\OneDrive\experimental\gulpfile.js
[22:27:48] Starting 'watch'...
[22:27:48] Starting 'watch'...
So you see the start and end pattern there that I copied (with extra escaping).
I suggest that you separately run your "Pre Debug Task" and copy the start and ending output into your "Pre Debug Task" problemMatcher and see if it now works.
My code in the first answer I believe is correct, I just wasn't using "isBackground" and "dependsOn" as you are. But I have added "isBackground" to mine and the problemMatcher option and it works flawlessly now.
Hopefully, this will be fixed in the next February 2019 release and there will be no need for this workaround.
If on Linux or macOS, a less hacky solution that just works is using pkill. If on Windows, see below.
First run the task and find the full command vscode runs for that task, with $ ps -af
Then use pkill + the full command in a postDebugTask.
I have an entry in tasks.json like this:
{
"label": "stop npm:watch",
"type": "shell",
"command": "pkill -f 'sh -c node ./scripts/watch.js'",
"presentation": {
"reveal": "silent",
"panel": "dedicated",
"close": true,
}
}
'sh -c node ./scripts/watch.js' is how vscode runs my npm:watch task.
The presentation properties prevent this task from taking focus or taking up terminal space after it finishes successfully.
Then you reference that task in a launch.json configuration:
{
...
"preLaunchTask": "npm:watch",
"postDebugTask": "stop npm:watch",
...
}
If the full command contains changing parameters (paths, port numbers, etc.), you can use a part of the command or regex.
e.g.: I could have probably matched with './scripts/watch.js' or 'node.*watch'.
For Windows: you can make this work by substituting pkill for taskkill.
If you want to support both Unix and Windows, you can make a script that does one or the other depending on the underlying OS.