Live ASP.Net Web Application Giving NullReferenceException - asp.net

I have a web application that is working great while running form VS, but once it's published trying to navigate to the site throws a NullRefernceException. Here is the stack trace:
[NullReferenceException: Object reference not set to an instance of an object.]
DAL.VendorRepDAL.GetRepsInfo(List`1 fields) in C:\Users\mfoster\Desktop\EventPlanner\DAL\DAL.vb:649
EventPlanner.DealEntry.LoadData() in C:\Users\mfoster\Desktop\EventPlanner\EventPlanner\deals.aspx.vb:31
System.Web.UI.Control.LoadRecursive() +70
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3063
I think the problem may have something to do with the fact that file paths in the stack trace are referencing my hard drive for some reason. If that's the case I'm not how to fix it.
Thanks For any help.

Sherlock Holmes might deduce that since this error comes from a class named DAL, either:
Your live application does not have a valid database connection string, or
The database your live application is connecting to does not have the tables and/or rows and/or data that it expects.
The rest of us, however, might need to see a bit more code, such as the GetRepsInfo method that seems to be throwing.
Common causes and fixes for NullReferenceException can be found here: What is a NullReferenceException, and how do I fix it?

Related

Tracking recurring error that is occuring in the Session_Start method

I am getting a recurring error occuring in the Session_Start method in the Global.asax.cs file (ASP.NET, C#, .NET Framework 4). The error seems to be happening on the following line
if (!OnlineVisitorsUtility.Visitors.ContainsKey(currentContext.Session.SessionID))
which basically checks to see if this sessionId is in the current list of SessionIds.
The error is
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at TestSystem.WebSite.Global.Session_Start(Object sender, EventArgs e) Global.asax.cs:line 142
at System.Web.SessionState.SessionStateModule.CompleteAcquireState()
at System.Web.SessionState.SessionStateModule.BeginAcquireState(Object source, EventArgs e, AsyncCallback cb, Object extraData)
at System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
There is no user logged against the error (because this is thrown before anybody logs in). But no user has reported errors attempting to log in, the only reason we see this is because it is showing up in the error logs.
The error occurs every minute or so for a few days, then stops for a few days before re-surfacing.
We record the remote host ip for each error, and it is different for each instance of the error I have looked at. I initially thought it was some sort of automated job kicking this off, but when I track the location IP address I have found it originating in places we have users, places we don't and a private (i'm guessing internal) IP address.
We cannot replicate this error on our internal test and QA systems. I am looking for help in two areas, first, anyone have any idea what could be causing this, and second, if not, what information could I log that would shed some light on what's causing this?
Thanks,
Neil
EDIT
The dictionary in the error trace above is a dictionary that stores a SessionId and a WebsiteVisitor class.
public static Dictionary<string, WebsiteVisitor> Visitors = new Dictionary<string, WebsiteVisitor>();
We only add to this after checking the ContainsKey if statement above. The whole statement is below
lock (visitorsLock)
{
if (!OnlineVisitorsUtility.Visitors.ContainsKey(currentContext.Session.SessionID))
{
OnlineVisitorsUtility.Visitors.Add(currentContext.Session.SessionID, new WebsiteVisitor(currentContext));
}
}
Sounds like you have a synchronization problem with your Visitors dictionary. The Dictionary collection is not thread-safe so read/write access needs to be controlled. I see your using a locking object to resolve this issue, however, the problem with that approach is IIS doesn't guarantee that each request will be running under the same AppDomain instance or even the same worker process.
Instead of cross thread locking you need to look at cross process locking, I would suggest using a Mutex.
Update
Actually #RichardDeeming made a very good point - the Visitors object won't be shared across multiple processes/AppDomain so it can't be a synchronisation problem in that respect, however, the Dictionary is getting corrupt somehow. I would recommend switching to using a ConcurrentDictionary and let the framework take care of the synchronisation for you.
Generally, static property in web apps aren't a good idea as they can't be shared across multiple AppDomains and you can end up running into mysterious issues like this.

Which Asp.net exceptions can do what?

If I write this code
protected void Page_Load(object sender, EventArgs e)
{
Page_Load(sender, e);
}
I get the an Error (endless recursion):
and the w3wp.exe process is terminated from task manager.
Fine...
however if i do:
throw new ApplicationException(); //or SystemException();
it appears in just a regular exception page. ( w3wp.exe is still up).
questions :
what kind of exceptions causing the w3wp.exe to shutdown ?
what kind of exceptions causing the Application Pool to shutdown ?
p.s.
according to what ive just written , please think about the following scenario :
i can write a web page , host my site in a farm of sites , and i can terminate the whole w3wp.exe process by creating recursion ..... ( also others will have trouble)...
Can you please answer my questions ?
thanks.
This is most likely the famous StackoverflowException. It's caused by an infinite loop since you're calling the method Page_Load again and again.
From MSDN:
In prior versions of the .NET Framework, your application could catch
a StackOverflowException object (for example, to recover from
unbounded recursion). However, that practice is currently discouraged
because significant additional code is required to reliably catch a
stack overflow exception and continue program execution.
Starting with the .NET Framework version 2.0, a StackOverflowException
object cannot be caught by a try-catch block and the corresponding
process is terminated by default. Consequently, users are advised to
write their code to detect and prevent a stack overflow. For example,
if your application depends on recursion, use a counter or a state
condition to terminate the recursive loop. Note that an application
that hosts the common language runtime (CLR) can specify that the CLR
unload the application domain where the stack overflow exception
occurs and let the corresponding process continue. For more
information, see ICLRPolicyManager Interface and Hosting Overview.
You may want to have a look at this answer:
https://stackoverflow.com/a/4802309/284240
The reason for the exception is memory overflow. There are many ways how an application can cause this, there is no point to guess specific scenarios. I imaging good hosting providers should be protected from misbehaving applications.
to add to the answers which alrdy are available. u cant bring down the whole process because every website in a server runs in a seperate AppDomain. so if ur code misbehaves only ur appdomain wud be killed.

Find the source of a first chance exception raised in the Visual Studio 2010 Output window

I'm working on a asp.net web application with Visual Studio 2010. There are a bunch of output window messages during debugging regarding:
A first chance exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll
and
An exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll but was not handled in user code
I've read some great Q&A on the topic of how and why these might be raised and how to handle them (or not handle them). My first guess is that it is related to Response.Redirect()s that are in the code. However, I see them in the output and I'm not sure of the source of those output messages.
Question: how do I determine where the first chance exception came from in Visual Studio 2010?
Once I determine the source, I can investigate, solve or simply ignore per the Q&A linked to this question. Thanks in advance!
From personal experience, unless there is specifically an error occurring as a result of these, these messages can generally be ignored.
I have read in the past that this can be solved by adding false to the second parameter of Response.Redirect to stop processing occurring after redirect.
E.g. Response.Redirect("path/to/page.aspx", false);
Response.Redirect on MSDN
When you use this method in a page handler to terminate a request for one page and start a new request for another page, set endResponse to false and then call the CompleteRequest() method. If you specify true for the endResponse parameter, this method calls the End method for the original request, which throws a ThreadAbortException exception when it completes. This exception has a detrimental effect on Web application performance, which is why passing false for the endResponse parameter is recommended. For more information, see the End method.

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.

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.

Resources