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"
}
Related
I am new to DotnetCore and MS programming. With the new push from MS to be more platform neutral, I had an interest in me to try it out and see if it works the way it promises. That said, I have had problem even getting a helloworld program work on DotNetCore on windows from VSCode. Everything seems to work fine on my command prompt and VisualStudio 2019, my mac's VS Studio for mac. Real strain seems to be on VSCode in Windows 10. I'd appreciate all your help, if you can
The error I receive is "Cannot find debug adapter for type coreclr". No matter what I do, I end up with this error.
1. INstalled Dotnet core 3.0
2. Set up MSBuildSDKsPath env variable that points to C:\Program Files\dotnet\sdk\3.0.100\Sdks
3. Restarted machine as many times
Nothing works. Here's the sample code as well as my launch.json.
using System;
namespace OOPExample
{
public struct Dimensions {
public double Length { get; }
public double Width { get; }
public Dimensions(double length, double width) {
Length = length;
Width= width;
}
public double Diagonal => Math.Sqrt(Length * Length + Width * Width);
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine($"Hello World - {new Dimensions(10.0, 15.0).Diagonal}");
}
}
}
Here's my launch.json
{
// 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 (console)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/bin/Debug/netcoreapp3.0/OOPExample.dll",
"args": [],
"cwd": "${workspaceFolder}",
// For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
"console": "internalConsole",
"stopAtEntry": false
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach",
"processId": "${command:pickProcess}"
}
]
}
When I execute dotnet build and dotnet run from command prompt, everything is fine
dotnet build:
C:\Users\Krishnan\Projects\DotNet\OOPExample> dotnet build
Microsoft (R) Build Engine version 16.3.0+0f4c62fea for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.
Restore completed in 12.86 ms for C:\Users\Krishnan\Projects\DotNet\OOPExample\OOPExample.csproj.
OOPExample -> C:\Users\Krishnan\Projects\DotNet\OOPExample\bin\Debug\netcoreapp3.0\OOPExample.dll
Build succeeded.
0 Warning(s)
0 Error(s)
Time Elapsed 00:00:00.77
dotnet run:
PS C:\Users\Krishnan\Projects\DotNet\OOPExample> dotnet run
Hello World - 18.027756377319946
If you are wondering how I created this project, it was nothing more than a simple
dotnet new console command. So nothing fancy
Maybe this can help someone having this problem: Twice in the past week I have resolved this error.
First time by uninstalling/re-installing the OmniSharp C# extension.
Second time by updating VSCode to latest.
I haven't figured out if the two things are related, but I don't see anything in OmniSharp or VSC release notes about it specifically.
first of all, ensure that you had install official Microsoft C# extension for vs-code.
then, if still doesn't run it would be a problem with your launch.json file.
The following error message appeared when I tried to start debugging.
"Cannot find debug adapter for type 'coreclr'".
If the following error message was appearing too, like in my case, I'd recommend you to also consider to click on "Developer Tools" because I think there's a very good chance that you would be able to get a good hint there.
"Extension host terminated unexpectedly".
In the box of the above message, I clicked "Developer Tools" and then I could see some error messages containing a string "kite" that made me guess that, in my case, these error messages could've been coming from the extension "kite" that I had installed a long time ago. After disabling this extension and restarting VS Code, neither error message appeared again. (Now I'm not sure if restarting was essential.) I'm not saying that the extension kite is troublesome. In your case, the problem could've been coming from some other extensions or something other than an extension. I'm saying that the "Developer Tools" could be a goldmine of hints.
I've one more piece of happy news. Later on, these error messages didn't appear even after enabling this extension "kite". I could start debugging without giving up this extension.
I was getting OPs error message, but only when using Run & Debug with ".NET Core Launch (web)" configuration in a Dev Container:
Couldn't find a debug adapter descriptor for debug type 'coreclr' (extension might have failed to activate)
I noticed in VS Code's Output tab, on the C# console, the following additional output:
Installing C# dependencies...
Platform: linux, x86_64, name=ubuntu, version=20.04
Downloading package 'OmniSharp for Linux (x64)'
Retrying from 'https://roslynomnisharp.blob.core.windows.net/releases/1.37.8/omnisharp-linux-x64-1.37.8.zip'
Failed at stage: downloadPackage
Error: Failed to establish a socket connection to proxies: ["PROXY 127.0.0.1:8118"]
It seems that the Dev Container picks up the HTTP_PROXY and HTTPS_PROXY environment variables from the host but, being a guest container, its 127.0.0.1 address is different than the host computer's 127.0.0.1 address.
I fixed this by way of Windows-Pause > Advanced System Settings > Advanced > Environment Variables... > with the host computer's "public" IP address as returned from ipconfig /all, e.g.:
HTTP_PROXY = http://192.168.0.111:8118/
HTTPS_PROXY = http://192.168.0.111:8118/
Followed by closing and reopening VS Code, with Run & Debug now working as expected in the Dev Container.
I had the same problem, I just uninstalled the Omnisharp and all extensions from dotnet, closed the VSCode and after reopened it, and install everything again(package Omnisharp). Now is working as expected.
Just to let registered my SO is Linux Ubuntu 20.04.
I had my share of this debug error today. The following steps I took to resolve the issue might be helpful to someone.
Uninstalled "C# for Visual Studio Code (powered by OmniSharp)" and then installed it back.
Closed Visual Studio Code
Restarted VS Code
Launched the debug button
I hope this is helpful!
I was also getting same error after running dotnet clean
-i simply closed vscode
-then open vscode
-dotnet restore
-dotnet build
my error solved
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.
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 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 ;-)
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