Global exception handler in ASP.Net Core (Not UI) - c#

I am working on an application that will run in Kubernetes. Kubernetes relies on the application to know if it is healthy or not.
So, I need to know when I get a critical exception thrown. By "Critical", I mean Out of Memory, Stack Overflow, etc. Things that mean that the container should be killed.
I have seen things in ASP.Net Core that allow you to show an error page when an exception happens, but I need this to happen with both UI and Web API applications. And I don't really want it to interact with my UI at all (on the ones that have a UI ).
Is there an event (or something similar) that is raised when an exception was thrown in an ASP.Net Core application?

A .NET application will not be able to handle “critical” issues like memory issues or stack overflows in a way that it can report about its own health. There are basically two possible outcomes with unexpected errors: The application can handle the problem, in which case the ASP.NET Core application is expected to work properly for future requests, or the process terminates abruptly.
Observing the latter should be done from the outside. You can do this for example by checking if the process is still alive in your container.
Another option would be to employ health checks which is a way for an ASP.NET Core application to report about its own health:
Health probes can be used by container orchestrators and load balancers to check an app's status. For example, a container orchestrator may respond to a failing health check by halting a rolling deployment or restarting a container. A load balancer might react to an unhealthy app by routing traffic away from the failing instance to a healthy instance.
So your container orchestrator could check whether the ASP.NET Core application is still able to respond to a health probe, and if it isn’t assume that the application crashed in some way or another, requiring a container restart.

Related

Why is my azure webapp request sometimes slow

My azure web application sometimes reacts very slowly. He waits a few seconds before executing the request.
Of course I have the setting "always on" turned on.
It's running on a S2 service plan.
Avg users online 3
No vertical or horizontal scaling configured.
Application
Asp.net MVC
.net Framework 4.6.1
C#
Does anyone have an idea why this problem occasionally occurs?
Ok i see based on your picture that there is a wait time of 98.71% and lots of wait time from the compiler, so i would recommend you to consider to use precompiled views on your mvc app, to avoid the runtime compilation of the views. If you are using Azure DevOps, you should be able to change your task to build the solution and add the following options on the MSBuild arguments.
/p:PrecompileBeforePublish=true /p:UseMerge=true /p:SingleAssemblyName=AppCode
When you see the WebApp being slow it is important to understand what HTTP requests are slow and whether those HTTP requests are slow all the time or it is an intermittent issue? How are the CPU and memory metrics and what is the pattern of slowness? If you have application Insights enabled please navigate to the "Performance" tab to see the requests were are slow and whether they are dependent on an external component.
Collecting CLR profiler in the context of slowness will reveal where the time is spent.
You can navigate to Azure Portal-->WebApp-->Diagnose and solve problem blade-->Diagnostic tools-->Autoheal and enable the rule to collect the CLR profiler traces on slowness.
Once the rule triggers it will collect the profiler traces and build a report for your review.

.Net Web Application app startup workflow for IIS

Okay, so let's say I have a web application that absolutely has to perform some kind of startup and has to remain running indefinitely regardless of the communication it receives from the clients (as it's a push based system)
Now for testing I have been hosting this as a windows service, which is great because it allows for me to have a hard entry point to the application where I can do my bootstrapping and get the service up and running
Next, I'm trying to move this into the IIS world instead so I can face this service to the outside world...and I've hit a snag...I don't have any hard entry point where I can bootstrap the application except for global.asax, which as I understand it is only invoked when the clients make a call to the server
Is there a better area I can put an entrance to the application and get it bootstrapped without waiting for a client to connect to it? And is this area only called once or is it going to be called periodically as the application falls out of scope (so to speak)? Like I said, the app has to remain running at all times
Is there a better area I can put an entrance to the application and get it bootstrapped without waiting for a client to connect to it?
Yes, there is. You can warm up IIS.
And is this area only called once or is it going to be called periodically as the application falls out of scope (so to speak)?
It depends which method in Global.asax you use. Application_Start runs once per app start.
Like I said, the app has to remain running at all times
Beware, dragons here. This depends how critical it is. If you need utter reliability, you must use load balancer and have at least one other duplicate service. Other things to consider, app pool needs to be recycled from time to time. IIS, OS, your application have bugs, updates needs to be installed, network device fails, power outages do happen and so on.

Always run application within ASP.NET and external web hosting

I'm creating a ASP.NET .NET 4.0 website and part of this site requires that there is an "always running" application. Normally I would create a Windows Service for this, but the site will be hosted within a shared hosting environment, and unless I get a virtual server, then this isn't a possibility.
My first thought was to have a thread running in the background that would do this and it would be created on Application_Start and destroyed on Application_End. I've looked around and this seems like it could be an option, but I would of course have to hit the site in order to cause the Application_Start to be called and if the associated AppPool is recylced, then this process would have to be repeated (so I believe?!?).
Within a normal ASP.NET website does these seem possible?
In the end I had a seperate thread that sits and waits for a signal to be set. Once set it then does it's work. To make sure the thread is always active I make a HTTP request for a "dummy" page to ensure that, if the AppPool was recycled, then the Application_Start event is triggered and the thread restarted.
It depends on what mean by 'always running application':
If it's a realtime service, it still makes sense to run it as separate process, even if it may have a web front-end. It's so because ASP .NET server was designed by Microsoft for specific tasks(to run web apps, render pages etc.) in many aspects like memory usage or multithreading. And I'd prefer to use at least a VDS in such case.
Another case is when it's is a periodically(say every hour) alarmed application which does some uncomplicated work - perhaps your shared hoster has some mechanisms to trigger a specific page to do some work(as my hoster does). For example, I have an ASP .NET page that monitors the tour date list of my favourite band, and sends email notification when they are going to play a gig in my town - it's triggered by hoster every 4 hours.

Windows program that always runs

I have a requirement that a Windows Forms C# .NET 2.0 program running in user-space (not a service) must always be running. As I'm not infallible and make coding mistakes, I wanted to know of any extra safeguards I could use to ensure this requirement is met. The things I've been thinking of are TaskScheduler to check it every 5 minutes, A stub watcher or a secondary process. Are these good / bad ideas?
Thanks,
Richard
EDIT: The reason I didn't use a service (the obvious and sensible answer!) was the program runs in a kiosk type environment and has has a heavy GUI component. The service option didn't work well across Windows 2000 - W7.
EDIT: The second reason not to use a service was the app needs internet access and on some of our customer sites, proxies are set up to only allow specific users (not the local system account) so it would be tricky to ensure access if multiple users log onto the machine.
Task scheduler is a cheap solution for this which does work. I use this to keep our Perforce Proxy server running (had some issues with the service), and so far there's been no problems - though now I've said that the server's probably exploded!
However, the most complete solution is a Windows service which invokes your app. You can make that service catch error return codes from the app, restart it on failure and notify you by email, which may help you diagnose and fix those issues. I think the Task Scheduler does something similar but it won't be able to provide as much insight into your application as a custom service.
If you're unsure of how to do that, then something like this should work:
http://www.codeproject.com/KB/install/csharpsvclesson1.aspx
There are three approaches that you can take:
Heartbeat Message.
A heartbeat is useful in a distributed application and is simply message that is sent (from let say a client to server) to confirm that it is still healthy/running.
Manager Process
A stub program, implemented as either a user process or a service. It launches the main application, monitors any unhandled exceptions, reports errors, and restarts on failure.
An exception guard on the entry point.
A try-catch-all in the application entry point.
I would recommend either of the first two options; the third option, the try-catch-all, is a particular nasty hack for the lazy and inexperienced programmer (IMHO).
I have successfully used both heartbeat and manager process in a large distributed application.
UPDATE
As for ready-to-go™ restart managers, take a look at the Windows API Codepack as discussed in Emmanuel Istace blog post (http://istacee.wordpress.com/2013/09/21/automatic-recovery-restart-in-net-application/).
You can install the package from https://www.nuget.org/packages/WindowsAPICodePack-Core/

WCF self hosting, hosting via Console app

I have seen examples, sample codes etc for self hosting WCF services within a console app, windows service etc.
My question is, how will this work in production? Will it be efficient? Will it scale?
I m not sure, how it will work, so other question is, will that be single threaded? multi threaded? do i need to manage the multi threading? appdomains?
I prefer hosting with command line, windows service for application related reasons.
My question is,
Will it be efficient? Will it scale?
Yes and yes. But for really large scale apps you should still consider IIS (+WAS).
so other question is, will that be single threaded? multi threaded?
That is determined by the configuration.
Will it be efficient?
It depends on the service implementation, on the maximum number of requests it is able to manage within a specific time-frame. Efficiency is a relative measure: let's assume your service is able to process 20 messages/sec, if your requirement is to be able to process 10 messages/sec, then your service is efficient. But if the requirement is 30, then it is not.
Will it scale?
Once again, it is not related to hosting. Are your services stateless? if not then, they probably won't scale much since load balancing is not possible.
Will it be manageable ?
Probably not:
- you need to have a user logged on the server to run the app
- it does not auto-start with the server
- it cannot auto-restart on failure
- it does not create instances of the service pro-actively
- it does not provide (without custom code) a way to check the service health
Single instance ? Multiple threads ?
If your service does not maintain state between calls per client, then configure it as "one instance per call and no multithreading" -> No concurrency, high throughput
If your service does maintain state, then configure it as "one instance per session and multithreading" to allow a client to perform concurrent calls. Be careful about concurrency issues and protect your resources.
If your service does not maintain state per client but keeps some global data stored for all calls, consider the "single instance per service and multithreading". Keep in mind the possible concurrency issues. In that you might as well use "one instance per call" and keep the global storage out the service.
A Windows service hosting a WCF endpoint is fine for small services that aren't going to be hit often; you don't have to mess with IIS (which can be a REAL pain IMO). However, there will only be one listener listening, so it's not recommended for a service that is likely to be hit from several places at once (use IIS for that; it sets up an app pool that can handle many simultaneous requests). This model is good for one-on-one interop between two machines; you might set up the service host on a "set and forget" box living out in a warehouse somewhere, and call it to perform simple but custom tasks like rebooting, log dumps, etc.
Avoid having any user app (console or otherwise) host a service endpoint, except for initial proof-of-concept testing. In addition to the single-listener drawback, a user app MUST be run in the context of a logged-in user (not the service users, which are "logged in" as part of Windows startup), and must have custom "keepalive" monitoring; with a service, Windows can be told to simply restart it if it crashes, while it doesn't give a toss about a user app crashing other than to prevent that program taking down the whole OS (and to ask the user if they want to report the crash).

Categories

Resources