belav / csharpier

CSharpier is an opinionated code formatter for c#.
https://csharpier.com
MIT License
1.33k stars 89 forks source link

Visual Studio 2022 17.7 reformat on save isn't working #790

Closed andrewrondeau-optirtc closed 9 months ago

andrewrondeau-optirtc commented 1 year ago

I installed the Visual Studio 2022 extension, and I just can't get it to work:

(Yes, I did run "dotnet tool install -g csharpier", and yes, the tool does run from the command-line.)

image

Any suggestions to diagnose what's wrong?

belav commented 1 year ago

@andrewrondeau-optirtc there should hopefully be an error message showing the problem under Output | Show output from: CSharpier. Turning on the debug logging option can also help troubleshoot any errors.

image

There have been some problems with the extension not successfully installing CSharpier to a custom location. The workaround if this is another edge case the extension can't yet handle is to close VS, delete the folder at C:\Users\{CurrentUser}\AppData\Local\CSharpier, and then try it again.

andrewrondeau-optirtc commented 1 year ago

Here's the debug output:

(Note that I removed some of my paths from the log. I can't paste my paths and private source code filenames in a public location.)

Starting Ensure there is a csharpier process for C:\Users\AndrewRondeau\git\opti\[Sanitized] Looking for C:\[Sanitized]\.config/dotnet-tools.json [Sanitized] (It looked in every parent directory of a file until...) Looking for C:\.config/dotnet-tools.json Unable to find dotnet-tools.json, falling back to running dotnet csharpier --version dotnet csharpier --version output: 0.21.0 Exception while running 'dotnet csharpier --version' in C:\Users\AndrewRondeau\AppData\Local\CSharpier\0.21.0 Exception: System.ComponentModel.Win32Exception (0x80004005): The system cannot find the file specified at System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo) at CSharpier.VisualStudio.ProcessHelper.ExecuteCommand(String command, String arguments, Dictionary2 environmentVariables, String workingDirectory) at CSharpier.VisualStudio.CustomPathInstaller.EnsureVersionInstalled(String version) The tool package could not be restored. Tool 'csharpier' failed to install. This failure may have been caused by:

For more reasons, including package naming enforcement, visit https://aka.ms/failure-installing-tool

Adding new version 0.21.0 process for C:\Users\AndrewRondeau\git\opti\OptiRTC.Products\ProcessInitiation\DataManipulation Exception: System.ComponentModel.Win32Exception (0x80004005): The system cannot find the file specified at System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo) at CSharpier.VisualStudio.CSharpierProcessPipeMultipleFiles..ctor(String csharpierPath, Logger logger) at CSharpier.VisualStudio.CSharpierProcessProvider.SetupCSharpierProcess(String directory, String version)

`

I can confirm that CSharpier works from the command line: image

I tried deleting C:\Users{CurrentUser}\AppData\Local\CSharpier (via a rename to _CSharpier) and it didn't fix the problem.

belav commented 1 year ago

@andrewrondeau-optirtc from the stack trace, it sounds like the plugin is failing to run this command with a file not found exception

dotnet csharpier --version

It could be that C:\Program Files\dotnet\ is in your individual user path environment variable, but not in the system path environment variable. I'm not sure if Visual Studio would be running the command as your user or not.

Assuming this is the issue, I believe I can modify the plugin to detect it and supply a warning indicating the problem.

andrewrondeau-optirtc commented 1 year ago

C:\Program Files\dotnet\ is in my system PATH

belav commented 1 year ago

It looks like I have some logging that isn't quite correct which led me astray, I think the real problem is actually the failure of

The tool package could not be restored.
Tool 'csharpier' failed to install. This failure may have been caused by:

You are attempting to install a preview release and did not use the --version option to specify the version.
A package by this name was found, but it was not a .NET tool.
The required NuGet feed cannot be accessed, perhaps because of an Internet connection problem.
You mistyped the name of the tool.
For more reasons, including package naming enforcement, visit https://aka.ms/failure-installing-tool

That failure is coming from when the plugin is trying to run this command.

dotnet tool install csharpier --version 0.21.0 --tool-path C:\Users\AndrewRondeau\AppData\Local\CSharpier\0.21.0

Are you able to run the command yourself?

andrewrondeau-optirtc commented 1 year ago
dotnet tool install csharpier --version 0.21.0 --tool-path C:\Users\AndrewRondeau\AppData\Local\CSharpier\0.21.0
You can invoke the tool using the following command: dotnet-csharpier
Tool 'csharpier' (version '0.21.0') was successfully installed.

After that, I re-enabled the csharpier extension and it now works.

belav commented 1 year ago

hmmm, maybe VS didn't have permissions to install itself? I'm going to leave this open so I can hopefully modify the extension to detect when it can't install csharpier, and let the user know how to work past it themselves.

Insadem commented 1 year ago

I had the same issue, fixed by manualy installing it through command. I glad that I checked this issue first, but otherwise I thought this extension is dead... However Visual Studio told me that CSharpier must be installed before formatting, I clicked "Install Global", but nothing changed. Each restart it was asking to install it.

Jammer-hammer commented 1 year ago

I have a very similar problem.

I did not have any Csharpier folders in appdata. When i check the Output log for for Cshapier, after clicking install i get ["INFO" - 10:52:43 AM] Initializing csharpier-vscode

and nothing else. Then when I open a Text file or try to format a C# text file: ["ERROR" - 10:54:19 AM] CSharpier was not found so files may not be formatted.

and the popup about CSharpier needs to be installed to support formatting files When i clock install globally or locally: ["INFO" - 10:55:23 AM] Installing csharpier globally with dotnet tool install -g csharpier

I tried running several commands from Powershell: dotnet tool install -g csharpier PS C:\Users\jha> dotnet tool install csharpier --version 0.24.2 --tool-path C:\Users\jha\AppData\Local\CSharpier\0.24.2

I get the following error:

C:\Users\jha\AppData\Local\Temp\2286cf84-ffa9-4603-8e6b-8e481e2097eb\restore.csproj : error NU1100: Unable to resolve '
csharpier (>= 0.0.0)' for 'net6.0'.
C:\Users\jha\AppData\Local\Temp\2286cf84-ffa9-4603-8e6b-8e481e2097eb\restore.csproj : error NU1100: Unable to resolve '
csharpier (>= 0.0.0)' for 'net6.0/any'.
The tool package could not be restored.
Tool 'csharpier' failed to install. This failure may have been caused by:

* You are attempting to install a preview release and did not use the --version option to specify the version.
* A package by this name was found, but it was not a .NET tool.
* The required NuGet feed cannot be accessed, perhaps because of an Internet connection problem.
* You mistyped the name of the tool.

For more reasons, including package naming enforcement, visit https://aka.ms/failure-installing-tool

I have tried both not6.0 and net7.0. I have tried reinstalling VS code, Csharpier, .net but to no avail.

belav commented 1 year ago

@Jammer-hammer I'm curious what is in the C:\Users\jha\AppData\Local\Temp\2286cf84-ffa9-4603-8e6b-8e481e2097eb folder, maybe that is a temporary folder nuget is using to install csharpier. Otherwise maybe try deleting it and seeing if somehow it is interfering.

Does running dotnet tool install csharpier -g cause the same error about the restore.csproj file?

You could also try installing older versions, maybe the nuget cache on your machine has something cached that is invalid.

Jammer-hammer commented 1 year ago

I did try installing older versions, and did also try the dotnet tool install csharpier -g.

What ultimately worked for me, was clearing the NuGet cache, as described in answer 1.2 on this post .

BenjaBobs commented 1 year ago

My VS (17.7.0 Preview 2.0) is also not formatting on save. EDIT: it did work in v 17.7.0 Preview 1.0, so maybe they changed or broke something in the latest VS?

It's configured like this: image

And debug logs look like this: image

If I do a manual Reformat With CSharpier command, it formats no issues.

Moving the dotnet-tools.json to the .config folder made CSharpier find the config file, but it still doesn't format on save.

Ccry11 commented 1 year ago

Also on 17.7.0 Preview 4.0 the "Format on save" doesn't work

belav commented 1 year ago

I reproduced the problem with the 17.7 preview. Added some extra debug logging, tested, and it worked. Removed the debug logging, recompiled the extension in 17.7 preview with no changes, installed the vsix and it worked. So.... I released that version as 1.4.2 even though there are no actual code changes. Let me know if that also solves the issue for you @Ccry11 @BenjaBobs

BenjaBobs commented 1 year ago

Amazing, I'll try it first thing tomorrow at work!

BenjaBobs commented 1 year ago

It appears to be working now! Thanks a lot!

Ccry11 commented 1 year ago

Hi @belav, thank you for the fast response to this issue. I tried to build the CSharpier.VisualStudio from VS 2022 preview and then install the CSharpier.VisualStudio.vsix generated in the /bin/debug or /bin/release but unfortunately on my VS installation, even doing this with the source code of the v.1.4.2, it doesn't work. Of course I have checked and enabled the Reformat on save setting in both global and solution scope. With VS 2022 non-preview the format on save works as expected. Before building the vsix I have removed the extension from both VS preview and non-preview installation

BenjaBobs commented 1 year ago

It stopped working at my end again. Currently running VS 17.7.0 Preview 3.0 and Csharpier extension 1.4.2.

liri2006 commented 1 year ago

Hello @belav Thank you for this amazing tool!

I've just updated Visual Studio 2022 to 17.7.0 and Reformat on save stopped working (it was working fine before on the old version). I've tried reinstalling extension multiple times (also deleting Csharpier folder from AppData), but wasn't able to make it work. It does format if clicking the option in right-click menu.

Some logs: image

belav commented 1 year ago

I was hoping this was just a preview bug, but if it is it made it into the release. I figured out that the IVsRunningDocTableEvents3.OnBeforeSave method is not being called, but there is a newer IVsRunningDocTableEvents7.OnBeforeSaveAsync that does get called. The documentation claims that VS will fall back to the old interface but that doesn't seem to be happening anymore.

I still want to do some testing, but I should have a fix for this out shortly

liri2006 commented 1 year ago

@belav I've updated to the new version (1.4.3) and it still does not format on save :( I've also tried uninstalling/deleting csharpier folder from AppData/installing, but no success.

image

belav commented 1 year ago

@liri2006 Maybe this is more of a VS/dotnet/something weird on your machine issue, because CSharpier isn't doing anything special to trigger an event on save. Could you try one of these to see if they work? https://marketplace.visualstudio.com/items?itemName=SteveCadwallader.CodeMaid https://marketplace.visualstudio.com/items?itemName=WinstonFeng.FormatonSave

And the relevant code so I don't have to go looking again. https://github.com/codecadwallader/codemaid/blob/dev/CodeMaidShared/Integration/Events/RunningDocumentTableEventListener.cs https://github.com/tifish/VSFormatOnSave/blob/master/VSFormatOnSaveShared/VsRunningDocTableEventsHandler.cs

liri2006 commented 1 year ago

@belav It is a bit funny, but after installing those extensions Csharpier starts working on save :D

So I don't know what is going on here, but at least I have a workaround now :D

Girildo commented 1 year ago

I'm also running the same version of the extension (1.4.3) with VS 17.7.0 and format on save does not work. Funnily, @liri2006 's workaround with the FormatOnSave extension worked for me, too.

Hau-Hau commented 1 year ago

Hi, run into same issue. Format on save stopped working after VS update or CSharpier update, not exactly sure.

belav commented 1 year ago

I've opened a request on the VS dev community, because it seems like this is probably a VS problem - https://developercommunity.visualstudio.com/t/IVsRunningDocTableEvents3-not-reliably-w/10450735?

lpatrickvezina commented 1 year ago

On my end, the Format on save was working perfectly and stopped working when I upgraded VS from 17.7.2 => 17.7.3.

lpatrickvezina commented 1 year ago

I was able to get it working but not sure exactly what cause to make it work 😃 I did the following:

After applying that, I can see in CSharpier logs that it is running when I save.

belav commented 1 year ago

Microsoft got back to me asking for a Trace of the issue occurring, which lead me to realizing I didn't try to verify if my OnSave code was being triggered when format on save was not working... and it was not.

Long story short, I figured out the DTE.Documents was throwing exceptions while the extension was trying to figure out which file to format, but this only occurred after I build the VISX and installed it. Launching the extension through VS it worked fine. I am assuming that some of these "fixes" get DTE.Documents into a state that it no longer throws exceptions.

I modified the extension to first see if the active document is the one that is being saved, which should bypass the issue most of the time. 1.4.6 has that fix. Hopefully Microsoft can provide me some guidance on the problem with DTE.Documents. Sorry I didn't dig into this more sooner! I assume it has been a bit frustrating to not have format on save available.

BenjaBobs commented 1 year ago

Don't worry, we always had fallback to cli, and our build pipeline is set up to complain if the formatting was not up to CSharpier standard, so it wasn't too big of a hassle. :)

Thanks for your work, I just installed the newest version, and it appears to work! 🚀

liri2006 commented 1 year ago

I've updated the extension and it works. Thanks a lot for the fix!

BlueInt32 commented 1 year ago

I updated the extension to 1.4.6, it worked once on save, then I got this exception and it stopped working :

Starting
Exception: System.Runtime.InteropServices.COMException (0x8000000A): The data necessary to complete this operation is not yet available. (Exception from HRESULT: 0x8000000A)
   at EnvDTE.Documents.Item(Object index)
   at CSharpier.VisualStudio.ReformatWithCSharpierOnSave.FindDocument(UInt32 docCookie)
belav commented 1 year ago

@BlueInt32 I have another fix 1.4.7, it eats those exceptions after logging them which is what I meant to do. I believe that exception should only happen if the non-active document is being saved.

Microsoft did let me know yesterday that they believe 17.8 preview 2 fixes the exception that the csharpier plugin is running into. I have yet to verify that.

pvginkel commented 12 months ago

I'm running 17.4 and I kept getting the error message "CSharpier was not found so files may not be formatted". I think my issue isn't the same as what this thread is about, but I did find this thread, so I'd like to contribute this if someone else has the same issue. The problem for me was that after installing CSharpier globally, "dotnet-csharpier" couldn't be found in the command line. I believe the problem is that I installed Visual Studio using a different account on this machine and that that caused some issues. I solved my issue by going into "Edit environment variables for your account", confirming that there was an entry for "%USERPROFILE%.dotnet\tools" and just OK -> OK out of the screen. This seemed to resolve my issue. After that, "dotnet-csharpier" ran successfully from the command prompt and CSharpier integration in Visual Studio worked again.

shocklateboy92 commented 12 months ago

@belav, should we update our extension so that it tries to run dotnet csharpier instead of dotnet-csharpier?

That should run as long as dotnet is installed in the path.

pvginkel commented 12 months ago

@shocklateboy92 don't on my behalf :). I tried that before fixing the PATH configuration and it didn't work either. My setup was just completely broken I think.

belav commented 12 months ago

@belav, should we update our extension so that it tries to run dotnet csharpier instead of dotnet-csharpier?

That should run as long as dotnet is installed in the path.

The plugins only use dotnet when trying to figure out the version of csharpier installed or when trying to install it. Once it is installed to a custom location it runs the dotnet-csharpier in the context of the directory it is installed in. On windows at least, there is dotnet-csharpier.exe in that directory. It looks like when you install a global tool that same exe ends up in %USERPROFILE%.dotnet\tools, which explains why dotnet-csharpier works from any location. @pvginkel I'm not exactly clear on why "%USERPROFILE%.dotnet\tools" would affect the plugin, but I'm glad you figured it out.

In any case, the plugin needs to account for multiple versions if you are using a manifest file for csharpier. And in the case of using the global version, because the plugin keeps csharpier running in the background it would prevent someone from updating csharpier while they had their IDE open. I ran into that early on and it wasn't obvious what the problem was.

belav commented 9 months ago

I believe a number of issues with the VS extension are resolved now with the 1.5.0 version.