.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

TCPClient and Read not returning complete data unless I use thread.sleep

Posted By:      Posted Date: October 02, 2010    Points: 0   Category :ASP.Net

Hello experts, here is my code that I have a question on:

 Dim receivedbyte(1024) As Byte
        Dim myread As Integer = 0
        Dim myresponsesb As New StringBuilder()
            myread = myns.Read(receivedbyte, 0, receivedbyte.Length)
            myresponsesb.Append(System.Text.Encoding.UTF8.GetString(receivedbyte, 0, myread))

        Loop While (myns.DataAvailable)

In the above, myns is a networkstream that is initialized with a tcpclient that is communicating with a XMPP server. basically, iam getting back xml messages.

The issue with the above is that if I dont use thread.sleep(500), the complete data is not returned. Why is that? I have tried to use a streamreader instead of read and using that method i can get complete data from the stream. What am I doing wrong with the Read method of networkstream?

SECOND: The XML being returned from the server is not well formed - the closing tag for one of the tags is missing and I am unable to use XDocument to parse this XML because of this. What could be the issue here? Is it my code or something on server end?

Also, what technique should i use to make the returned XML well formed so that I can use XDOCUMENT and LINQ to parse this?


View Complete Post

More Related Resource Links

Entity Data Model and database view returning the same columns as there are in a table


When adding a stored procedure into the Entity Data Model I can select whether the procedure returns a scalar, a (new) complex type or one of the entity types I already defined. 

How do I do something similar for a view?

I mean assuming I have a view like this

CREATE VIEW FilteredFoos as SELECT Foo.* FROM Foo join ... WHERE ...

(that is a view that implements some involved filtering, but returns all columns from one table) how do I add it to the project so that I can use the entity set, but get the Foo objects, not some new FilteredFoo objects.

var foos = myDB.FilteredFoos.Include("Bar").ToList();

foreach (Foo foo in foos) { ...

Thanks, Jenda

Creating a SharePoint 2010 Web Part That Can Read and Write Data to an External Data Source

Learn to use Visual Studio 2010 to create a Visual Web Part that uses a BCS external content type in SharePoint Server 2010 to read and write data to the AdventureWorks sample database.

Sample: Creating a SharePoint 2010 Web Part That Can Read and Write Data to an External Data Source

Explore the code in this visual how-to article as you learn to use Visual Studio 2010 to create a Visual Web Part that uses a BCS external content type in SharePoint Server 2010.

System.InvalidOperationException: Invalid attempt to read when no data is present.


Invalid attempt to read when no data is present.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.InvalidOperationException: Invalid attempt to read when no data is present.

Source Error: 

Line 53:             if (reader.HasRows)
Line 54:             {
Line 55:                 Response.Write(reader.GetString(0));

Here is my code:

System.IO.IOException: Unable to read data from the transport connection

Hello,   I have an xml webservice calling another xml web service and occasionally i get the following error - any ideas why?Does this happen when the request is made or when reading the response? Also how i can prevent it from happening? Thanks   System.IO.IOException: Unable to read data from the transport connection: A blocking operation was interrupted by a call to WSACancelBlockingCall. ---> System.Net.Sockets.SocketException: A blocking operation was interrupted by a call to WSACancelBlockingCall   at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)   --- End of inner exception stack trace ---   at System.Net.ConnectStream.Read(Byte[] buffer, Int32 offset, Int32 size)   at System.IO.StreamReader.ReadBuffer(Char[] userBuffer, Int32 userOffset, Int32 desiredChars, Boolean readToUserBuffer)   at System.IO.StreamReader.Read(Char[] buffer, Int32 index, Int32 count)   at System.Xml.XmlTextReaderImpl.ReadData()   at System.Xml.XmlTextReaderImpl.InitTextReaderInput(String baseUriStr, TextReader input)   at System.Xml.XmlTextReaderImpl..ctor(String url, TextReader input, XmlNameTable nt)   at System.Xml.XmlTextReader..ctor(TextReader input)   at System.Web.Services.Protocols.SoapHttpClientProtocol.GetReaderForMessage(SoapClientMessage message, I

Read data from BLOB field and write to sharepoint list

Hi, I want to read the data from BLOB field and write it into sharepoint list item. Please provide some pointer to archive above objective.   Thanks in Advance.

SslStream.Read() - Returns invalid data

Hey,I am currently attempting to implement a multi-threaded C# socket, using SSL (.pem file/certification/private key combo) server using Visual Studio C# Express.I have successfully made the client application establish a connection, and send data, which appears in plain, de-crypted text on the server - this works.However, I am 'polling' the socket to see if data is available to read.Here is some code which is appropriate:----        public void Process(int threadId)        {            int BytesRead = 0;            try            {                Master.Log("BEGIN READ");                sslStream.ReadTimeout = 5000;                BytesRead = sslStream.Read(bytes, 0, bytes.Length);                Master.Log("READ " + BytesRead + " bytes");                if ( BytesRead > 0 )                {                   // process                }             } catch (IOException e) {                Log("Caught IOException: " + e.Message);                if (e.InnerException != null)                    Log("=========> INNER IOException: " + e.InnerException.Message);         }---- Here is some console output when running the application:---------LOG: Authentication successfulLOG: BEGIN READLOG: READ 140 bytesLOG: [Thread 0] [Client 1] [Address] Client.ProcessDataReceived()Text received from client: Testing

Cannot read the next data row for the data set

Hi, My report runs fine when I view in VS, data shows fine when I run the query in the data window, but when I publish it to the server, I get the above error. I am running SQL server 2005 RTM and I have re-deployed the entire solution. Any ideas?

read data from excel

hi all,i had 2 columns in the excel file one is SNo and another Descriptionlooks like belowSno                         Description1                              1/2 Feet2                               1/5 Feet3                              204                               30i read the data from this file using below codestring strFileName = FileUpload1.PostedFile.FileName;            string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + strFileName + ";" + "Extended Properties=Excel 8.0;";            OleDbC

Not able to read Config File data in Windows Service

While I'm trying to read connection string which is in App.Config file I'm getting error like "Object reference not set to an instance of an object." string strconn = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"].ToString(); For the windows service where I need to keep app.config file and how to integrate that config file with the windows service exe file. Thanks in advance.

how to read a custom dynamic data meta data attribute in a field template

All --Please help.I need to know how to read a custom dynamic data meta data attribute in a field template.I know how to do it in a page template because I have a handle to the meta table on the page.However, I do not know how to get a handle to the meta column at run time in a field template.Can you help?Please advise.Thank you.-- Mark Kamoski

How to read a complete column from the dataset

I want to read complete column from the dataset using select command or whatever without looping the rows of the table.Because in table i got 35000 records i only want to read a one complete column from the top to the end using dataset.Eg: select column_name from table.lly, dataset.tables[0].select["Column='Product'"]I have tried with this but throwing exception.I was trying to get it but not able to find an answer.Please do the needful.Its very urgent.Suchitra.

Read Binary Data which is nothing but a Zip file and unzip through SSIS 2005 SP2

Hi ALL, I need some help in developing a task. I have a source database which is Oracle and it has a ZIP file stored inside the database in Binary format. When I move this data into the sql server 2005 database I get the data as binary data. Now the task begins with SSIS, I need to read the binary data which gives us a zip file and then unzip this zip file and read the XML data which is present inside the Zip file. I beleive some one might have already developed this task can you share the solution with us. Note: As this has to be moved into production I dont have permission to use third party tools like Cozy roc or install winrar.exe and simpy calling this exe from the execute process task in SSIS.  Raju

Rare exception: Unable to read data from the transport connection: An existing connection was forcib

Our .NET 2.0 app relies upon the ability to download xml webpages from URLs.  At startup, we have about 6 boxes in the wild (out of thousands) that are seeing the following inner exception when they try to download an xml page.  System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive. (Inner: ) System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. They can get to the URL in their browser just fine, so we know our server is working.  Furthermore, the embedded WebBrowser control in our app can pull up webpages just fine, so I don't think their firewall is blocking our app.  I'm hoping it's just some diagnosible configuration issue.  Here is the snippet of code that does the downloading: WebRequest request = WebRequest.Create(fileToDownload.SourceUri);request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);request.Timeout = (int)DefaultTimeout.TotalMilliseconds;request.Method = "HEAD";WebResponse response = request.GetResponse(); Nothing revolutionary there. (I've also tried it without the HEAD request, without keepalive, and using HTTP 1.0).  And here is the exception: System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive. StackTrace Infor

Data Flow Tasks does not complete even though data transfer has ended

I have an SSIS 2008 package which contains a number of SQL Tasks and Data Flow tasks with precedence.  When I run each of the tasks separately, the transfer is completed, and sometimes the data flow task turns green, but sometimes it does not.  When I run the package as a whole from my workstation, a few of the tasks compete but then all processing stops.  There are no errors, the package just sits there.  The objects within the Data Flow tasks are green and the data transfer is completed, but the task is yellow and the package does not move on to the next task. Each of the Data Flow tasks consists of one ADO.Net Source to an ODBC driver for Cache and an OLDB Destination to a SQL Server database.  I can monitor the source connections and I can see when the successful transfer activity stops.  However, the package does not close the connection and move on to the next task. I have tried different levels of precedence and even allow all of the tasks to run in parallel and it does not seem to matter.

How to read an Excel file and show data from 2 columns

Hi,I have an Excel file called Products.xls .I have Columns A and B, with the titles NAME and QUANTITY.The name of the sheet is SHEET1.The file has about 40 lines.How do i show these data on a Gridview or Listview ?Thank you.

Read from and write to Data Base an Image

Hi guys. How can I show a saved picturs from data base into a Image control? And how can I save an Image from my web page into data base? (with less code pleeeaaase.)
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend