Check if application was started from within Visual Studio debug session - visual-studio

I am working on an application that installs a system wide keyboard
hook. I do not want to install this hook when I am running a debug
build from inside the visual studio (or else it would hang the studio
and eventually the system), and I can avoid this by checking if the
DEBUG symbol is defined.
However, when I debug the release version of the application, is
there a way to detect that it has been started from inside visual
studio to avoid the same problem? It is very annoying to have to
restart the studio/the computer, just because I had been working on
the release build, and want to fix some bugs using the debugger having
forgotten to switch back to the debug build.
Currently I use something like this to check for this scenario:
System.Diagnostics.Process currentProcess = System.Diagnostics.Process.GetCurrentProcess();
string moduleName = currentProcess.MainModule.ModuleName;
bool launchedFromStudio = moduleName.Contains(".vshost");
I would call this the "brute force way", which works in my setting, but I would like to know whether there's another (better) way of detecting this scenario.

Try: System.Diagnostics.Debugger.IsAttached

For those working with Windows API, there's a function which allows you to see if any debugger is present using:
if( IsDebuggerPresent() )
{
...
}
Reference: http://msdn.microsoft.com/en-us/library/ms680345.aspx

Testing whether or not the module name of the current process contains the string ".vshost" is the best way I have found to determine whether or not the application is running from within the VS IDE.
Using the System.Diagnostics.Debugger.IsAttached property is also okay but it does not allow you to distinguish if you are running the EXE through the VS IDE's Run command or if you are running the debug build directly (e.g. using Windows Explorer or a Shortcut) and then attaching to it using the VS IDE.
You see I once encountered a problem with a (COM related) Data Execution Prevention error that required me to run a Post Build Event that would execute editbin.exe with the /NXCOMPAT:NO parameter on the VS generated EXE.
For some reason the EXE was not modified if you just hit F5 and run the program and therefore AccessViolationExceptions would occur on DEP-violating code if run from within the VS IDE - which made it extremely difficult to debug. However, I found that if I run the generated EXE via a short cut and then attached the VS IDE debugger I could then test my code without AccessViolationExceptions occurring.
So now I have created a function which uses the "vshost" method that I can use to warn about, or block, certain code from running if I am just doing my daily programming grind from within the VS IDE.
This prevents those nasty AccessViolationExceptions from being raised and thereby fatally crashing the my application if I inadvertently attempt to run something that I know will cause me grief.

Related

Debugging Custom SSIS Task

I'm trying to develop my first custom SSIS task. I've got two instances of SSDT open -- one for building and debugging the task, and the other that uses the custom task. Then in the first instance, I use the Attach to Process function from the Debug menu to debug the code. That all works fine but my trouble is that each time I rebuild the task and register it in the GAC from the first instance, I have to close and reopen the second instance of SSDT. If I don't, the second instance seems to still use the previous build of my custom task. Is there some way besides closing/reopening Data Tools that will cause it to recognize the new build of the custom task? All the closing/reopening is getting exhausting.
While it has been a decade since I last built any custom components for SSIS, the work cycle is as you describe it.
The best bit of of advice I'd offer is to add post-build steps to your development process to GAC the DLL. Oh, and modify your Visual Studio shortcut to include /nosplash to eliminate the startup splash screen.

Visual Studio 2017 locking files

Visual Studio Version 15.2 (26430.6) Release.
Having recently updated to the above version I am running into continuous issues with VS locking up files when trying to build.
Could not copy "obj\Debug\projHype.dll" to "bin\Debug\projHype.dll". Exceeded retry count of 10. Failed.
Also tried running VS2017 with and with out admin priveledges
I tried the suggestions for older versions of visual studio but to no avail. Any ideas how to get around this?
For anyone encountering this. Updating to version 26430.12 will resolve this. Looks like the previous release contained a bug.
While there may be other causes, testhost.exe and testhost.x86.exe can both result in a lock that prevents the build from completing. The symptoms are bewildering-- the test explorer churns indefinitely, sometimes timeout warnings appear in the build. Sometimes the files cannot be accessed even after VS is shut down.
If you are using nUnit or another test framework, make sure that test discovery does not encounter any infinite loops or crashes in your code. If this happens, it can hang the testhost executable. For example, if you use nUnit TestCase or TestCaseSource, if any of these perform an action that can hang, lock up, or crash, they will be invoked before the tests are executed.
This is the tricky bit-- your tests haven't run yet, but your code can lock up VS! While this may not be your problem, if you have unit test discovery in any way, check that it all completes.
One way to make sure all discovery completes is to use the functions from a test itself, and disable them as a TestCase or TestCaseSource (or equivalent in other test frameworks). If the test hangs or crashes, that's the culprit.
For me it helped to run the program again with accepting "run last successful build". After the run, the locks were gone.

VS2010 F5 is available but Ctrl F5 is invalid

I encountered a hell problem when I attempted to invoke “LoadLibrary” in C# environment. The application was crashed when I pressed “Ctrl + F5” and entered the directly running environment, but it was certainly O.K. if I pressed “F5” entering the debug mode. I tried to directly run the application, it had the same errors. There are some test projects in attach files, I thought that it was enough describing the issue. How did I solve it?
Ps: The solution’s environment must be set to “Debug” and the compile form must be “X64”, then the ConsoleApplication2 project is “Startup project”.
I tried to use the “LibraryEssential” project to invoking the “MathmaticPower” function which was in “MathmaticLibrary” project. But my C# project “ConsoleApplication2” loaded “LibraryEssential” dll file by “PInvoke LoadLibrary”.
Some improvements: I tried to run the C# exe application in "Administrator", It's O.K., but I run it with other user, it's failed! Shall I must run the application in administrator role? I don't want to do so. Have any other ways for the issue?
attach files: LoadLibrary.zip

VS10 debugger error: Test host process exited unexpectedly

I have been having some problems with the test debugger in VS10. All tests are running without error, but when debugging it aborts when I try to read the object data. Afterwards, this error is displayed in the summary: Test host process exited unexpectedly.
I'm unable to see anymore details about the error. How do I access/generate test-log files? Or, even better: Has anyone experienced a similar problem? And found a solution?
Additional information:
The runtime-test-data is available on objects from same libary assembly, it's just one class I can't get access to in runtime mode. If I use breakpoints at:
every line that affects the object: - I can see the runtime-data and the test passes
only one place: - the test will abort and no data is visible
no breakpoints: - the test runs and passes.
The test used to work fine until recently. Just before the problem occurred when I made some solution changes with dividing the projects into solution folders. I didn't make any changes that should affect the code. Moving the projects back to their original folder don't solve the problem, So I wonder - Is this a bug in Visual Studio itself?
Here is what I've tried so far:
Rebuilding and cleaning the solution.
Closing Visual Studio and rebooting my system.
Installing VS10 Service Pack 1
Reinstalling Visual Studio 10
Testing on VS10 Ultimate and Premium
Removing and regenerating solutions files
Removing all break points
TraceAndTestImpact/Local.testsettings: Testing Timeout > timeout and setting abort to 30 minutes.
TraceAndTestImpact/Local.testsettings: Unit Test > Assembly folders defined
TraceAndTestImpact/Local.testsettings: Deployment > Enable deployment directories and files
How can I fix this? Any suggestions are welcome.
What's most likely happening here is that a property, local which is being evaluated in the locals or autos window is causing a side effect in the running process which leads to the failure. To verify this you should turn off automatic property evaluation
Tools -> Options
Go to the Debugger menu
Uncheck "Enable Property evaluation and other implicit function calls"
Solution:
It had overridden ToString, and as it showed out, there was a loop i forgot to close.
After altering ToSting everything works fine.
Thank you very much for the answers :)
I was getting a similar issue, however in my case ALL tests were being skipped, and the error was reproducible on an empty test project, so code was ruled out.
Checking the EventViewer led me to the cause in my case; somehow the C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\QTAgent32.exe.config file had been removed from my machine?!? I copied one from another machine here and I'm back in action.
I was finally able to resolve this issue in my case. What was happening for me was I was running asynchronous threads, but closed a process using a synchronous Close() method for a powershell runspace rather than the asynchronous CloseAsync() method.

Why do I get "file is used by another process" errors when I debug within Visual Studio?

Using Visual Studio 2010 beta, when I run my application within the IDE for debugging, it works perfectly the first time. However, after closing the debug session, either by closing the application or clicking the stop debugging button, all subsequent attempts to debug the application fail with:
Error 1 Unable to copy file "obj\Debug\Application.dll"
to
"bin\Debug\Application.dll".
The process cannot access the file
'bin\Debug\Application.dll'
because it is being used by another
process.
Handle.exe from SysInternals does show handles open, but even if I close the handles, the error doesn't go away. Any attempts to delete the file manually result in an "Access Denied" error message.
To fix this, I have to completely restart Visual Studio, afterwhich the Debug session will work once and stop again.
I'm not entirely sure when this started happening, but I'm pretty sure it's fairly recently.
UPDATE: After I force close the handles on Application.dll, I get the following error from VS:
Error 1 Unable to copy file
"obj\Debug\Application.dll"
to
"bin\Debug\Application.dll".
The requested operation cannot be
performed on a file with a user-mapped
section open.
What the heck is a "user-mapped section"??
UPDATE 2: It appears that this problem occurs when I have a Form open in Design view when trying to debug. I'm going to do some more troubleshooting and then post my results.
UPDATE 3: I think I've narrowed it down to a form using a UserControl.
To be honest with you, it sounds like a bug in VS2010. For some reason it isn't closing the open handles when the debugger stops. Killing the VS process automatically closes those handles, allowing you to access the file again. As a work around, you might look at unlocker it's free and works exceptionally well. I know that's not a great answer, but it should be faster than restarting VS. You might to consider sending a bug report too...
Unlocker doesn't work on 64-bit OS, LockHunter does though.
Here is how I solved this problem
*I open the project Properties,
*select the build tab,
*Clear the output path,
*and buid(this will create the dll in the root folder)
*come back to the output path and select browse(browse to the bin directory to either debug/release)and voila!
As per Error: Cannot access file bin/Debug/… because it is being used by another process answer by TarmoPikaro, sometimes Visual Studio creates multiple msbuild.exe ghost processes, which persist after build. These ghost processes seem to be causing file locks.
Solution 1 - Kill ghost MSBuild.exe's
Killing msbuild.exe's is a one time solution, it needs to be done per build basis.
You can kill the processes as follows mrtumnus:
taskkill /f /im MSBuild.exe
Solution 2 - Disable parallel builds in Visual Studio
You can disable parallel build once and for all:
Tools > Options > Projects and Solutions > Build and Run > "maximum numbers of parallel project builds" - by default it has value of 8, switch it to 1.
Of course builds are bit slower now, but mileage may vary depending on your use case.
This is related to
Error: Cannot access file bin/Debug/... because it is being used by another process
I've seen the Windows Indexing Service cause this. Disabling it helped. Virus scanners can also be at fault. Mutliple Application.Close() calls can supposedly cause this, too.
Of course, since it always works the first time, I suppose these are unlikely.
Had the same problem. The following things helped
Closing all design files while debugging
using unlocker
Also my application opens a port. While debugging an exception was thrown and program quit. While ending the program I closed the port. That helped too.
But definitely, bug with VS2010.
I encountered the same problem and in my case I had the file in question open in Visual Studio. Closing all files helped.
I faced the same error and I was stuck in it for many days. Finally resolved the issue.
I was working on a project that had many class libraries added in it. I added the reference of these libraries to my main project and mistakenly added reference to same project to itself. So when I removed self reference, it worked.
I had this issue myself. I had the project properties window open and that apparently creates a file lock. Even after I closed the window the file lock remained and I had to restart VS.
P.S. I'm using VS 2019. Just posting this for anyone having the issue I had and coming to this post.
If you get this error on VS Code;
Click on terminal screen and use "Ctrl + C" for stop running.

Resources