Skip to content
September 22, 2008 / kiranpatils

“The underlying connection was closed: The connection was closed unexpectedly.” While returning Data Table from WCF service.

Error:

“The underlying connection was closed: The connection was closed unexpectedly.”

StackTrace:

System.ServiceModel.CommunicationException was unhandled by user code

Message=”The underlying connection was closed: The connection was closed unexpectedly.”

Source=”mscorlib”

StackTrace:

Server stack trace:

at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)

at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)

at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)

at System.ServiceModel.Channels.ClientReliableChannelBinder`1.RequestClientReliableChannelBinder`1.OnRequest(TRequestChannel channel, Message message, TimeSpan timeout, MaskingMode maskingMode)

at System.ServiceModel.Channels.ClientReliableChannelBinder`1.Request(Message message, TimeSpan timeout, MaskingMode maskingMode)

at System.ServiceModel.Channels.ClientReliableChannelBinder`1.Request(Message message, TimeSpan timeout)

at System.ServiceModel.Security.SecuritySessionClientSettings`1.SecurityRequestSessionChannel.Request(Message message, TimeSpan timeout)

at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)

at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)

at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)

at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)

at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]:

at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)

at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)

at System.Web.UI.Control.OnLoad(EventArgs e)

at System.Web.UI.Control.LoadRecursive()

at System.Web.UI.Control.LoadRecursive()

at System.Web.UI.Control.LoadRecursive()

at System.Web.UI.Control.LoadRecursive()

at System.Web.UI.Control.LoadRecursive()

at System.Web.UI.Control.LoadRecursive()

at System.Web.UI.Control.LoadRecursive()

at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

InnerException: System.Net.WebException

Message=”The underlying connection was closed: The connection was closed unexpectedly.”

Source=”System”

StackTrace:

at System.Net.HttpWebRequest.GetResponse()

at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)

InnerException:

Scenario:

I have one OperationContract defined in my service contract which was returning DatTable as its return Type So it was looking like this:

[OperationContract]

DatTable LoadEmployeeInformation(long employeeID);

And in implementation I am filling this data Table using Table Adapter and returning it.

But it was throwing me error which was really annoying i had spent 4-5 hours to figure out it…

Solution:

I have changed my operation Contract to return Dataset Instead of Data Table

[OperationContract]

DataSet LoadEmployeeInformation(long employeeID);

and it worked like a charm!!!! For me…and hope that it works for you also…then go ahead and try this change….

Root cause:

Sorry guys I don’t know the root cause of this error. But i read some forums from Microsoft and they says that don’t use Data Table as a return type because some problem occurs in deserializaing it at client side…hooh…but I think it is BUG of WCF!!

Webliography:

http://connect.microsoft.com/wcf/feedback/ViewFeedback.aspx?FeedbackID=286535

http://processmentor.com/community/blogs/scott_middleton/archive/2007/06/08/169.aspx

http://blogs.msdn.com/lifenglu/archive/2007/08/01/passing-datatable-across-web-wcf-services.aspx

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1828652&SiteID=1&mode=1

http://blogs.conchango.com/merrickchaffer/archive/2007/09/19/WCF-System.Net.WebException_3A00_-The-underlying-connection-was-closed_3A00_-The-connection-was-closed-unexpectedly.aspx

-Kiran

37 Comments

Leave a Comment
  1. Youssef / Dec 3 2008 8:29 pm

    After struggling with the same issue you are having, I sent a request to Microsoft and I got a simple answer that I did not expect, and the solution works perfectly.
    Simply give your Table a name. If you don’t, which is what I was doing, it will block teh client and time ou.
    e.g. DataTable dt = new DataTable(“name”)
    or DataTable dt = new DataTable();
    dt.TableName = “name”;
    then hydrate your DataTable any way you want (from the database or from another data source), and return from WCF method withouy any problems.
    I’d be interested if it works out for you.
    -Youssef

    • Trex / Jun 23 2010 5:34 am

      Thank you . .works like magic ^_^

      • kiranpatils / Jul 20 2010 4:38 pm

        Thanks Trex! Happy Coding!🙂

    • andrevancoller / Jul 19 2011 2:32 pm

      it works thanks

      • Anuva / Jun 4 2013 9:13 am

        thanks boss

    • Nway / Oct 18 2011 4:57 am

      Thanks a lot

    • fiddlestix / Oct 18 2011 6:07 pm

      Youssef: you are the man!

      Your post saved me a lot of time.

      thank you!

  2. stephen / Aug 25 2009 12:18 pm

    it worked ina charm !!! thanks

  3. Kris / Sep 1 2009 12:05 pm

    Tried this…but didn’t work out !

    Hence had to revert to returning DataSet itself instead of DataTable 😦

    Regards,
    Kris

  4. Raj / Oct 30 2009 3:29 am

    that’s a wonderful solution. thanks

  5. Srini / Mar 22 2010 3:29 am

    Awesome

  6. Abdul Rafay / Apr 13 2010 7:46 pm

    Thanks buddy, it saved a lot of time for me I was stuck for a long time on this error.
    Thanks,
    Abdul Rafay
    Abdul Rafays BizTalk Blog

  7. Tom / Apr 20 2010 1:12 am

    At last after 5 hours today and 5 yesterday i have found a solution. My issue was cuased by cloning a typed table to a datatable – using a dataset to conviently populate a types datatable and then clone it to an datatable for consuming by remote app – without any refs to the typed dataset etc…. so here is how it works….

    public System.Data.DataTable GetData(string Product, int ID)
    {
    dsSettingsAndResultsTableAdapters.MT2_settings_resultsTableAdapter dta = new micro_trends.co.uk.WCF.Service.StrategySettings.dsSettingsAndResultsTableAdapters.MT2_settings_resultsTableAdapter();
    dsSettingsAndResults.MT2_settings_resultsDataTable tdt = null;
    tdt = dta.GetDataByID(ID);
    DataTable dt = new DataTable(tdt.TableName);
    dt.Merge(tdt.Clone(), false, MissingSchemaAction.Add);
    return dt;
    }

    goddam messy… much easier to use a normal datatable and populate via a dal / dataadapter and stored proc etc….
    but i was in a rush….

  8. ninjatrader indicators / Aug 31 2010 10:58 am

    Solution that works for dataset or dataTable

    System.Data.DataSet IUpdates.GetDataSet()
    {
    DataSet ds = new DataSet(“MTProducts”);
    ds.Merge(mTProductsDataset);
    return ds;
    }

    System.Data.DataTable IUpdates.GetDataTable()
    {
    DataTable dt = new DataTable(“Products”);
    dt.Merge(mTProductsDataset.Products);
    return dt;
    }

  9. ninjatrader indicators / Aug 31 2010 11:02 am

    test client

    [ServiceContract]
    public interface IUpdates
    {

    [OperationContract]
    DataSet GetDataSet();

    [OperationContract]
    DataTable GetDataTable();

    }

    static void Main(string[] args)
    {

    try
    {
    // Create a channel
    EndpointAddress address = new EndpointAddress(Settings.SercviceAddress);
    BasicHttpBinding binding = new BasicHttpBinding();
    using (ChannelFactory factory = new ChannelFactory(binding, address))
    {
    IUpdates channel = factory.CreateChannel();
    Console.WriteLine(“Fetch dataTable”);
    System.Data.DataTable dt = channel.GetDataTable();
    if (dt != null)
    {
    Console.WriteLine(“Fetch Success”);
    dt.WriteXml(@”dt.xml”);
    Console.WriteLine(File.ReadAllText(@”dt.xml”));
    }
    else
    {
    Console.WriteLine(“Fetch Error”);
    }

    Console.WriteLine(“Fetch dataSet”);
    System.Data.DataSet ds = channel.GetDataSet();
    if (ds != null)
    {
    Console.WriteLine(“Fetch Success”);
    ds.WriteXml(@”ds.xml”);
    Console.WriteLine(File.ReadAllText(@”ds.xml”));
    }
    else
    {
    Console.WriteLine(“Fetch Error”);
    }

    ((IChannel)channel).Close();

    }

    }
    catch (Exception ex)
    {
    Console.WriteLine(ex.ToString());
    //
    }
    Console.Read();
    }

  10. Thirmal Reddy / Sep 27 2010 12:33 pm

    Thanks It helps me a lot i worked on this one week

  11. Jyotsna / Jan 19 2011 6:06 am

    Hi Kiran

    I have my WCF returning a list of objects and the last link in webliography helped me in this case.

    http://blogs.conchango.com/merrickchaffer/archive/2007/09/19/WCF-System.Net.WebException_3A00_-The-underlying-connection-was-closed_3A00_-The-connection-was-closed-unexpectedly.aspx

    Thanks much
    Jyotsna

  12. DDesch / Mar 5 2011 2:43 am

    Thanks Youssef, naming the table fixed the problem. Now if only I could have found this thread before I gave myself a concussion from banging my head on the table.

  13. Moondog / Apr 11 2011 6:37 pm

    Thank you, this was driving me nuts and changing to a dataset finally got it working. Awesome!

  14. Alex / Jul 5 2011 6:09 pm

    A big Thank you! Mine was returning a Hastable (which WCF isn’t fond of it seems). Changed it and it worked again!

  15. Aminda / Nov 1 2011 9:39 pm

    yes its working for me. thanks a lot for the post.

  16. idpkshr / Mar 6 2012 9:29 am

    Thanks !

    It really worked for me

  17. Bipin / May 18 2012 6:22 am

    Thanks a lot, it saved a lot of time for me I was stuck for a long time on this error.
    Thanks,

  18. Bhanu / Jun 26 2012 11:40 am

    WCF..
    public DataTable newfuncion()
    {
    int qtype = 1;
    SqlCommand cmd = new SqlCommand(“StateBind”, con);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add(“@Qtype”, SqlDbType.Int).Value = qtype;
    SqlDataAdapter adap = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable(“Product”);
    adap.Fill(dt);
    return dt;
    }

    Client..
    dt = client.newfuncion();

    I am getting error like ”
    Unable to Automatically debug .. urlservice
    the remote procedure could not be debugged .this usuallly indicates that debugging has mnot enabled on the server.”

    I am not using any break point .

  19. lokesh / Jul 17 2012 1:40 am

    thanks it worked

  20. Dorababu / Aug 25 2012 4:51 am

    This is Just awesome man. I am pulling out my head to figure it out what happens, but you just give a simple solution of all

  21. bharat / Oct 15 2012 10:56 am

    thank you so much ….what a idea

  22. SJ Alex / Mar 19 2013 10:46 am

    Thanks a lot.. for Dataset It is working fine but in List it shows same error

    • kiranpatils / Mar 23 2013 7:02 pm

      Sj Alex — Glad to know that you found it useful!

      Thanks for your comment — It stimulates!

      Keep sharing, Keep visiting and Keep reading!🙂

      Sincerely,
      Kiran Patil

  23. kat / Jun 11 2013 10:06 am

    Hello there, I think your site might be having web browser compatibility
    problems. When I take a look at your blog in Safari, it looks fine however, when
    opening in I.E., it has some overlapping issues.
    I merely wanted to give you a quick heads up! Other
    than that, great website!

  24. pra / Mar 5 2014 12:41 pm

    thanks a lot..
    i was stuck in that problem from last few days..and finally i solved it by your blog..thank u so much

  25. Johnf982 / Apr 27 2014 3:54 pm

    Nice read, I just passed this onto a friend who was doing some research on that. And he just bought me lunch since I found it for him smile So let me rephrase that Thank you for lunch! Whenever you have an efficient government you have a dictatorship. by Harry S Truman. ggbabccbacef

  26. Johne935 / Apr 27 2014 3:54 pm

    I do not even know how I stopped up here, however I assumed this put up was good. I do not recognise who you are however definitely you’re going to a wellknown blogger for those who are not already dbaabgefegdg

  27. Johnk176 / Apr 27 2014 3:54 pm

    Really informative blog article.Really thank you! Want more. ekcffckdkgac

  28. Johne817 / Apr 27 2014 3:58 pm

    Hi my friend! I want to say that this post is amazing, great written and include almost all significant infos. I’d like to see more posts like this. gdkfcdbddgfk

  29. parul / Dec 1 2014 9:59 am

    thanks alot.. i ws juggling alot to get the solution..
    it worked like magic…

Trackbacks

  1. 2010 in review « A Place for C Sharpers/.Netters

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: