“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

  • 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

  • Tried this…but didn’t work out !

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

    Regards,
    Kris

  • 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….

  • 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;
    }

  • 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();
    }

  • 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.

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

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

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

  • 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 .

  • 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

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

    • 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

  • 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!

  • 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

  • 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

  • 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

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

  • 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

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

Comments are closed.