I think I found the craziest .NET bug yet. This one boggles the mind in every sense of the word “boggle.”
Basically, if you try to run a series of HttpWebRequest’s from class and you set the ContentType after the RequestStream is written to, the code will work exactly ONCE.
Yes, thats right. The code will run once, then fail on all subsequent tries.
If the ContentType is set before the RequestStream is written, it works fine.
Now you might say “why would you set it after?” I would agree. We should ask Microsoft why in their Exchange 2000 SDK for WebDAV they have several samples that set it after.
Imagine the following code snippet:
System.Net.HttpWebRequest request = null;
System.Net.WebResponse response = null;byte[] bytes = null;
System.IO.Stream requestStream = null;try
{
// Create the HttpWebRequest object.
request = (System.Net.HttpWebRequest)HttpWebRequest.Create( “http://URL” );// Specify the PROPPATCH method.
request .Method = “POST”;// Encode the body using UTF-8.
bytes = Encoding.UTF8.GetBytes( yourRequestStringHere);// Set the content header length. This must be
// done before writing data to the request stream.
request.ContentLength = bytes.Length;// Get a reference to the request stream.
using ( requestStream= request .GetRequestStream() )
{// Write the message body to the request stream.
requestStream.Write(bytes, 0, bytes.Length);// Close the Stream object to release the connection
// for further use.
requestStream.Close();
}// Set the content type header.
// !!! TSK TSK !!! You better put this before the requestStream is written!
request.ContentType = “text/xml”;// Create the appointment in the Calendar folder of the
// user’s mailbox.
using ( response = (System.Net.HttpWebResponse)request.GetResponse() ) //WebException will be thrown here
{
// Clean up.
response.Close();
}Console.WriteLine(”Appointment successfully created.”);
}
Now Microsoft needs to 1) Fix the Exchange 2000 SDK and 2) Explain why exactly this happens, what sort of wacky connection caching is the Framework doing without our knowledge?
Special thanks to matt who posted a similar issue on microsoft.public.exchange2000.development