I am writing a PowerShell Cmdlet in C# using Visual Studio 2015. Debugging it works fine, but I cannot rebuild the DLL until I close the PowerShell window. The DLL seems to be in use and therefore cannot be deleted (not on the command line nor using explorer). I tried remove-module. This successfully removes my Cmdlet but I still cannot delete / overwrite it.
It is very unhandy to close PowerShell, rebuild the DLL and then reopen a new PowerShell, cd to the DLL path (usually deeply nested), re-import it again, start the command to debug, and so on for every single debugging session...
Is there no better solution to unload the DLL?
Anytime I see something like this:
It is very unhandy to close the powershell, rebuild the dll and then reopen a new powershell, cd to the dll path (usually deeply nested), re-import it again, start the command to debut, and so on for every single debugging session...
I immediately think, "I should create a script to do these tasks for me".
There are solutions. You can start a second PowerShell (like another answer suggested). Another solution is to use a script to do some work for you, and to top it off, you can add this to your VS project.
Create a script in your profile to start PowerShell
function Start-DebugPowerShell
{
PowerShell -NoProfile -NoExit -Command {
function prompt {
$newPrompt = "$pwd.Path [DEBUG]"
Write-Host -NoNewline -ForegroundColor Yellow $newPrompt
return '> '
}
}
}
Set-Alias -Name sdp -Value Start-DebugPowerShell
Edit debug settings for your Cmdlet project
Start external program:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Command line arguments:
-NoProfile -NoExit -Command "Import-Module .\MyCoolCmdlet.dll"
Debug your Module
Now from Visual Studio, start debugger with F5, and you have a new PowerShell window with your Cmdlet loaded, and you can debug it however you like.
Use the 'sdp' alias from any PowerShell window
Since the Start-DebugPowerShell function is in our profile and we gave it an alias sdp, you can use this to start a second instance of PowerShell anytime you need it.
I'm afraid there is not much you can do about this behavior as far as I know. One trick is to immediately start a new PowerShell session inside your existing session before loading the DLL. Then you can exit out of the second one and you have a brand new without the DLL loaded. Just remember to start a new "secondary" session before loading it again in case you need to unload it again.
I used a helper powershell script which did most of it for me.
$module = 'AccessLogParser'
Push-Location $PSScriptroot
dotnet build -o $PSScriptRoot\output\$module\bin
Import-Module "$PSScriptRoot\Output\$module\bin\$module.dll"
$VerbosePreference = $DebugPreference="continue"
Write-Debug "$pid - $($PSVersionTable.PSVersion)"
with two options in launch config, the helper outputs the current process ID in which terminal process (bottom part of the vscode) is running, and I can select that PID in the dropdown when I launch debugger. Helpful when you want to develop something for old v5 powershell as well as v7 (pwsh.exe) version.
{
"name": ".NET Framework Attach",
"type": "clr",
"request": "attach",
"processId": "${command:pickProcess}"
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach",
"processId": "${command:pickProcess}"
}
<edit: this is now doc'd fully for pwsh and powershell.exe at https://learn.microsoft.com/en-us/powershell/scripting/dev-cross-plat/vscode/using-vscode-for-debugging-compiled-cmdlets - this doc discusses the DLL lock issue /edit>
To add to #kory-gill's answer, this is my launch.json:
{
"name": ".NET Core Launch (console)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
"cwd": "${workspaceFolder}",
"program": "pwsh",
"args": [
"-NoExit",
"-NoProfile",
"-Command",
"ipmo ${workspaceFolder}/DependencyTree/bin/Debug/netstandard2.0/DependencyTree.dll",
],
"console": "integratedTerminal",
"stopAtEntry": false
}
My project is called DependencyTree. Substitute your own project name.
The -NoProfile is important for me because my profile is large and breaks the debugger.
More generally, I have PSReadline set up, and you should too, to persist history across terminal sessions. So I can Ctrl-R and summon any command I have typed for a long way back. With that configured, the following is useful when working interactively with compiled or Powershell classes, and also when working with non-exported members of a module:
Use your keyboard shortcuts to create and delete terminals. In VS Code, terminals should be considered disposable.
$host.ExitNestedPrompt(); $Module = ipmo .\DependencyTree.psd1 -Force -PassThru; & $Module {$host.EnterNestedPrompt()}
The & $Module { ... } trick runs that scriptblock inside the module scope. Very useful for wizards ;-)
Related
I'm trying to run C# on macOS, using Sublime Text 3 on Automatic mode under:
> Tools > Build System > Automatic
and have built a system:
{
"cmd": ["csc $file && $file_base_name"],
"shell": true,
"file_regex": "^(...*?):([0-9]*):?([0-9]*)",
"selector": "source.cs",
"quiet": true
}
in Sublime Text 3/Packages/Users/CSharp.sublime-build based on this article.
I've tested with CMD+B:
using System;
class re{
public static void Main(){
Console.WriteLine("Hello world");
}
}
which returns:
/bin/sh: csc: command not found
and I'm not sure how to fix that, looked at some related posts such as this, yet can't figure it out. How do I fix that?
Other Info
$ which dotnet
/usr/local/share/dotnet/dotnet
$ dotnet --version
2.2.401
$ ls /usr/local/share/dotnet/shared/Microsoft.NETCore.App/
2.2.6
If you're using dotnet core (as it appears from your question), you need to use dotnet to execute code and not csc; that's the compiler for .NET (the nomenclature and weird namings of these things gives me a bit of a headache).
As a gross oversimplification, dotnet core uses a command named dotnet to do compilations and runs of your project, while .NET uses things like msbuild to run builds and uses csc as the underlying compiler. To use those commands you would need to install something like Mono instead (or an official MacOS version of .NET 4 or what have you, assuming such a thing exists).
The build system that I personally use for this sort of thing is:
{
"working_dir": "${folder:${project_path:${file_path}}}",
"selector": "source.cs",
"variants":
[
{
"name": "Build",
"shell_cmd": "dotnet build",
"word_wrap": false,
"quiet": true,
},
{
"name": "Clean",
"shell_cmd": "dotnet clean"
},
{
"name": "Run",
"shell_cmd": "dotnet run"
},
{
"name": "Run Interactive",
"cmd": ["dotnet", "run"],
"target": "terminus_open",
"auto_close": false,
}
],
}
This sets up a build system with several variants, allowing you to choose to build clean or run the program. If you don't choose a variant when you build, the command will fail because the top level build doesn't contain any command to build anything.
In this case that's because of the last variant that uses the Terminus package to allow for running interactive programs. Terminus only supports cmd and I prefer to use shell_cmd, so the top level build needs to have no implicit command.
An alternative to this would be to either ditch the Terminus variant or convert all of the others to use cmd instead. In that case you could move the command for the most common item (say the Run variant) to the top level instead, so that running the program is the default.
As a last note, for the build sysytem to work the presumption is that you're working in a folder where you've use the appropriate dotnet command to create an empty project. I'm not aware offhand if there's a way to execute single ad-hoc C# files using dotnet outside of that context.
try this :)
I just started a class that uses C#, but of course the instructors grades in Visual Studio..
Made the error regex myself because I cannot find any online :)
{
"cmd": [ "mcs '$file' && mono $file_base_name.exe" ],
"shell": true,
// error regex credits to Simon | github.com/mightbesimon
"file_regex": "^(..[^(]*?)\\(([0-9]*),([0-9]*)\\):? (.*)$",
"selector": "source.cs"
}
I have a problem trying to debug applications written in .NET Core in Visual Studio Code. Here is the setup:
I'm using a virtual machine running Debian 9 (with the default GUI). I've installed .Net Core SDK 2.1, and Visual Studio Code 1.30.0. Installed the extensions for C# 1.17.1. I've created simple project:
class MyProgram
{
static void Main(string[] args)
{
Console.WriteLine("Hello You Angel!");
ProcessStartInfo startInfo = new ProcessStartInfo() { FileName = "/bin/bash", Arguments = "-c nautilus /home/", };
Process proc = new Process() { StartInfo = startInfo, };
proc.Start();
}
}
If I run the program, in executes, and produces the correct output.
In the debug window I pressed the gear button to edit the launch.jason file
Here it is what it looks like:
{
"version": "0.2.1",
"configurations": [
{
"name": ".NET Core Launch (console)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/HelloWorld/bin/Debug/netcoreapp2.1/HelloWorld.dll",
"args": [],
"cwd": "${workspaceFolder}/HelloWorld",
// For more information about the 'console' field, see https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md#console-terminal-window
"console": "integratedTerminal",
"stopAtEntry": false,
"internalConsoleOptions": "openOnSessionStart",
"externalConsole": false,
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach",
"processId": "${command:pickProcess}"
}
,]
}
I've put a breakpoint in the project:
and when I hit the green triangle button, the breakpoint it not hit. Actually I think that non of the code i executed at all.
Is there something I'm missing to get this app it debugging mode?
Please help!
I was having the same issue on a different setup. Running windows 10 using VSCode and dotnet sdk 2.2.
I found a few answers browsing through gissues Here.
And This one I think fixed my problem
I also noticed to make sure I was selecting the correct "c:/projectdir/bin/debug/projectname.dll" when asked to attach the debugger to a process.
After that VSCode successfully hit my breakpoint.
I hope this helps.
1) In terminal go to your project and write
dotnet restore
dotnet clean
dotnet build
2) Check paths of "program" and "cwd" in your configurations (launch.json).
In case anyone hits this problem when they have 'converted' a Class Library project to a Console Application here are the symptoms and cause that I found:
I had mistakenly created a Class Library when I actually wanted a Console Application. I've made this same mistake in .NET Framework projects before and so thought I'll just convert it, no problem. So I altered the Output Type and gave it a Startup Object. The project ran but breakpoints were not hit.
It took me a while to find out why; it was because I'd created the original Class Library project as a .NET Standard project. When I created a new project (same code) as .NET Core (rather than .NET standard) the breakpoints were hit.
Quite interesting that you can actually switch a .NET standard Class Library project to Console Application, as it appears you can't create that setup through the UI.
I switched my project file from netcoreapp3.0 to netcoreapp2.2 and everything build fine but my breakpoints did not hit. After deleting the bin and obj directories, I got an error that the executable dll could not be found. Turned out I had to also change my launch.json file.
In .vscode/launch.json make sure to check your program folder and executable exists.
VSCode Version: 1.8.0
OS Version: Win10 x64
Steps to Reproduce:
Create a new .net core cli app using "dotnet new"
Open the folder using VS code
Add two lines of code in Program.cs
string a = Console.ReadLine();
Console.WriteLine(a);
Switch to VS code debug window and start debugging, Debug Console window shows, and displays the first "Hello, World." output, and stops on the line of Console.ReadLine(), enter anything in the Debug Console and press Enter will be given err message of "Unable to perform this action because the process is running."
The question is how and where to enter text for Console.ReadLine() to accept during debugging, if I open a new cmd.exe and do a "dotnet run" it works fine, but in Visual Studio Code Debug Console it's not working.
To read input whilst debugging, you can use the console property in your configurations in launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": ".NET Core Launch (console)",
"type": "coreclr",
"request": "launch",
"program": "${workspaceFolder}/bin/Debug/net5.0/your-project-name.dll",
"args": [],
"cwd": "${workspaceFolder}",
"stopAtEntry": false,
"console": "integratedTerminal"
}
]
}
You can either use "externalTerminal" or "integratedTerminal". The "internalConsole" doesn't appear to be working.
I use the integratedTerminal setting, as the terminal is inside VSCode itself. You will now be able to read input with Console.ReadLine();
Note: Also, internalConsole doesn't work, and it is by design. The reason this is, is because internalConsole uses the Debug Console tab to show the output of the Console.WriteLine. Since the input box in the Debug Console is used to run expression on the current stack, there's no place to pass in input that will go to Console.ReadLine. That's the reason you'll have to use something like integratedTerminal.
The screenshot below shows that the VSCode team knows this -
i am pretty new to c#-visual studio debugger...
try setting a breakpoint before your
Console.Readline()
and debug it by stepping through your code F10 (not F11).
it should stop at
Console.Readline()
and wait for your input.
I'm trying to learn how to create method libraries but whenever I run my program a little pop-up window (with a surprisingly basic Windows graphical interface, post-update) shows up with the message "PreLaunch task 'Build' terminated with exit code 1."
I click on "Show error" and in the "problems" tab I see the message "No problems in the workspace so far."
Does anyone know what's going on?
Here are my launch configurations...
launch configurations
launch configurations 2/2
Here is a screenshot of that pop-up window bearing the message.
pop-up window
Also, I'm not sure if this is related but I noticed that this stuff started happening after I moved the .NET SDK files to another folder, and also when the debugging shortcut command stopped working.
I encountered the same error after renaming my project. The problems was that in my task.json file, the arguments were referencing my previous project csproj file.
task.json (old)
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}/MyOldProject.csproj"
],
"problemMatcher": "$msCompile"
}
]
}
`
I changed the csproj file name to the current project's name it worked without any errors.
The problem might be in the tasks.json file since the error is
"PreLaunch task 'Build'" (that's in the tasks.json file).
With the latest vscode update all the warnings in the console were treated as errors and since I removed this line of configuration "problemMatcher": "$msCompile" (in tasks.json) it solved the problem for me.
In mac ensure the VSCode can detect .NET
Try doing a symbolic link.
sudo ln -s /usr/local/share/dotnet/dotnet /usr/local/bin/
Also, ensure that terminal.integrated.inheritEnv is true in VSCode settings.
In dotnet the Main() method needs to be a static. Try changing your definition from
public void main()
to
public static void Main()
and see if that helps. This microsoft doc will give you some more information https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/main-and-command-args/
There is a problem in your Launch.json, in your First Picture , in .Net Core Launch (web) section , in Program attribute, you should write the framework you are using and your project name instead of the default text.
for example netstandard2.0 and mylibrary.dll
And you can remove the web configuration if you are not going to write asp code.
Also you can delete Tasks.json because you can build and test your whole project by F5 by configuring your Launch.json like this Gist
Try to see any update is required or an extension is needed
I searched for ms-dotnettools.csharp-1.21.13
and it worked ok.
It is my first time to use Visual Studio Code IDE to create a C# program, I just follow the simple guideline to test the first case "Hello world". unfortunately, I got the same issue, so I had traced every step to look at what's wrong with me, the result was I didn't close my "Dotnet run Environment"
All my steps:
Step 1:using command line to create "Dotnet environment"
Step 2:using VS Code IDE to open this folder "MyWebsite" and I got the error message after ran it
Step 3: closing "command line" and VS Code is okay now
I have installed the preview version of Microsoft's new code editor "Visual Studio Code". It seems quite a nice tool!
The introduction mentions you can program c# with it, but the setup document does not mention how to actually compile c# files.
You can define "mono" as a type in the "launch.json" file, but that does not do anything yet. Pressing F5 results in: "make sure to select a configuration from the launch dropdown"...
Also, intellisense is not working for c#? How do you set the path to any included frameworks?
Launch.json:
"configurations": [
{
// Name of configuration; appears in the launch configuration drop down menu.
"name": "Cars.exe",
// Type of configuration. Possible values: "node", "mono".
"type": "mono",
// Workspace relative or absolute path to the program.
"program": "cars.exe",
},
{
"type": "mono",
}
Since no one else said it, the short-cut to compile (build) a C# app in Visual Studio Code (VSCode) is SHIFT+CTRL+B.
If you want to see the build errors (because they don't pop-up by default), the shortcut is SHIFT+CTRL+M.
(I know this question was asking for more than just the build shortcut. But I wanted to answer the question in the title, which wasn't directly answered by other answers/comments.)
Intellisense does work for C# 6, and it's great.
For running console apps you should set up some additional tools:
ASP.NET 5; in Powershell: &{$Branch='dev';iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/aspnet/Home/dev/dnvminstall.ps1'))}
Node.js including package manager npm.
The rest of required tools including Yeoman yo: npm install -g yo grunt-cli generator-aspnet bower
You should also invoke .NET Version Manager: c:\Users\Username\.dnx\bin\dnvm.cmd upgrade -u
Then you can use yo as wizard for Console Application: yo aspnet Choose name and project type. After that go to created folder cd ./MyNewConsoleApp/ and run dnu restore
To execute your program just type >run in Command Palette (Ctrl+Shift+P), or execute dnx . run in shell from the directory of your project.
SHIFT+CTRL+B should work
However sometimes an issue can happen in a locked down non-adminstrator evironment:
If you open an existing C# application from the folder you should have a .sln (solution file) etc..
Commonly you can get these message in VS Code
Downloading package 'OmniSharp (.NET 4.6 / x64)' (19343 KB) .................... Done!
Downloading package '.NET Core Debugger (Windows / x64)' (39827 KB) .................... Done!
Installing package 'OmniSharp (.NET 4.6 / x64)'
Installing package '.NET Core Debugger (Windows / x64)'
Finished
Failed to spawn 'dotnet --info' //this is a possible issue
To which then you will be asked to install .NET CLI tools
If impossible to get SDK installed with no admin privilege - then use other solution.
Install the extension "Code Runner". Check if you can compile your program with csc (ex.: csc hello.cs). The command csc is shipped with Mono. Then add this to your VS Code user settings:
"code-runner.executorMap": {
"csharp": "echo '# calling mono\n' && cd $dir && csc /nologo $fileName && mono $dir$fileNameWithoutExt.exe",
// "csharp": "echo '# calling dotnet run\n' && dotnet run"
}
Open your C# file and use the execution key of Code Runner.
Edit: also added dotnet run, so you can choose how you want to execute your program: with Mono, or with dotnet. If you choose dotnet, then first create the project (dotnet new console, dotnet restore).
To Run a C# Project in VS Code Terminal
Install CodeRunner Extension in your VS Code (Extension ID: formulahendry.code-runner)
Go to Settings and open settings.json
Type in code-runner.executorMap
Find "csharp": "scriptcs"
Replace it with this "csharp": "cd $dir && dotnet run $fileName"
Your project should Run in VS Code Terminal once you press the run button or ALT + Shift + N