When to load database drive configuration settings in ASP.NET? - asp.net

At application start our application connects to the database and fetches a language translation table and caches it into memory. The code that does this is placed in Application_Start in Global.ascx
The problem with this approach is that if the database is not available, there will be a completely unhandled exception. Because the code is set at Application_Start, Request and Response are not available.
I was wondering if there's a general lightweight approach to this.
My plan is to implement a singleton to store the state of the connection attempt, and then check that on the default routed page. It's a solution, but I feel there's something missing. Are there any other approaches to this?

The problem with this approach is that if the database is not
available, there will be a completely unhandled exception.
Well handle it then. You could implement some retry policy in your code so that if the result is not cached in memory it will fetch it from the database once again.

The excellent article about the error handling can be find at http://blog.gauffin.org/2011/11/how-to-handle-errors-in-asp-net-mvc/#.UZsZ6LVTAus
. And jgauffin also had a discussion's thread at What is best practice for global error/exception handling in ASP.NET MVC?
Hope this help.

Related

WebApi loggin results async

I am using WebApi with Entity Framework to implement a REST service. I need to log the usage to the database. I can do this in the controller before it returns or in an ActionFilterAttribute. I want to be able to fire off a call to update the database, BUT I don't want to wait for completion. I want the response to return to the user without waiting for the update.
I was thinking about using a BackgroundWorker and passing in the objects.
Anyone have thoughts on if this is the good way to do this?
I think the question you should ask yourself is how much latency the database update can add to your overall response time. In most cases, it will be a lot simple to do the update as part of the request processing. Background worker is generally not a good solution but here is a good read related to that topic. If you absolutely need to do the database update outside of request processing, it will be better to consider a queueing mechanism like MSMQ, RabbitMQ, etc from the perspective of reliability.
I believe my performance problem is related to running in VS2012 debugger. When running the site directly, performance increased drastically. So I won't need to do any 'tuning tricks' if this proves out when deployed to test server.
Have you tried exploring NLog's async capabilities? We use NLog's async wrappers by wrapping a database logging target like so:
<targets async="true">
<target name="dbLog" xsi:type="Database" dbProvider="sqlserver" connectionString=".." />
.
.
</targets>
A quick startup on logging to MS SQL DB using NLog is found here
Moreover, you could make your logging method call async (.NET 4.5 required) and if you do not care for the result, choose not to await the method execution.
Look at this SO Thread for a sample NLog.config.

Webservice unavailable

I have an ASP.NET C# 3.5 web application that consumes another ASP.NET web service as a web reference. The web service is built into some proprietary hardware device. The problem is that that device has been having troubles and not alwasy accessible. My web application is suffering brcause of it, as it takes over a minute to load. It does load, but not acceptable.
The service is instantiated in a try catch block and no exception is being throw, but the output windows displays:
A first chance exception of type 'System.Net.WebException' occurred in System.dll
I know there is a better way to handle this, but I am drawing blanks.
Any help is appreciated.
UPDATE: Still looking for an answer on how to handle webservices that become unavailable without affecting website.
After tearing it apart, I found the exception. It is a standard "Unable to connect" exception. The problem is now the timeout, I have tried setting the asyncTimeout to 5000 in the web.config under the System.Web -> Pages properties. It is still taking aroung 20 seconds to throw the exception. Any ideas?
If you saw a "first chance exception" but your exception handler didn't get it, that means that the exception was handled elsewhere (swallowed, consumed by an exception handler, etc.) Perhaps something in the .NET libraries already handled that exception, and you need not concern yourself with it in your code. Or maybe you left some exception swallowing somewhere in your code.
You ought to consider using a timeout in your web request.
Simple solution, poll the service using JavaScript after page load.
Without any details regarding frequency/usage of the service and not seeing any code, heres a thought or two.
Its most likely the web method on this hardware that giving the error, so I'd pursue any support options you have (if any), but just for giggles, try this first to see if it helps....
I noticed that some people online said that they were able to get around this (in their scenario) by setting the KeepAlive to false on the requesting object, so that way your aren't inadvertently using an old (stale) connection to the service. You may be trying to "Keep Alive" but the webserver timed out the connection on you. Worth a quick try...
Good Luck!
In addition to the above, I would use a http debugger (like fiddler2) to get a better idea of what is happening on the wire.

ASP.Net static objects

I'm trying to cache some information that I've retrieved from a database. I've decided to use a static List<> member to store the information. I know from my experience with List<> in multithreaded applications that I need to protect access to it with the lock statement. Do I treat any code in my Asp.Net code the exact same way? Will the lock statement still work?
A lock statement around List method's would definitely work but if you need caching functionality in your ASP.NET application I would recommend you using Cache class which is adapted to this functionality.
Lock will work. Be aware that if there are multiple worker processes, you will end up with multiple versions of the list. Each of them will be protected by its own lock.
A pretty real danger here is that if you fail to release the lock, your entire web application might hang. A user might get disconnected while your ASP.NET page is executing; so be careful of exceptions thrown at unexpected times.
It depends upon whether you're going to modify the List. Here's a good discussion of this subject: Do i need a lock on a list? C#

ASP.NET Error Handling

In my asp.net applications, I've typically used the Application_Error global event handler to log the error and redirect the user to a user-friendly error page.
However, I have read about ELMAH and while that seems interesting, Application_Error seems like the simpler approach.
I've read other questions where people, including myself, have suggested one way or the other. What I'm wondering is if there is any significant benefit to using one over the other and why?
Elmah is a fantastic project and we use it for all of our ASP.NET applications. Not only does it log unhandled errors for you, it grabs the entire original page that the user saw, which contains a lot of detail for you.
It has email support, RSS feeds (both itemized and digest) and has an attractive console.
For 3 lines in config and a dll reference, I'd say that's a slam dunk.
I guess the main drawback of ELMAH is that it might be overkill for what you need. If it's logging and storing more info than you would in your own implementation, that's an unnecessary overhead in storage and processing. You also need to think about how you secure access to ELMAH's console since those exception details could contain juicy details of your app (that needn't be hard, but it's a worry that you didn't have before).
On the other hand, your own implementation will probably grow to log all that extra information once you decide that some stubborn bug requires it, and do you really care about shaving fractions of a second off the time that it takes for the error page to be displayed? Chances are you'll eventually end up building your own version of ELMAH, so why not just use ELMAH and save yourself the time.
I'd recommend that if you do want to write your own error logging rather than using ELMAH, you at least put it in a module rather than straight into Application_Error in global.asax. Just subscribe to the application's Error event in your module's Init method, and you can easily reuse your error handling code in another application with a line in web.config.
I also find it useful to handle any exception logging through ASP.NET's health monitoring. This makes it easy to control the type and level of logging in web.config, and also allows logging of exceptions that were handled in a try...catch without getting as far as Application_Error. Create a custom HandledExceptionEvent class that extends WebRequestErrorEvent, and you can create and raise those events in any catch block where you'd really like to know that the exception happened even though it was handled.

How do you log errors (Exceptions) in your ASP.NET apps?

I'm looking for the best way to log errors in an ASP.NET application.
I want to be able to receive emails when errors occurs in my application, with detailed information about the Exception and the current Request.
In my company we used to have our own ErrorMailer, catching everything in the Global.asax Application_Error. It was "Ok" but not very flexible nor configurable.
We switched recently to NLog. It's much more configurable, we can define different targets for the errors, filter them, buffer them (not tried yet). It's a very good improvement.
But I discovered lately that there's a whole Namespace in the .Net framework for this purpose : System.Web.Management and it can be configured in the healthMonitoring section of web.config.
Have you ever worked with .Net health monitoring? What is your solution for error logging?
I use elmah. It has some really nice features and here is a CodeProject article on it. I think the StackOverflow team uses elmah also!
I've been using Log4net, configured to email details of fatal errors. It's also set up to log everything to a log file, which is invaluable when trying to debug problems. The other benefit is that if that standard functionality doesn't do what you want it to, it's fairly easy to write a custom appender which can process the logging information as required.
Having said that, I'm using this in tandem with a custom error handler which sends out a html email with a bit more information than is included in the standard log4net emails - page, session variables, cookies, http server variables, etc.
These are both wired up in the Application_OnError event, where the exception is logged as a fatal exception in log4net (which then causes it to be emailed to a specified email address), and also handled using the custom error handler.
First heard about Elmah from the Coding Horror blog entry, Crash Responsibly, and although it looks promising I'm yet to implement it any projects.
I've been using the Enterprise Library's Logging objects. It allows you to have different types of logging (flat file, e-mail, and/or database). It's pretty customizable and has a pretty good interface for updating your web.config for the configuration of the logging. Usually I call my logging from the On Error in the Global.asax.
Here's a link to the MSDN
I use log4net and where ever I expect an exception I log it to the appropriate level. I tend not to re-throw the exception because it doesn't really allow for as-nice user experience, there is less info you can provide at the current state.
I'll have Application_Error also configured to catch any exception which was not expected and the error is logged as a Fatal priority through log4net (well, 404's are detected and logged as Info as they aren't that high severity).
My team uses log4net from Apache. It's pretty lightweight and easy to setup. Best of all, it's completely configurable from the web.config file, so once you've got the hooks in your code setup, you can completely change the way logging is done just by changing the web.config file.
log4net supports logging to a wide variety of locations - database, email, text file, Windows event log, etc. My team has it configured to send detailed error information to a database, and also send an email to the entire team with enough information for us to determine in which part of the code the error originated. Then we know who is responsible for that piece of code, and they can go to the database to get more detailed information.
I recently built an asp.net webservice with NLog, which I use for all my desktop apps. The logging works fine when I'm debugging in Visual Studio, but as soon as I switch to IIS the log file isn't created; I've not yet determined why, but it the fact that I need to look for a solution makes me want to try something else for my asp.net needs!
We use EnterpriseLibrary.ExceptionHandling.Logging. I like it a bit better than log4net because not only do we control the logging completely, but we can control the Throw/NoThrow decision within config as well.
We use a custom homegrown logging util we wrote. It requires you to implement logging on your own everywhere you need it. But, it also allows you to capture a lot more than just the exception.
For example our code would look like this:
Try
Dim p as New Person()
p.Name = "Joe"
p.Age = 30
Catch ex as Exception
Log.LogException(ex,"Err creating person and assigning name/age")
Throw ex
End Try
This way our logger will write all the info we need to a SQL database. We have email alerts set up at the DB level to look for certain errors or frequently occurring errors. It helps us identify exactly where the errors are coming from.
This might not be exactly what you're looking for. Another approach similar to using Global.asax is to us a code injection technique like AOP with PostSharp. This allows you to inject custom code at the beginning and end of every method or on every exception. It's an interesting approach but I believe it may have a heavy performance overhead.

Resources