locked
The request was aborted: The connection was closed unexpectedly.

    Question

  • Hello All,

    As a part of integration of Yammer into the application,While trying to post the data, The error message "The request was aborted: The connection was closed unexpectedly." This error leads to the application crash. 

    Could some one tell me in general, when this error occurs.. Is this faulty from server end or client end and how to handle this.

    Finding some threads, mentioning to KeepRequestAlive=true/false for web Request.

    But no such property exsists for HttpWebRequest in metro apps.

    Please find below snippets I'm using for..

    Issue occurs at

    string response = await GetLocationHeader(request);

            public async Task<string> PostDataToYammerWithAttachments(string authHeader, string filename, StorageFile file, long filelength, string groupID, string broadcastToAll, string content, string replied_to_id = "")
            {
    
    
    
                try
                {
                    List<KeyValuePair<string, Object>> parameters = new List<KeyValuePair<string, Object>>();
    
    
                    string yammerPostUrl = "https://www.yammer.com/api/v1/messages.json";
    
                    parameters.Add(new KeyValuePair<string, Object>("body", content));
    
                    parameters.Add(new KeyValuePair<string, Object>("group_id", groupID));
                    if (!String.IsNullOrEmpty(replied_to_id))
                    {
                        parameters.Add(new KeyValuePair<string, Object>("replied_to_id", replied_to_id.ToString()));
                    }
    
                    parameters.Add(new KeyValuePair<string, Object>("broadcast", broadcastToAll.ToString()));
    
    
                    parameters.Add(new KeyValuePair<string, Object>("attachment", "attachment1"));
                    parameters.Add(new KeyValuePair<string, Object>("file", file.Name));
                    parameters.Add(new KeyValuePair<string, Object>("broadcast", broadcastToAll.ToString()));
    
    
    
                    string beginBoundary = GenerateRandomString(25);
                    string contentBoundary = "--" + beginBoundary;
                    string endBoundary = contentBoundary + "--";
                    string contentTrailer = "\r\n" + endBoundary;
    
    
    
    
    
    
                    HttpWebRequest request = HttpWebRequest.CreateHttp(yammerPostUrl);
    
    
    
                    request.Method = "POST";
                    request.Headers[HttpRequestHeader.Authorization] = "Bearer " + authHeader;
                    request.ContentType = "multipart/form-data; boundary=" + beginBoundary;
    
    
    
    
                    string contentType = "multipart/form-data; boundary=" + beginBoundary;
                    string contentDisposition = "Content-Dis-data; name=";
                    request.Headers["Cache-Control"] = "no-cache";
                    string postParams = GetPostParameters(parameters, contentBoundary, contentDisposition);
    
    
    
                    int i = 0;
                    long postDataSize = 0;
                    int headerLength = 0;
                    List<string> fileHeaders = new List<string>();
                    AddFileHeaders(filename, contentBoundary, contentDisposition, file, ref i, ref postDataSize, ref headerLength, fileHeaders, filelength);
                    request.Headers["ContentLength"] = (postParams.Length + headerLength + contentTrailer.Length + postDataSize).ToString();
                    System.IO.Stream io = await request.GetRequestStreamAsync();
                    WritePostData(postParams, io, false);
    
    
                    WritePostData(fileHeaders[i], io, false);
                    WriteFile(io, filename, file);
    
    
                    WritePostData(contentTrailer, io, false);
    
    
                    string response = await GetLocationHeader(request);
                    io.Dispose();
                    request = null;
    
    
                    return response;
                }
                catch (Exception ex)
                {
                    return string.Empty;
                }
    
            }
    
    
            private static void AddFileHeaders(string fileNames, string contentBoundary, string contentDisposition, StorageFile fi, ref int i, ref long postDataSize, ref int headerLength, List<string> fileHeaders, long filelength)
            {
    
    
    
    
                string contentType = fi.FileType.ToUpper().Contains("PNG") || fi.FileType.ToUpper().Contains("JPG") || fi.FileType.ToUpper().Contains("BMP") || fi.FileType.ToUpper().Contains("GIF") ? "image/gif" : "text/xml";
                string header = contentBoundary + "\r\n" + contentDisposition + "\"attachment" + (i + 1).ToString() +
                                    "\"; filename=\"" + fileNames + "\"\r\n" + "Content-type: " + contentType + "\r\n\r\n";
    
                postDataSize += filelength;
                headerLength += header.Length;
                fileHeaders.Add(header);
    
    
            }
    
    
            private static string GetPostParameters(List<KeyValuePair<string, Object>> parameters, string contentBoundary, string contentDisposition)
            {
    
    
                var p1 = parameters.ToArray();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < parameters.Count; i++)
                    sb.Append(contentBoundary + "\r\n" + contentDisposition + '"' + parameters[i].Key + "\"\r\n\r\n" + parameters[i].Value.ToString() + "\r\n");
    
    
    
    
                return sb.ToString();
            }
    
    
            public async static Task<string> GetLocationHeader(HttpWebRequest request)
            {
    
                string data = string.Empty;
                try
                {
                    var response = await request.GetResponseAsync();
    
                    data = response.Headers["Location"];
                    if (response != null)
                        response.Dispose();
                }
                catch (Exception ex)
                {
                    
                }
                
                return data;
    
    
    
    
            }
    
    
            private static void WritePostData(string postData, Stream requestStream, bool close)
            {
                byte[] postDataBytes = System.Text.Encoding.UTF8.GetBytes(postData);
                requestStream.Write(postDataBytes, 0, postDataBytes.Length);
                if (close)
                    requestStream.Dispose();
            }
    
            public static async void WriteFile(System.IO.Stream io, string fileName, StorageFile file)
            {
                int bufferSize = 10240;
                // StorageFile myStorageFile = await localFolder.GetFileAsync(fileName);
                var stream = await file.OpenReadAsync();
    
                using (var dataReader = new DataReader(stream))
                {
                    var bytes = new byte[stream.Size];
                    await dataReader.LoadAsync((uint)stream.Size);
                    dataReader.ReadBytes(bytes);
                    io.Write(bytes, 0, bytes.Length);
                    // return Convert.ToBase64String(bytes);
                }
    
    
            }
    
            private static string GenerateRandomString(int intLenghtOfString)
            {
                StringBuilder randomString = new StringBuilder();
                Random randomNumber = new Random();
                Char appendedChar;
                for (int i = 0; i <= intLenghtOfString; ++i)
                {
                    appendedChar = Convert.ToChar(Convert.ToInt32(26 * randomNumber.NextDouble()) + 65);
                    randomString.Append(appendedChar);
                }
                return randomString.ToString();
            }

    Sat on it for whole day to figure out, But could not.


    Thanks & Regards Tejaswi Chandrapatla

    Thursday, February 13, 2014 2:19 PM

Answers

  • Http 500 is a server error, so you'll have to check with yammer support or yammer API forums.  Specifically, look at your request's headers. 

    (The content hasn't been sent yet, from the sounds of it.)

    Don't assume that because it works once that it will work again - the server could have all sorts of processing flow that would make the same data fail on the second try. (For example, an anti-replay mechanism)

    However, I wouldn't think they'd return a 500.


    Darin R.

    Friday, February 14, 2014 4:55 PM

All replies

  • I'd monitor the network traffic and see what yammer is throwing back at your HTTP Request. 

    Usually that message on a Http POST means that a precondition failed on the server

    I.E. you aren't sending the correct header/Uri query string or other key information in the headers, and the server is rejecting the request before it wastes time and accepts the POST data in the body (if any)


    Darin R.

    Thursday, February 13, 2014 5:03 PM
  • "The connection was closed unexpectedly" means that the server closed the connection; generally this is because of an malformed request or due to incorrect authentication.  Can you switch over to the Windows.Web HttpClient?  Among other things, it includes an HttpMultipartContent class that makes sending multipart data easier.

    Some simple documentation in the in HttpClient poster available on the Microsoft Download site.


    Network Developer Experience Team (Microsoft)

    Thursday, February 13, 2014 8:17 PM
  • Darin,

    The issue is observed when the post request is done second or third time consequently. For the first time there was no issue being returned.

    If the issue is due to the wrongness of passing info, then the request need to fail for the first time too.Is there any thing I'm going wrong at client end

    I have captured the traffic using Fiddler.

    It comes out with  HTTP 500 error while doing second time.

    Checked the message body and parameters, All are the perfect and the same in both case while passing


    Thanks & Regards Tejaswi Chandrapatla


    • Edited by Teja510 Friday, February 14, 2014 5:19 AM
    Friday, February 14, 2014 3:55 AM
  • Does this require changing the most of the construct of request than above?

    What makes the true difference of it?

    Every thing works fine in first hit, when there is second/third hit being done then only I end up with this issue.


    Thanks & Regards Tejaswi Chandrapatla

    Friday, February 14, 2014 3:56 AM
  • Http 500 is a server error, so you'll have to check with yammer support or yammer API forums.  Specifically, look at your request's headers. 

    (The content hasn't been sent yet, from the sounds of it.)

    Don't assume that because it works once that it will work again - the server could have all sorts of processing flow that would make the same data fail on the second try. (For example, an anti-replay mechanism)

    However, I wouldn't think they'd return a 500.


    Darin R.

    Friday, February 14, 2014 4:55 PM
  • Thanks Darin,

    I will check with Yammer API team of the same.

    The issue occurs for same and different data.

    Could I handle it  in client side.

    As the error occurs, It leads to crash my app.. :(


    Thanks & Regards Tejaswi Chandrapatla

    Saturday, February 15, 2014 5:51 AM