Bizarre error with Response.Redirect - c#

I get the following error when trying to use Response.Redirect in one of my ASP.NET pages:
[ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: offset]
System.Web.HttpResponseStream.Write(Byte[] buffer, Int32 offset, Int32 count) +8858392
System.Web.HttpResponseStreamFilterSink.Write(Byte[] buffer, Int32 offset, Int32 count) +30
System.Web.HttpWriter.Filter(Boolean finalFiltering) +8754611
System.Web.HttpResponse.FilterOutput() +82
System.Web.ApplicationStepManager.ResumeSteps(Exception error) +501
System.Web.HttpApplication.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +123
System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) +379
I've never seen this before. It is happening if I Response.Redirect during the Page Load event.
Any Ideas?
EDIT: It's not my code, This is happening if I were to just stick Response.Redirect by itself in Page_Load.
EDIT #2: Using a 302 FOUND header works fine, but isn't that what response.redirect is supposed to do anyways?

This probably won't help much, but the exception itself is thrown inside HttpResponseStream.Write(byte[] buffer, int offset, int count), when either offset < 0 (which it isn't) or buffer length is zero. From what I understand, this could happen if buffered output is enabled and something managed to write a zero bytes into a stream.
I would try calling a Flush before doing the redirect and experiment with the second parameter. I would also check the web.config for any custom filter registration (unlikely though). Also make sure that your target application does not have asynchronous page processing, which could cause a havoc.
Apparently other people have been getting similar error, but usually when writing their own filters. I would end up debugging on the assembler level...

I would review the code of the destination page carefully (since you comment the error is happening there). It is probably using something that depends on the request. I have never seen a similar error, but it really looks like you should be focusing on any special stuff that page is doing.

Related

C# Argument out of Range while sending mail

Sometimes, using the following code :
return SmtpClient.Send(message, OutboundClient.Host, OutboundClient.Port);
I retrieve the following error :
ArgumentOutOfRangeException: Count cannot be less than zero.Parameter name:count
at System.String.RemoveInternal(Int32 startIndex, Int32 count)
at ActiveUp.Net.Mail.TraceInfo.ToString()
at ActiveUp.Net.Mail.Header.ToHeaderString(Boolean removeBlindCopies)
at ActiveUp.Net.Mail.Message.ToMimeString(Boolean removeBlindCopies)
at ActiveUp.Net.Mail.Message.ToMimeString()
at ActiveUp.Net.Mail.SmtpClient.Send(Message message, String host, Int32 port)
In my code Host and Port are static values that never change message instead is (Message object) readen in another mailbox (but i have checked is always valorized even if this exception is thrown)
Anyone know why sometimes i get the exception above ?
You should check your version of MailSystem.NET.
There was a bug that look like yours on versions prior to 71651.
It happens when From, By, With, For, Via and Id are all empty.

Low level file access with .NET

Is there any class in the .NET framework which provides access to \.\G: - style paths. (i.e. raw volumes)?
We're currently doing this without any problem using p/invoked ReadFile and WriteFile, which is not complex for synchronous access, but it's tedious to add async read/write, because of all the care you need to take over pinning and handling the OVERLAPPED structure and managing the event object lifetime, etc. (i.e. all the tedious stuff we'd have to do in Win32 code...)
It's hard to prove you've got the interaction with the GC correct too, with any simple testing technique.
The FileStream class contains all this code in, no doubt, a completely bomb-proof and refined fashion, and taking advantage of lots of internal helpers which we can't use. Unfortunately FileStream explicitly stops you opening a raw volume, so we can't use it.
Is there anything else in framework which helps avoid writing this sort of code from scratch? I've poked about in Reference Source, but nothing leaps out.
Update - we had already tried the suggestion below to avoid the check on the path type by opening the device ourselves and passing in the handle. When we try this, it blows up with the following error (note that this trace goes through the contstructor of FileStream - i.e we don't get any chance to interact with the stream at all):
System.IO.IOException: The parameter is incorrect.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.SeekCore(Int64 offset, SeekOrigin origin)
at System.IO.FileStream..ctor(SafeFileHandle handle, FileAccess access, Int32 bufferSize, Boolean isAsync)
at OurApp.USBComms.UsbDevice..ctor(Char driveLetter) in
For reference, our CreateFile call looks like this:
var deviceName = String.Format(#"\\.\{0}:", driveLetter);
var handle = SafeNativeMethods.CreateFile(deviceName,
0x80000000 | 0x40000000,
FileShare.ReadWrite,
0,
FileMode.Open,
(uint)FileOptions.Asynchronous | 0x20000000, // Last option is 'FILE_FLAG_NO_BUFFERING'
IntPtr.Zero);
if (handle.IsInvalid)
{
throw new IOException("CreateFile Error: " + Marshal.GetLastWin32Error());
}
Update3: It turns out that (on a volume handle, anyway), you can't call SetFilePointer on a handle which has been opened with FILE_FLAG_OVERLAPPED. This makes some sense, as SetFilePointer is useless on files where there's any kind of multithreaded access anyway. Unfortunately FileStream seems determined to call this during construction for some reason (still trying to track down why) which is what causes the failure.
As Sriram Sakthivel noted (+1), you could pass a SafeFileHandle to the FileStream constructor.
From your stacktrace I'm assuming you tried to seek the stream to an invalid position ; raw disks / volume have special rules about read/write positions.
For instance, you cannot start reading a disk in the middle of a sector (you'll have to read/seek per chunk of 512 bytes). Try to read for instance at offset 0 to see if it work better.
I believe you can use this constructor of FileStream passing the pre opened FileHandle as SafeFileHandle instance. With that you have managed FileStream instance which you can use to issue an async I/O operation.
public FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync);
Also when you're planning to do async I/O, don't forget to set isAsnc flag to true. Otherwise you'll not get all the benefits of async I/O.

NVelocity: "Cannot read from a closed TextReader"

Just getting started on NVelocity (v1.1.1) and it seems to be working just fine.
There's just one small thing that annoys me. I've set up VS2010 to break each time an exception is thrown even though it gets handled somewhere, and when running the following code, it always breaks at the call to Evaluate, stating that it "Cannot read from a closed TextReader" (ObjectDisposedException). I do not have the source code for NVelocity, so I cannot debug.
Am I missing a setting somewhere that causes this? Is it just a harmless bug in NVelocity? The result comes out fine, to me it just seems like something's not quite right.
var velocity = new VelocityEngine();
var properties = new ExtendedProperties();
var context = new VelocityContext(fieldValues);
properties.AddProperty("velocimacro.library", string.Empty); // no library
velocity.Init(properties);
using (var writer = new StringWriter())
{
velocity.Evaluate(context, writer, null, templateContents);
return writer.ToString();
}
Exception stack trace:
at System.IO.__Error.ReaderClosed() at
System.IO.StringReader.Read(Char[] buffer, Int32 index, Int32 count)
at NVelocity.Runtime.Parser.VelocityCharStream.FillBuff() in
c:\...\src\NVelocity\Runtime\Parser\VelocityCharStream.cs:line 313
This is a first-chance exception. You can see in the source code that this exception is caught right afterwards within NVelocity code.

Memory exception while XDocument.Save()

I am trying to save an XDcoument to a thumb drive which doesnt have enough memory space available. (This is a special test condition for the app) Though the application is giving an exception like below, I cant get that in the try catch block around the XDocument.Save(filePath). Looks like it is a delayed throw. Is it a LINQ issue or am I doing something wrong?.
alt text http://img211.imageshack.us/img211/8324/exce.png
System.IO.IOException was unhandled
Message="There is not enough space on the disk.\r\n"
Source="mscorlib"
StackTrace:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.WriteCore(Byte[] buffer, Int32 offset, Int32 count)
at System.IO.FileStream.FlushWrite(Boolean calledFromFinalizer)
at System.IO.FileStream.Dispose(Boolean disposing)
at System.IO.FileStream.Finalize()
You found a bug in the framework. XDocument.Save(string) uses the "using" statement to ensure the output stream gets disposed. It depends on the encoding you used in the processing instruction but the internal System.Xml.XmlUtf8RawTextReader would be a common one to implement the text writer.
The bug: the Microsoft programmer that wrote that class forgot to implement the Dispose() method. Only the Close() method is implemented.
It is rather strange that this bug wasn't yet reported at the connect.microsoft.com feedback site. It ought to cause trouble in general use because the file stays open until the finalizer thread runs. Although that normally doesn't take that long, a couple of seconds or so. Except in your case where you exit the program right after writing and have the unfortunate luck to run out of disk space at the exact moment the buffer gets flushed.
A workaround for this bug is to use the XDocument.Save(TextWriter) overload instead, passing a StreamWriter whose Encoding matches the encoding of the XML.
Look at the stack trace. This trace starts with a Finalize call, which does a Dispose, which does a FlushWrite, which calls WriteCore, which gets the error.
In other words, flush your data first.
Post the code you use to write and we can show you where to do the flush.
Peeking into reflector, the last few lines are
using (XmlWriter writer = XmlWriter.Create(fileName, xmlWriterSettings))
{
this.Save(writer);
}
It means, the exception is thrown when the writer is disposed.
I guess, it will be better to check for available disk space before calling Save.
EDIT: Have you Disposed any object that the instance of XDocument depended on before making a call to Save?
XDocument.Save(string) does not have a bug, it does implement the Dispose method. The using statement is:- (as also described above)
using (XmlWriter writer = XmlWriter.Create(fileName, xmlWriterSettings))
this.Save(writer);
And XmlWriter does have a Dispose(), it implement the IDisposable interface.

IClientChannel antipattern

I've just spend 4 hours (it's 3am in the UK) trying to debug ASP.NET application which caused an exception in a thread managed by Framework (i.e. not my thread). I've just found out that a result from the static method ChannelFactory.CreateChannel can be cast to IClientChannel and explicitly Disposed. I mean that's all fine and nice but why:
1) ChannelFactory.CreateChannel does not return IClientChannel as an out parameter?
2) .Net documentation for CreateChannel does not mention it?
3) .Net documentation does not show a proper usage pattern in examples (no dispose code)?
Don't get me wrong - I love .Net framework. Microsoft (and Krzysztof Cwalina: see Designing Framework Guidelines) has done a really great job. That's why I didn't expect a such disaster. I mean how the hell I should know that my IMyService variable also supports IClientChannel and I should explicitly dispose it?
Here is an ASP.NET log if someone is interested.
Event Type: Error
Event Source: ASP.NET 2.0.50727.0
Event Category: None
Event ID: 1334
Date: 12/08/2009
Time: 01:55:47
User: N/A
Computer: WLGH3GIS
Description:
An unhandled exception occurred and the process was terminated.
Application ID: /LM/W3SVC/1/Root/Maps
Process ID: 3044
Exception: System.NullReferenceException
Message: Object reference not set to an instance of an object.
StackTrace: at System.Threading.Overlapped.Free(NativeOverlapped* nativeOverlappedPtr)
at System.ServiceModel.Channels.OverlappedContext.Free()
at System.ServiceModel.Channels.PipeConnection.CloseHandle(Boolean abort, String timeoutErrorString, TransferOperation transferOperation)
at System.ServiceModel.Channels.PipeConnection.Close(TimeSpan timeout)
at System.ServiceModel.Channels.BufferedConnection.Close(TimeSpan timeout)
at System.ServiceModel.Channels.ConnectionPool.CloseItem(IConnection item, TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationPool`2.EndpointConnectionPool.CloseItem(TItem item, TimeSpan timeout)
at System.ServiceModel.Channels.IdlingCommunicationPool`2.IdleTimeoutEndpointConnectionPool.CloseItem(TItem item, TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationPool`2.EndpointConnectionPool.CloseIdleConnection(TItem connection, TimeSpan timeout)
at System.ServiceModel.Channels.IdlingCommunicationPool`2.IdleTimeoutEndpointConnectionPool.IdleTimeoutIdleConnectionPool.OnIdle()
at System.ServiceModel.Channels.IdlingCommunicationPool`2.IdleTimeoutEndpointConnectionPool.IdleTimeoutIdleConnectionPool.OnIdle(Object state)
at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.WorkItem.Invoke2()
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)
Karol, I know this is a bit old, but I wanted to say thank you. Your post really helped me out.
The symptom I had was that when I tried to Close a ChannelFactory on the Server, it would always give a Timeout, regardless of the length of timespan I set for OpenTimeout, ReceiveTimeout, SendTimeout, InactivityTimeout, or CloseTimeout.
The solution was actually on the client, to cast the IMyServiceInterface that was returned by ChannelFactory.CreateChannel to ICommunicationObject. Then, it can be passed nicely to the Util.SafeCloseAndDispose(ICommunicationObject) method that you see copy and pasted all over the web.
After I did that on my client, then the Server's ChannelFactory can be closed in only a second or two, with no more timeout.
As far as I know, this insight from Karol's post is one of the only places online where this problem is spelled out.
Thanks again, Karol! :)

Categories

Resources