System.Web.HttpUnhandledException - asp.net

I got error in my aspx.Below the information of the error.
Error Message : Exception of type 'System.OutOfMemoryException' was thrown.
Source : mscorlib
StackTrace : at System.String.GetStringForStringBuilder(String value, Int32 startIndex, Int32 length, Int32 capacity)
at System.Text.StringBuilder.set_Capacity(Int32 value)
at System.Xml.BufferBuilder.ToString()
at System.Xml.XmlTextReaderImpl.ParseText()
at System.Xml.XmlTextReaderImpl.ParseElementContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.XmlTextReader.Read()
at System.Xml.XmlReader.ReadElementString()
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderService.Read3_GetXmlResponse()
at Microsoft.Xml.Serialization.GeneratedAssembly.ArrayOfObjectSerializer9.Deserialize(XmlSerializationReader reader)
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle)
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
-----
-----
-----
Target Site : System.String GetStringForStringBuilder(System.String, Int32, Int32, Int32)
Can any one help me ?
Thx

Don't know whether this solves your issue or not. But please take a look at this one
Problems with System.OutOfMemoryException At System.String.GetStringForStringBuilder in 32-Bit Managed Solutions

When you want to add text to StringBuilder, and the current capacity is not enough StringBuilder will try to double it's capacity.
So max capacity for string is 2^32 but in your case it will want to go from 17MB to 34MB. may be you are trying to append the text to a big StringBuilder?

You need to use .NET memory profiler to check where are memory leaks in your application.
http://www.google.com/search?ie=UTF-8&oe=UTF-8&sourceid=navclient&gfns=1&q=.NET+memory+profilers
It looks like you are operating with very big string there, or some other memory leaks caused memory pressure.

The error occurs when access web service that return xml.
the return will be used in datatable.

Your server are running out of memory. There's really three possibilities here:
You need a new server. Probably not the cause.
Your server is misconfigured. A possibility, especially given the stack trace.
You are doing something drastically wrong. Probably the cause.
Beyond this, noone will be able to even hazard a guess at what is wrong without actually seeing the code around where the error is happening. Though, if that's a complete stack trace it may be the case that #2 is coming into play. It may be that #1 is coming into play if your server is being swamped with traffic, but really, it would take alot of traffic on any semi-modern server to trigger an out of memory error.

Related

What could cause GDI+ Initialize exception

I spend a lot of time to search answer but I didn't found it. We have console application (exe) with C1 Report Component for automated printing task. This application is executed from cmd file and cmd file is called by cmdexec from SQL Server 2014 every minute. It's work very fine but there is exceptiton GDI+ Initialize - System.Drawing.SafeNativeMethods+Gdip.Initialize aproximetelly montly. There is no chance to solve this so we must restart server.
I tried to create cmd file with echo command. It was worked fine and I got output from echo. So I created application with Console.Writeline("Hello world") only. It was worked fine. Then I add reference to System.Drawing. Nothing happend - ouput was produced. Then I created System.Drawing.Bitmap object and I got GDI+ Initialize exception.
Job on SQL server run as SQLRUNSERVICES and it is in Administrator group. But when I log as SQLRUNSERVICES and launch our application in command line, application works fine without exception. When I log as another user there is no problem with this. Only with SQLRUNSERVICES throught SQL Proxy.
I suppose there must be something wrong with windows session. This application starts, prints some reports and finishes. So I suppose when application finishes memory will be free and GDI object will be free so. I check if we have call dispose method for each object working with GDI.
Can I have some chance to see GDI objects used by session? Or what could cause this exception? I cannot use task manager because when application is not running there is nothing to see.
Thank you for replies. It is very stresfull problem for us because it is going repeatedly every month after restart server.
We created testing application to print most quickly and we got this exception for one day. We call Dispose method for C1Report ofcourse. We will try to use using section. But it looks like C1 error. Test application printed about 65000 count of document and then crashed by GDI+ Initialization Exception. There is stack:
System.TypeInitializationException: The type initializer for 'Gdip' threw an exception. ---> System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+.
at System.Drawing.SafeNativeMethods.Gdip.Initialize()
at System.Drawing.SafeNativeMethods.Gdip..cctor()
--- End of inner exception stack trace ---
at System.Drawing.SafeNativeMethods.Gdip.GdipCreateBitmapFromScan0(Int32 width, Int32 height, Int32 stride, Int32 format, HandleRef scan0, IntPtr& bitmap)
at System.Drawing.Bitmap..ctor(Int32 width, Int32 height, PixelFormat format)
at System.Drawing.Bitmap..ctor(Int32 width, Int32 height)
at C1.C1Preview.GraphicsHolder.FromBitmap()
at C1.C1Preview.GraphicsHolder.FromScreen()
at C1.C1Preview.C1PrintDocument.SelectBestMeasurementDevice(Boolean showWarning, MeasurementDeviceEnum& measurementDevice, String& measurementPrinterName, GraphicsHolder& measurementGraphicsHolder)
at C1.C1Preview.C1PrintDocument.#fFe()
at C1.C1Preview.C1PrintDocument.SetCreationDevice(MeasurementDeviceEnum creationDevice, String creationPrinterName)
at C1.C1Report.Layout..ctor(C1Report report)
at C1.C1Report.C1Report.Initialize()
at C1.C1Report.C1Report..ctor()

WPF WCF MVVM OutOfMemoryException

I am working on this WCF-WPF app. I am frequently getting this error on an asynchronous XamDataGrid. Trying to make a WCF call and populate the Grid. I initially thought this is something to do with the large amounts of data returned from WCF and I made the call return data is much small pieces, by calling only for a category only. This error comes up randomly, not always on the same set of data. Reproducible enough in 15-20 tries.
I am running Windows XP (32bit), Dual Core, with 4GB of ram. When this exception is raised, client machine only uses about 2GB of RAM, and on the server W3WP is using only 800MB (of 6GB, 3 cores. Total memory use on server is ~2GB).
This is only happening on XP machines. Does not get this error on Windows 7 box.
Please guide me how to resolve this issue.
Thanks in advance
Event Viewer Logs this Message:
Event Type: Error
Event Source: .NET Runtime 2.0 Error Reporting
Event Category: None
Event ID: 5000
Date: 10/13/2010
Time: 10:50:07 AM
User: N/A
Computer: COMP-DC7800
Description:
EventType clr20r3, P1 appname.exe, P2 2.0.0.21872, P3 4cb0a1b1, P4 mscorlib, P5 2.0.0.0, P6 492b834a, P7 35df, P8 45, P9 system.outofmemoryexception, P10 NIL.
Below id the Exception details:
System.OutOfMemoryException was unhandled
Message="Exception of type 'System.OutOfMemoryException' was thrown."
Source="mscorlib"
StackTrace:
at System.IO.MemoryStream.set_Capacity(Int32 value)
at System.IO.MemoryStream.EnsureCapacity(Int32 value)
at System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count)
at System.Xml.XmlMtomReader.MimePart.GetBuffer(Int32 maxBuffer, Int32& remaining)
at System.Xml.XmlMtomReader.Initialize(Stream stream, String contentType, XmlDictionaryReaderQuotas quotas, Int32 maxBufferSize)
at System.Xml.XmlMtomReader.SetInput(Stream stream, Encoding[] encodings, String contentType, XmlDictionaryReaderQuotas quotas, Int32 maxBufferSize, OnXmlDictionaryReaderClose onClose)
at System.Xml.XmlMtomReader.SetInput(Byte[] buffer, Int32 offset, Int32 count, Encoding[] encodings, String contentType, XmlDictionaryReaderQuotas quotas, Int32 maxBufferSize, OnXmlDictionaryReaderClose onClose)
at System.ServiceModel.Channels.MtomMessageEncoder.MtomBufferedMessageData.TakeXmlReader()
at System.ServiceModel.Channels.BufferedMessageData.DoTakeXmlReader()
at System.ServiceModel.Channels.BufferedMessageData.GetMessageReader()
at System.ServiceModel.Channels.MessageHeaders.GetBufferedMessageHeaderReaderAtHeaderContents(IBufferedMessageData bufferedMessageData)
at System.ServiceModel.Channels.MessageHeaders.GetBufferedMessageHeaderReader(IBufferedMessageData bufferedMessageData, Int32 bufferedMessageHeaderIndex)
at System.ServiceModel.Channels.MessageHeaders.GetReaderAtHeader(Int32 headerIndex)
at System.ServiceModel.Channels.WsrmMessageInfo.Get(MessageVersion messageVersion, ReliableMessagingVersion reliableMessagingVersion, IChannel channel, ISession session, Message message, Boolean csrOnly)
at System.ServiceModel.Channels.ReliableDuplexSessionChannel.HandleReceiveComplete(IAsyncResult result)
at System.ServiceModel.Channels.ReliableDuplexSessionChannel.OnReceiveCompletedStatic(IAsyncResult result)
at System.ServiceModel.Diagnostics.Utility.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
at System.ServiceModel.AsyncResult.Complete(Boolean completedSynchronously)
at System.ServiceModel.Channels.ReliableChannelBinder`1.InputAsyncResult`1.OnInputComplete(IAsyncResult result)
at System.ServiceModel.Channels.ReliableChannelBinder`1.InputAsyncResult`1.OnInputCompleteStatic(IAsyncResult result)
at System.ServiceModel.Diagnostics.Utility.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
at System.ServiceModel.AsyncResult.Complete(Boolean completedSynchronously)
at System.ServiceModel.Channels.InputQueue`1.AsyncQueueReader.Set(Item item)
at System.ServiceModel.Channels.InputQueue`1.Dispatch()
at System.ServiceModel.Channels.InputQueue`1.OnDispatchCallback(Object state)
at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.WorkItem.Invoke2()
at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.WorkItem.OnSecurityContextCallback(Object o)
at System.Security.SecurityContext.Run(SecurityContext securityContext, ContextCallback callback, Object state)
at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.WorkItem.Invoke()
at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.ProcessCallbacks()
at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.CompletionCallback(Object state)
at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.ScheduledOverlapped.IOCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
at System.ServiceModel.Diagnostics.Utility.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
OutOfMemory exceptions can happen for a lot of reasons in general, and in web apps in particular.
First, if you're running on IIS, there are settings specific to IIS to limit memory, see here: http://blogs.msdn.com/b/pfedev/archive/2009/01/22/memory-based-recycling-in-iis-6-0.aspx
Depending on your configuration, pools, etc., these limits may not apply to .NET web applications.
Now, in ASP.NET, there is also a setting memoryLimit in the machine.config file that specifies the maximum allowed memory size, as a percentage of total system memory, that the worker process can consume before ASP.NET launches a new process and reassigns existing requests.
The default is 60%, which is equal to 1.2G on a 2G machine.
However,... whatever you configure, 800M is the practical limit for ASP.NET apps on a 32-bit machine, see a good explanation here: Understanding ASP.Net memory
The solution to avoid this is to change the way your system works and break it in smaller pieces.
That's why by default, WCF has been carefully configured with so many limits (see here for an extensive list: http://weblogs.asp.net/paolopia/archive/2008/03/23/wcf-configuration-default-limits-concurrency-and-scalability.aspx) ... which almost every developer tends to change and max-out as soon as he discovers it :-)
You won't be able to utilise that 4 GB of RAM with a 32 bit OS.
http://chris.pirillo.com/32-bit-windows-and-4gb-of-ram/
If your application is consuming more and more memory as you use it, you may want to look at your memory management. Look at implementing the IDisposable interface for classes with unmanaged resources. Also, avoid keeping references to objects once you've finished using them. Events are particularly bad for this.
How do events cause memory leaks in C# and how do Weak References help mitigate that?
You could also look at streaming to a temporary file instead of streaming to memory.
Feel Relieved to find the answer that Microsoft Screwed it up all... :). that blame almost saved my Job... Here is the story..
WCF has a default message size of 64kb. One cannot find the reason for this on MSDN.. and so when we need to change the max message size to whatever we want. The problem is that the threshold for LOH is 85000b. If the message size is more than that, the object will be placed in LOH, your profiler will show that the objects have collected.. but when you see the LOH size in Sysinternals Process Explorer, Process properties window, you still see that the memory using is increasing. At around 800MB, our mighty Dr Watson comes up and kick of this application. Apparently this is a known issue with WCF & .net 2.0
Issue still exists in .net 4.0 but Microsoft released a quickfix. Sysinternals Process explorer is the tool which helped diagnose this issue. See Screenshot

ASP.NET application throwing "unable to find assembly" error for NHibernate

So let me start by saying that the weird thing about this error is that the application is running, and the error bubbles to the event log, but it's intermittent. Sometimes it's 2 hours between it happening, sometimes a few minutes, sometimes half an hour. Does not appear to be tied directly to requests (and requests don't seem to be failing because of it, though nearly all requests should be hitting NHibernate right now).
I've ensured that the dll is in the bin, it's unblocked (and if either of those weren't the case, I would expect it to fail always, not just sometimes).
For the app, I'm using Nhibernate 2.1.2, castle activerecord 2, ASP.NET MVC 2, and the app is deployed on IIS 7.5 with SQL Server 2005 for the db. I saw a similar error on Stack but no answers there, hoping someone has insight on this error.
Message: Unable to find assembly 'NHibernate, Version=2.1.2.4000, Culture=neutral,
PublicKeyToken=aa95f207798dfdb4'.
StackTrace: at
System.Runtime.Serialization.Formatters.Binary.BinaryAssemblyInfo.GetAssembly()
at
System.Runtime.Serialization.Formatters.Binary.ObjectReader.GetType(BinaryAssemblyInfo
assemblyInfo, String name)
at System.Runtime.Serialization.Formatters.Binary.ObjectMap..ctor(String objectName,
String[] memberNames, BinaryTypeEnum[] binaryTypeEnumA, Object[] typeInformationA,
Int32[] memberAssemIds, ObjectReader objectReader, Int32 objectId, BinaryAssemblyInfo
assemblyInfo, SizedArray assemIdToAssemblyTable)
at
System.Runtime.Serialization.Formatters.Binary.__BinaryParser.ReadObjectWithMapTyped(BinaryObjectWithMapTyped record)
at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.ReadObjectWithMapTyped(BinaryHeaderEnum binaryHeaderEnum)
at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.Run()
at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
at System.Runtime.Remoting.Channels.CrossAppDomainSerializer.DeserializeObject(MemoryStream stm)
at System.AppDomain.Deserialize(Byte[] blob)
at System.AppDomain.UnmarshalObject(Byte[] blob)
Does this also happen on Application start up or is it always at some time in the future after the application has started?
Check Unhandled IIS Exception - How can I track it down (which has a very similar stack trace) which leads to http://unhandledexception.codeplex.com/sourcecontrol/latest
I have gotten similar errors and found that the real problem is not being reported. The accepted answer here is specific to ASP.NET (which is fine since that is what the question was about), but I was having the issue with a WPF browser application (which doesn't have a web.config file) and I found another way to see what my real problem was. I thought I should post it in case other people will find it helpful.
If you are getting these while debugging in Visual Studio, it can help to go to Debug > Exceptions and select the "Thrown" checkboxes (I am using VS 2008). For me, this allowed the error to be reported in Visual Studio instead of my web browser, and provided more detailed and accurate error information.
If you do this, realize that some of these exceptions may have been previously handled but now will disrupt your workflow by breaking at those points. If this happens, you can just turn off the exceptions that you don't need to break on.

ASP.Net String Assignment Failure

This is my first post here, so go easy on me :) I'm having an odd problem with an ASP.Net page. I'm getting an object not set error message when assigning a string literal to a variable. Here's the error I'm getting.
[NullReferenceException: Object
reference not set to an instance of an
object.]
Project.Page.Page_Load(Object sender,
EventArgs e) in
C:\Project\Page.aspx.vb:10
System.Web.UI.Control.OnLoad(EventArgs
e) +91
System.Web.UI.Control.LoadRecursive()
+74 System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean
includeStagesAfterAsyncPoint) +2207
And here is the code that the error is pointing to. The last line in this fragment is the line 10 the error is complaining about
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim teststring As String
teststring = "test"
It seems it fails on accessing any reference type, even if it is declared locally in the load function. I originally found the problem when Request.IsSecureConnection was nulling out on me. I eventually discovered I could replace it with the above code and fail in the same way.
The problem does not always happen. It seems to be triggered by publishing an update from Visual Studio, or when I head home for the day and the server sits idle all night. One or two app pool recycles seems to clear it up, and the page functions correctly.
Any help would be greatly appreciated. I've been doing desktop development for a few years, but I'm fairly new to web development. So maybe this is something obvious I've got configured wrong. I'm currently using .Net 4 on IIS 6.
UPDATE
I was able to identify the line using the recommendation of copying the page, commenting everything out, and then uncommenting one line at a time. The line my test page started giving the error was this one
Dim StateName As String = State.Attribute(XName.Get("name")).Value
That code is in a foreach over an IEnumerable(of XElement). The stack trace still points to the string assignment, but all other stack traces are spot on, so I don't think it's a bad pdb.
Also, when the error occurred this time, no amount of recycling the app pool or stopping and starting it would fix the error. I finally got it working again by switching the application to a different app pool.
I don't see how that code could throw a null reference exception, are you sure it is not some other code, but the exception message is pointing to the wrong place becuase your pdb files are out of date. The most likely candidate for the code at fault based on your description is some code accessing an application variable that has become null becuase the app pool has recycled due to timeout or because you have republished the web app.
Try declaring the string as a constant... just to zoom in on the issue
Dim Const TESTSTR as String = "test"
Dim teststring As String
teststring = TESTSTR
If that doesn't work, move the Const declaration somewhere global. Maybe it's something to do with how/where .NET stores the string itself becoming invalid.
Try manually recycling the page every time you publish... maybe it's an issue of the pre-compiled code lingering after an update? I admit, that's a head-scratcher, a line like that should never fail.

Why do I get ErrorCode <ERRCA0022> when I take down one velocity cache host?

I'm getting the following exception in my web app when I take down one node of a three node cluster which is hosting my users’ sessions.
The session cache also has secondaries on with no eviction.
Here is the error message and stack:
Exception information:
Exception type: DataCacheException
Exception message: ErrorCode<ERRCA0022>:Cache::GetAndLock: There is a temporary failure, please retry after some time.
Stack trace: at Microsoft.Data.Caching.DataCache.ExecuteAPI(RequestBody reqMsg, String apiName)
at Microsoft.Data.Caching.DataCache.InternalGetAndLock(String key, TimeSpan timeout, DataCacheLockHandle& lockHandle, String region)
at Microsoft.Data.Caching.DataCache.GetAndLock(String key, TimeSpan timeout, DataCacheLockHandle& lockHandle)
at Microsoft.Data.Caching.DataCacheSessionStoreProvider.GetItemExclusive(HttpContext context, String id, Boolean& locked, TimeSpan& lockAge, Object& lockId, SessionStateActions& actions)
at System.Web.SessionState.SessionStateModule.GetSessionStateItem()
at System.Web.SessionState.SessionStateModule.PollLockedSessionCallback(Object state)
If I retry the request a few moments later the message will go away. Why am I getting this message in the first place and shouldn’t the server figure it out on its own that a host is down and switch to one of the other clients. I've defined the session client as simple in my web.config file just in case it was a routing problem but the issue still arises.
please refer to the following blogs:
http://blogs.msdn.com/velocity/archive/2009/04/30/the-dreaded-error-cache-get-the-request-timed-out.aspx
http://blogs.msdn.com/velocity/archive/2009/06/17/troubleshooting-velocity-series.aspx
To answer your question about the server figuring out this on its own; it can actually do that, but since we cannot make a choice from the application developer's perspective (to retry or failfast), we leave it tothe application to employ the right behaviour for itself (retry, failing back to a DB, etc.). Hence we by default retry but we also having an aye on having some retry logic inbuilt if some application wants it. Hope this answers your query.

Resources