I am trying to remotely debug a project with ASP.NET Core 2.1 that uses IIS as a server using the remote debugger tool, since I was able to establish the connection to the remote server and debug some things using breakpoints, the problem that is currently happening to me is that I can debug the file code as controllers,services, but I cannot debug the Program.cs file code using breakpoints.
Any ideas?
you could check the below things if you are not getting any error but breakpoint didn’t hit:
1)if you are running your code on more than one machine so the first check you are debugging the correct place code.
2)make sure your codding is running and you set the System.Diagnostics.Debugger.Break or __debugbreak( for c++) in your code where you want to set the breakpoint. (do not forget to build your project after adding this code)
3)If you are debugging optimized code, make sure the function where your breakpoint is set isn’t being inlined into another function. The Debugger.Break test described in the previous check can work to test this issue as well.
Add a call to Launch at the beginning of the OnStart()method.
protected override void OnStart(string[] args)
{
System.Diagnostics.Debugger.Launch();
}
How to: Debug the OnStart Method
Related
I am trying to follow this tutorial to run azure function app using C# using vscode.
But when I click the run button, it shows "You must have the Azure Functions Core Tools installed to debug your local functions." But I have actually installed it in my mac. When I click the install button, it shows errors like follows:
/bin/bash: func: command not foundThe terminal process "/bin/bash '-c', 'func host start'" failed to launch (exit code: 127).
And on the right bottom there is a small window showing:
Error exists after running preLaunchTask "host start". View task output for more information.
But when I use the command func host start in my local terminal, it can run smoothly.
We have tried the same but on Windows(OS) , Below are the workaround to resolve the above issue.
Created a new Azure function with HTTP Trigger using .net 6
Before debugging we have started the Azure storage Emulator/Azurite on local.
Or Alternatively, We can add "AzureWebJobsStorage": "UseDevelopmentStorage=true", in our localsettings.json and tried to debug by using .net Function.
OUTPUT DETAILS FOR REFERENCE:-
NOTE:- To run function locally based on the given MICROSOFT DOCUMENTATION:-
Click on Ctrl - (macOS) the HttpExample function and choose Execute
Function Now
Or, we can add a breakpoint over our function.cs file and type start debug as shown below :-
For more information regarding VS CODE on macos configuration Please refer this SO THREAD discussions .
I've run across an issue when debugging applications on VS 2010.
This is a simple command-line app:
namespace HttpTest
{
class Program
{
public void testHTTP ()
{
Console.WriteLine("Creating HTTP request. Press a key to proceed.");
Console.ReadKey();
var request = (HttpWebRequest)HttpWebRequest.Create("http://stackoverflow.com");
Console.WriteLine("Getting response...");
var response = (HttpWebResponse)request.GetResponse();
Console.WriteLine("Done");
Console.ReadKey();
}
static void Main(string[] args)
{
Program app = new Program();
app.testHTTP();
}
}
}
If I launch/debug it from Visual Studio 2010, I get a ConfigurationErrorsException when creating the HttpWebRequest:
Error creating the Web Proxy specified in the 'system.net/defaultProxy' configuration section.
This is quite suprising, as my app.config has no entry in system.net/defaultProxy (and neither does my devenv.exe.config).
By trying different settings, I found out that the error only happens if I set the target framework to 4.0 and the target platform to x86 and try to debug within VS
If I build it and run it from the command line (regardless of build settings), I have no issues.
If I set the target Framework to 3.5, the error disappears and the app debugs normally.
If I set the platform target to 'x64' or 'Any CPU', the app debugs normally.
If I build on 4.0/x86, run from command line, attach the debugger while waiting for the first key press, then proceed, I get the error mentioned above.
I have disabled the firewall on my machine
Running VS as administrator makes no difference to the test.
If I try this on a different machine, same hardware specs and OS, belonging to a colleague, I can debug it within VS2010.
It obviously has something to do with the settings on my machine. However, I have been unable to isolate what the conditions are.
Other users suggested moving the application to the C: drive. I don't think this applies to my case, as I can run int successfully from the D: drive. Issue happens only when debugging within VS.
Is it possible in C# to do run specific lines codes in debug setting and other in say release settings.
if #debug
//run some lines of code
else
// run different lines of code
You can do something like:
#if DEBUG
// Debug Code
#else
// Release Code
#endif
I use that in WCF services to run it as a console app in debug, but as a Windows Service in release
HTH,
Rupert.
Read this blog post If You’re Using “#if DEBUG”, You’re Doing it Wrong, the author suggests using System.Diagnostics.ConditionalAttribute:
[Conditional("DEBUG")]
private static void DebugMethod()
{
// Debugging code
}
I am using visual studio 2010, my application has a multiu layer architect,
MainUI, WCFService, BLL and DAL
My MainUI communicated to WCF and WCF further communicates to BLL and DAL, whenever i need to debug BLL and DAL, i first need to attach WCF as a process in Visual studio(everytime). How could i can save myself from this hassle.
How could i set up visual studio in a way that i automatically attach to the service automatically and i could debug my application easily.
Thanks
Configure your solution for multi project start up. I do this for a similar application. VS launches the WCF and client automatically and I can set break points in either.
The start-up order is the order in which you select the projects.
Right mouse click on your solution and select 'choose startup projects'. Then select multiple startup projects and select the projects.
Sample howto start a process and attach it to Visual Studio 2010 with EnvDTE(Version is relevant).
//c:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\PublicAssemblies\EnvDTE.dll
using Process = EnvDTE.Process;
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = System.AppDomain.CurrentDomain.BaseDirectory + #"\YourProcess.exe";
//Start the process
p.Start();
//Wait for process init
System.Threading.Thread.Sleep(1000);
bool attached = false;
//did not find a better solution for this(since it's not super reliable)
for (int i = 0; i < 5; i++)
{
if (attached)
{
break;
}
try
{
EnvDTE.DTE dte2 = (EnvDTE.DTE)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.10.0");
EnvDTE.Debugger debugger = dte2.Debugger;
foreach (Process program in debugger.LocalProcesses)
{
if (program.Name.Contains("YouProcess.exe"))
{
program.Attach();
attached = true;
}
}
}
catch (Exception ex)
{
//handle execption...
}
}
Try using System.Diagnostics.Debugger.Break() in the code. If a debugger is not attached, then running that code will ask to attach a debugger and you can choose the existing instance.
Have you tried System.Diagnostics.Debugger.Launch() in your service you would like the debugger to attach to?
http://msdn.microsoft.com/en-us/library/system.diagnostics.debugger.launch.aspx
In the properties page for the wcf service project, select the Web tab.
Select 'Start External Program' for the start action, and choose MainUI.exe.
Set the working directory as the folder that MainUI.exe is in (probably a bin folder).
Set a break point and press f5 to start debugging.
If I understand correctly, Macro may be answer:
in Vs:
Tools->Macros->record TemporarilyMacro (Ctrl+shift+r)
Attach VS to process as usual (ctrl+alt+p)
Stop recording macro (ctrl+shift+r)
Go to View->Other Windows->Macro Explorer (CTRL+F8)
find your Temporarily Macro (somewhere in MyMacros->RecordingModule) and rename it
Now, go to Tools->Options->Keyboard and find your macro (in "Show Command containing write name of you macro)
in "Press Shortcut keys" bind it to some key shortcut (i have my macro in CTRL+SHIFT+K ;))
Push OK
Be Happy
Have you tried using the WCFSvcHost.EXE that comes with Visual Studio to launch the BLL and DAL service? There is a help file with it. The help file states it best, "Windows Communication Foundation (WCF) Service Host (wcfSvcHost.exe) allows you to launch the Visual Studio debugger (F5) to automatically host and test a service you have implemented. You can then test the service using WCF Test Client (wcfTestClient.exe), or your own client, to find and fix any potential errors." The default installation is C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE. You can configure it to use your MainUI app as the client. The help file WcfSvcHost.chm in the same directory has a section for using a custom client under the Scenarios for using ECF Service Host. If you rather here is the link to help on MS web site: Using WCF Service Host (wcfSvcHost.exe).
If this is for a self-hosted WCF windows service, you need to make your WCF service host configurable to either run in console or as a windows service. When you have run in console turned on, you can start debugging from visual studio.
Create an app setting called "RunInConsole." In your service host startup method, have the following code:
public class MyWindowsService : ServiceBase
{
public static void Main(string[] args)
{
// if configuration says to run in the console, run the service in a console app. otherwise, use windows
// service to host application
if (ConfigurationManager.AppSettings["RunInConsole"] == "true")
{
using (ServiceHost host = new ServiceHost(typeof(MyService)))
{
host.Open();
Console.WriteLine("Press <Enter> to terminate the Host application.");
Console.ReadLine();
}
}
else
ServiceBase.Run(new MyWindowsService ());
}
}
On all environments you deploy to, you'd always have this config setting set to false or else the service will fail to start, but when debugging locally you'd set it to true.
Here is a detained article that explains how to do this...You can customize this macro.
http://sivablogz.wordpress.com/2013/04/08/running-an-application-and-attaching-to-the-process-with-a-macro-in-visual-studio/
Personally I prefer to use Debugger.Launch() as suggested here
in this thread, because it doesn't need for references to the DTE (that's IDE-specific and must be explicitly referenced into the project to be used)
I have code written in .NET that only fails when installed as a Windows service. The failure doesn't allow the service to even start. I can't figure out how I can step into the OnStart method.
How to: Debug Windows Service Applications gives a tantalizing clue:
Attaching to the service's process allows you to debug most but not all of the service's code; for example, because the service has already been started, you cannot debug the code in the service's OnStart method this way, or the code in the Main method that is used to load the service. One way to work around this is to create a temporary second service in your service application that exists only to aid in debugging. You can install both services, and then start this "dummy" service to load the service process. Once the temporary service has started the process, you can then use the Debug menu in Visual Studio to attach to the service process.
However, I'm not clear how it is exactly that you are supposed to create the dummy service to load the service process.
One thing you could do as a temporary workaround is to launch the debugger as the first line of code in the OnStart
System.Diagnostics.Debugger.Launch()
This will prompt you for the debugger you'd like to use. Simply have the solution already open in Visual Studio and choose that instance from the list.
I tend to add a method like this:
[Conditional("DEBUG")]
private void AttachDebugger()
{
Debugger.Break();
}
it will only get called on Debug builds of you project and it will pause execution and allow you to attach the debugger.
Once you have a service that is installed using installutil.exe, you can alter the Start Parameters to jump into the debugger if the service is started:
When you manually start the service with the parameter -debugWithVisualStudio (or simply -d), it will automatically detect the correct project, and fire up the interactive debugger in Visual Studio:
To support this functionality, change the service's OnStart() function:
/// <summary>
/// Executed when the service is started.
/// </summary>
/// <param name="args">Command line arguments.</param>
protected override void OnStart(string[] args)
{
try
{
//How to debug when running a Windows Service:
// 1. Right click on the service name in Windows Service Manager.
// 2. Select "Properties".
// 3. In "Start Parameters", enter "-d" (or "-debugWithVisualStudio").
// 4. Now, when you start the service, it will fire up Visual Studio 2012 and break on the line below.
// 5. Make sure you have UAC (User Access Control) turned off, and have Administrator privileges.
#if DEBUG
if (((ICollection<string>)args).Contains("-d")
|| ((ICollection<string>)args).Contains("-debugWithVisualStudio"))
{
Debugger.Launch(); // Launches VS2012 debugger.
}
#endif
ShellStart(args);
base.OnStart(args);
}
catch (Exception ex)
{
// Log exception here.
}
}
(optional) If you want to narrow down to the exact line of code where the service is throwing an error, switch on exceptions from the Visual Studio menu DEBUG .. Exceptions. When you continue debugging, it will break on the exact line that is throwing the exception.
It works just fine!
protected override void OnStart(string[] args)
{
System.Diagnostics.Debugger.Launch();
}
The options above did not appear to work on Windows 8.
I have added Thread.Sleep(15000); into my OnStart() method and set a breakpoint on the next line of the code. This give me 15 seconds to attach VS debugger to my process after starting the service and allowed me to debug the OnStart() method nicely.
You can add a line of code like this:
System.Diagnostics.Debugger.Break()
which will bring up a window prompting you to choose which debugger to use to debug, e.g. allowing you to attach with Visual Studio and step into the code.
see:
http://msdn.microsoft.com/en-us/library/system.diagnostics.debugger.break.aspx
It's possible to set up a companion project to the Windows Service that runs as a console app, but accesses the service methods using Reflection. See here for details and an example: http://ryan.kohn.ca/articles/how-to-debug-a-windows-service-in-csharp-using-reflection/.
Use following Code in Service OnStart Method:
System.Diagnostics.Debugger.Launch();
Choose Visual Studio option from Pop Up message. Remember to run Visual Studio as Administrator.
Note: To use it in only Debug mode, #if DEBUG compiler directive can be used, as follows. This will prevent accidental or Debugging in Release mode on Production server.
#if DEBUG
System.Diagnostics.Debugger.Launch();
#endif
As others have pointed out, you have to add a debugger break to the OnStart-Method:
#if DEBUG
System.Diagnostics.Debugger.Break()
#endif
Also start VisualStudio as Administrator and allow, that a process can automatically be debugged by a different user (as explained here):
reg add "HKCR\AppID\{E62A7A31-6025-408E-87F6-81AEB0DC9347}" /v AppIDFlags /t REG_DWORD /d 8 /f
(I also explained this here: https://stackoverflow.com/a/35715389/5132456 )
I know this is late but this is how we handle debuging Windows services
First create a class which will act as the service.
Add the appropriate methods for starting, stopping, pausing, etc...
Add a windows form to the service project.
In the service code create the service class created above and make the calls needed to start and stop the service in the ServiceBase class
Open the Program.cs and add the following
#if DEBUG
[STAThread]
#endif
static void Main()
{
try
{
#if DEBUG
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new DebugForm());
#else
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new YourWindowsService()
};
ServiceBase.Run(ServicesToRun);
#endif
}
catch (Exception e)
{
logger.Error(DateTime.Now.ToString() + " - " + e.Source + " - " + e.ToString() + "\r\n------------------------------------\r\n");
}
}
When you run in DEBUG mode the windows form will launch. Just remember to build in Release mode when finished. Of course the conditional compile variable can be anything you like. You could even create seperate projects so the debug form is its own project.
Hope this helps
You can also try System.Diagnostics.Debugger.Launch() method. It helps in taking the debugger pointer to the specified location and you can then debug you code.
Before this step please install your service.exe using the command line of Visual Studio command prompt - installutil projectservice.exe
Then start your service from the Control Panel -> Administrative Tools -> Computer Management ->Service and Application -> Services -> Your Service Name
If you add Debugger.Launch() in your OnStart method and it doesn't work, you could have the same issue I had, namely, the exception was occurring in the constructor so the OnStart was never called. (head slap)
(sorry if this should have been a comment on someone else' answer, but i don't have enough cred to make comments)
Try adding Debugger.Break inside the problematic method. When the service will start an exception will be thrown and widows should offer to debug it using visual studio.
I usually have a console app that pretends to be the SCM e.g. calls Start, Stop which I can then just F5 into for my main coding/debugging purposes, and use the Debugger.Break for debugging when the service has been installed and started via the SCM.
It means a bit more work to start with, I have a class lib that contains all the service code, with a class that exposes Start and Stop that the Windows Service class and the console app can both call.
Matt
Before I go in the topic one advise. Always use log specially if you are server side developer. Because there are some certain condition which you might not be able to produce while debugging the code in visual studio.
Coming back to topic, I use Envoirnment.UserInteractive flag this is really handy see my code below
public static void Main(string[] args)
{
if (System.Environment.UserInteractive)
{
string parameter = string.Concat(args);
switch (parameter)
{
case "--install":
ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
break;
case "--uninstall":
ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });
break;
default:
WindowsService service = new WindowsService();
service.OnStart(args);
Console.ReadKey();
service.OnStop();
break;
}
}
else
{
ServiceBase.Run(new WindowsService());
}
}
From visual studio you will get UserInteractive flag set so i would run it as console application, In addition to that even you can run product build by double clicking it and attaching debugger with it if you like to test it.
I have an interesting way of doing this I add another Configuration called DebugNoService
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'DebugNoService|AnyCPU' ">
<OutputPath>.\</OutputPath>
<AllowUnsafeBlocks>false</AllowUnsafeBlocks>
<BaseAddress>285212672</BaseAddress>
<CheckForOverflowUnderflow>false</CheckForOverflowUnderflow>
<ConfigurationOverrideFile>
</ConfigurationOverrideFile>
<DefineConstants>DEBUG;TRACE;DEBUGNOSERVICE</DefineConstants>
<DocumentationFile>
</DocumentationFile>
<DebugSymbols>true</DebugSymbols>
<FileAlignment>4096</FileAlignment>
<NoStdLib>false</NoStdLib>
<NoWarn>
</NoWarn>
<Optimize>false</Optimize>
<RegisterForComInterop>false</RegisterForComInterop>
<RemoveIntegerChecks>false</RemoveIntegerChecks>
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<WarningLevel>4</WarningLevel>
<DebugType>full</DebugType>
<ErrorReport>prompt</ErrorReport>
<UseVSHostingProcess>false</UseVSHostingProcess>
</PropertyGroup>
I use the #if directive.
ProjectInstaller.cs
#if !DEBUGNOSERVICE
static void Main()
{
System.ServiceProcess.ServiceBase[] ServicesToRun;
.....
}
#endif
I add a windows form and I also wrap the windows form in
#if DEBUGNOSERVICE
...
static void Main()
{
Form form;
Application.EnableVisualStyles();
Application.DoEvents();
form = new <the name of the form>();
Application.Run(form);
}
...
#endif
depending on the configuration selected the code either runs as a windows form application that can be easily debugged or as a service.
If seems like a lot of work but it has always worked and makes debugging the code very very easy. You can have all sorts of output added to the form so you can watch it run.