Thursday, January 13, 2011

Error The underlying connection was closed: The connection was closed unexpectedly in WCF

I found something interesting today.You will observe that if you  have a WCF service returning  a DataTable and if you try using that DataTable in an APP, then it will error out as follows

The underlying connection was closed: The connection was closed unexpectedly

This will occur if you use code as follows in the DataTable

public DataTable GetDetails(String _course)
    {
        DataTable dt = new DataTable();

        dt.Columns.Add(new DataColumn("TopicID", typeof(String)));
        dt.Columns.Add(new DataColumn("TopicName", typeof(String)));

       
        XmlDocument _doc = new XmlDocument();
        _doc.Load(HostingEnvironment.ApplicationPhysicalPath + @"App_Data/Courses.xml");

        XmlNodeList _nodelst = _doc.SelectNodes("//Course[@name='" +_course.ToString() + "']/Topic");

        foreach (XmlNode _node in _nodelst)
        {
        
            dt.Rows.Add(_node.Attributes["id"].InnerText,_node.Attributes["title"].InnerText);
        }

        return dt;
      
    }


The solution to this problem is very simple as I found out.All you would need to do is give a name to the DataTable i.e just replace the code as         DataTable dt = new DataTable(); to         DataTable dt = new DataTable("Test");