Webservice unavailable - asp.net

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.

Related

What happens with an exception in Asp.Net with concurrent users

Does it cause all the threads,I mean all the users to stop and increase the wait time http request queue and start to affect the availability of the application ?
If so should we make sure there is no exception left over in an asp.net application to ensure scalability of the application.
Some unhandled exceptions can terminate w3wp.exe. Therefore, you should handle exceptions. Application_Error can't handle which are thrown on another thread (background workers, fire and forget taks). You should use http module for these kind of errors. But it also can't catch stackoverflow erros. You should use some decarations for this, if you want handle exceptions on Application level. Here is more detail.
Other than this I think exceptions will not effect the other users. Exception and performance.
Basically, exceptions shouldn't happen often unless you've got
significant correctness issues, and if you've got significant
correctness issues then performance isn't the biggest problem you
face.
I liked this sentence :)
Does it cause all the threads,I mean all the users to stop and
increase the wait time http request queue and start to affect the
availability of the application
It depends on the exception. For example, OutOfMemoryException will affect all users.
On the other hands, FileNotFoundException wouldn't affect other user.
If so should we make sure there is no exception left over in an
asp.net application to ensure scalability of the application.
Well, we all developers try to write bug free code, but sometimes things slip out of our hand. It is why we use logging to catch run-time exceptions - such as Log4Net, NLog.

What is The remote server returned an error: (400) Bad Request?

I am trying to add contacts to the constant contact site n there i am getting following exception
The remote server returned an error: (400) Bad Request.
i am using ASp.net C# application for inserting my records.
can any one tell me the solution ,or why i am getting the above error?
Thanks in advance
This website is useful.
Introduction:
Why I am getting this exception? What is the cause of this error. Developers are always curious to know the root cause of an
exception, even though they found the solution from elsewhere. So what
is the reason of this exception (400 Bad Request).The answer is
security. Security is an important feature for any application.
ASP.NET try to his best to give you more secure application
environment as possible. One important security feature is related to
URLs. Because there are various ways a hacker can try to access server
resource. Therefore it is important to make your application as secure
as possible. Fortunately, ASP.NET provides this security by throwing
an exception of Bad Request whenever he feels. In this Article I am
try to present when ASP.NET feels to throw this exception. You will
also see some new ASP.NET 4 features which gives developers some
control on this situation.

asp.net Background Threads Exception Handling

In my 3.5 .net web application I have a background thread that does a lot of work (the application is similar to mint.com in that it does a lot of account aggregation on background threads). I do extensive exception handling within the thread performing the aggregation but there's always the chance an unhandled exception will be thrown and my entire application will die. I've read some articles about this topic but they all seem fairly outdated and none of them implement a standard approach. Is there a standard approach to this nowadays? Is there any nicer way to handle this in ASP.NET 4.0?
Arguably, the entire application should die if you have an unhandled exception. An unhandled exception means that your program is in an unknown/indeterminate state, and any further processing or user interaction could cause corruption of the program's state, or worse, data corruption.
You're doing the right thing handling exceptions within your thread work. As far as I know, there is no way for a .NET application to "gracefully" deal with unhandled exceptions on background threads - they will always terminate the process.
Certain .NET Framework classes, such as the BackgroundWorker component and the Task Parallel Library in .NET 4 make multithreading easier and handle a lot of the dirty work of exception handling for you, so if it's possible for you to use those instead of implementing your own multi-threaded code, then you should definitely do so. But if those aren't able to help you in a given circumstance, if you must use the ThreadPool or a pure Thread, then be sure not to let any unhandled exceptions escape.
You can always put a try/catch block around your worker thread at a very high level... like right when the thread starts. I'm assuming this is what you're doing already, or something like it. But just keep in mind that you definitely don't want to turn an unknown error into a silent unknown error, because then it's going to be much harder to track down when something goes wrong. Be sure you are logging the exception to the EventLog or your custom app log if you want to just catch it and forget it.
Like Aaronaught says, the application should die when something unexpected happens. But I don't see a problem with just letting your background thread exit/die instead of bringing down the whole application process (in fact, I don't think Aaron is correct here, it won't kill the entire process) I think your question can basically be translated as "is there something magical in ASP.NET that will suddenly solve issues I don't even know about yet?" and the answer to that of course, is no. But you already knew that. :)

Exception Handling in .net web apps

I admit it: I don't bother with too much exception handling. I know I should do more but I can never wrap my head around where to start and where to stop. I'm not being lazy. Far from it. It's that I'm overwrought with exception handling ambivalence. It just seems that there is a seemingly infinite number of places in even the smallest app where exception handling can be applied and it can begin to feel like overkill.
I've gotten by with careful testing, validating, and silent prayer but this is a bad programming accident waiting to happen.
So, what are your exception handling best practices? In particular, where are the most obvious/critical places where exception handling should be applied and where are places where it should be considered?
Sorry for the vague the question but I really want to close the book on this once and for all.
Microsoft's Patterns & Practices team did a good job incorporating best practices of exception management into Enterprise Library Exception Handling Application Block
Event if wouldn't use Enterprise Library, I highly recommend you to read their documentation. P&P team describes common scenarios and best practices for exceptions handling.
To get you started I recommend read following articles:
Exception Handling on MSDN
Exception Management in .NET on MSDN
Exception Handling Best Practices in .NET on CodeProject
ASP.NET specific articles:
User Friendly ASP.NET Exception Handling
Global Exception Handling with
ASP.NET
Exception handling in C# and ASP
.Net
The golden rule with exception handling is:
"Only catch what you know how to handle"
I've seen too many try-catch blocks where the catch does nothing but rethrow the exception. This adds no value. Just because you call a method that has the potential to throw an exception doesn't mean you have to deal with the possible exception in the calling code. It is often perfectly acceptable to let exceptions propagate up the call stack to some other code that does know what to do.
In some cases, it is valid to let exceptions propagate all the way up to the user interface layer then catch and display the message to the user. It might be that no code is best-placed to know how to handle the situation and the user must decide the course of action.
I recommend you start by adding a good error page that catches all exceptions and prints a slightly less unfriendly message to the user. Be sure to log all details available of the exception and revise that. Let the user know that you have done this, and give him a link back to a page that will (probably) work.
Now, use that log to detect where special exception handling should be put in place. Remember that there is no use in catching an exception unless you plan to do something with it. If you have the above page in place, there is no use in catching database exceptions individually on all db operations, unless you have some specific way to recover at that specific point.
Remember: The only thing worse than not catching exceptions, is catching them and not doing nothing. This will only hide the real problems.
Might be more about exception handling in general than ASP.NET speific but:
Try to catch exceptions as close to
the cause as possible so that you
can record (log) as much information
about the exception as possible.
Include some form of catch all, last
resort exception handler at the
entry points to your program. In
ASP.NET this could be the
Application level error handler.
If you don't know how to "correctly" handle an exception let it bubble up to the catch all handler where you can treat it as an "unexpected" exception.
Use the Try***** methods in .NET
for things like accessing a
Dictionary. This helps avoid major
performance problems (exception
handling is relatively slow) if you
throw multiple exceptions in say a
loop.
Don't use exception handling to
control normal logic of your
program, e.g. exiting from a loop via
a throw statement.
Start off with a global exception handler such as http://code.google.com/p/elmah/.
Then the question comes down to what kind of application are you writting and what kind of user experience do you need to provide. The more rich the user experience the better exception handling you'll want to provide.
As an example consider a photo hosting site which has disk quotas, filesize limits, image dimension limits, etc. For each error you could simply return "An error has occured. Please try again". Or you could get into detailed error handling:
"Your file is to large. Maximum
filesizes is 5mb."
"Your image is is
to large. Maximum dimensions are
1200x1200."
"Your album is full.
Maximum storage capacity is 1gb".
"There was an error with your
upload. Our hampsters are unhappy.
Please come back later."
etc. etc.
There is no one size fits all for exception handling.
Well at the very basic level you should be handling the HttpApplication.Error event in the Global.asax file. This should log any exception that occurs to a single place so you can review the stack trace of the exception.
Apart from this basic level you should ideally be handling exceptions where you know you can recover from them - for example if you expect a file might be locked then handling the IOException and reporting the error back to the user would be a good idea.

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