Friday, 9 August 2013

HttpClient results in predictable exceptions

HttpClient results in predictable exceptions

I am using .NET 4.0 to try to leverage the functionality provided by
HttpClient. The aim is to upload a particular file around 10.5 MB in size
to a remote server using HTTP Verb "PUT". The remote server uses node.js.
I have written a small Console app (.NET 4.0 full not client profile)
The laptop I am using does not has .NET 4.5 or Visual Studio 2012
I installed Added these NuGet packages onto it to enable Async upload
features with progress update
<packages>
<package id="Microsoft.AspNet.WebApi.Client" version="4.0.20710.0"
targetFramework="net40" />
<package id="Microsoft.Net.Http" version="2.0.20710.0"
targetFramework="net40-Client" />
<package id="Newtonsoft.Json" version="4.5.11" targetFramework="net40" />
</packages>
I then wrote a simple function that does a synchronous upload
(UploadFile). This function works as expected and uploads the files
correctly.
The next method called UploadFileAsync tries to use HttpClient and fails
between 55-70% of upload. Visual Studio 2010 throws up a series of
exceptions. The first one is usually different ranging from
WebException
"The request was aborted: The request was cancelled"
to various other types. The second exception however is always predictable
and same. This is
ObjectDisposedExceptoin
Cannot access a disposed object.
Object name: 'System.Net.Sockets.NetworkStream'.
Finally this is the last exception in the chain
IOException
Unable to read data from the transport connection: Cannot access a
disposed object.
Object name: 'System.Net.Sockets.Socket'..
As you would notice I have removed all using blocks, close or dispose
statements etc. from my code. For the life of me I can not figure out what
is going wrong! I have tried PutAsync, and SendAsnyc methods both with
HttpClient. The only difference they make is that the first exception
changes.
Here is the code block
void UploadFile(string fileToUpload)
{
//string fileToUpload = @"F:\\upload_file.txt";
using (FileStream rdr = new FileStream(fileToUpload,
FileMode.Open))
{
HttpWebRequest req = null;
Stream reqStream = null;
try
{
req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "PUT";
req.Headers.Add("x-myheader", "163333.zip");
req.ContentType = "application/octet-stream";
req.ContentLength = rdr.Length;
req.AllowWriteStreamBuffering = false;
req.Timeout = 1000000;
reqStream = req.GetRequestStream();
Console.WriteLine(rdr.Length);
byte[] inData = new byte[rdr.Length];
// Get data from upload file to inData
int bytesRead = rdr.Read(inData, 0, (int)rdr.Length);
// put data into request stream
reqStream.Write(inData, 0, (int)rdr.Length);
rdr.Close();
req.GetResponse();
// after uploading close stream
reqStream.Close();
}
catch (Exception e)
{
}
finally
{
rdr.Close();
req.GetResponse();
// after uploading close stream
reqStream.Close();
}
}
}
void UploadFileAsync(string fileToUpload)
{
//string fileToUpload = @"F:\\upload_file.txt";
FileStream rdr = new FileStream(fileToUpload, FileMode.Open,
FileAccess.Read, FileShare.Read, 8192, true);
//newfs rdr = new newfs(fileToUpload, FileMode.Open);
HttpClientHandler clientHandler = new HttpClientHandler();
ProgressMessageHandler progressHandler = new
ProgressMessageHandler(clientHandler);
HttpClient client = new HttpClient(progressHandler);
try
{
client.DefaultRequestHeaders.Add("x-myheader", "163333.zip");
HttpRequestMessage requestPayLoad = new
HttpRequestMessage(HttpMethod.Put, url);
long totalFileSize = rdr.Length;
Console.WriteLine(totalFileSize);
int? previousPercentage = null;
progressHandler.HttpSendProgress += (sender, args) =>
{
if (!previousPercentage.HasValue || previousPercentage
!= args.ProgressPercentage)
Console.WriteLine(args.ProgressPercentage);
previousPercentage = args.ProgressPercentage;
};
requestPayLoad.Content = new StreamContent(rdr);
//requestPayLoad.Content = new FileContent(fileToUpload);
//var task = client.PutAsync<byte[]>(url, rdr, new
BinaryMediaTypeFormatter());
var task = client.SendAsync(requestPayLoad);
task.Wait();
}
catch (Exception e)
{
}
finally
{
//rdr.Close();
client.Dispose();
//req.GetResponse();
//// after uploading close stream
//reqStream.Close();
}
}

No comments:

Post a Comment