vb- networkstream write only returns first result (need all) - vb.net

My code looks very similar to this post Read bytes from NetworkStream (Hangs), which I copied below. ( I realize this is c# - I need a vb solution)
// Create a TcpClient.
// Note, for this client to work you need to have a TcpServer
// connected to the same address as specified by the server, port
// combination.
TcpClient client = new TcpClient(server, port);
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
// Get a client stream for reading and writing.
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
Console.WriteLine("Sent: {0}", message);
// Receive the TcpServer.response.
// Buffer to store the response bytes.
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("Received: {0}", responseData);
// Close everything.
stream.Close(); client.Close();
My issue lies in this:
I have a form that takes user input on which tif file(s) to find (which ends up being the getBytes(message) ). When one does this, it always returns one result - the first tif file that fits the criteria, However, I know in certain instances I should recieve more than one match.
Then I send the results to a picturebox and should be able to scroll through results (which this part works fine)
I've tried a few ways to get multiple results, but maybe I'm missing the obvious? My best guess is using the asyncronous beginread/write....
I've attempted using a for loop but I end up getting a bunch of the same tif files as a result...
Could anyone help me (even with a generic direction)? I'm not a pro. Thanks in advance for the help.

I ended up finding out what the issue was. the data i was looking for wasn't standardized as so the results were the same data over and over. I changed what items I was looking for and tada it worked. anyway, thanks for the help

Related

How to deserialise a proto that was received as a byte[]

I am using the Spring.Rest framework.
If we receive a 402, the body will contain a proto which in turn will contain various error information.
The Exception raised on a 402 is an instance of Spring.Rest.Client.HttpClientErrorException.
The response within the exception is an instance of Spring.HttpResponseMessage.
The Body within the response is of type byte[].
This means I have a byte[] while the Deserialiser is expecting a Stream.
In order to deserialise the proto contained in the body I have done the following:
MemoryStream mStream = new MemoryStream();
mStream.Write(exception.Response.Body,0,exception.Response.Body.Length);
var proto = Serializer.Deserialize<XXXRestProtoException>(mStream);
when I inspect the proto returned, its properties are all null.
Is my approach correct, or do I need to do more before presenting the Stream to the Deserialize method?
We have confirmed that the proto definitions used on Client and Server are in sync and the body is well formed on the server.
The Stream produced by this code has the same length and contents as the given byte[], which in turn matches the content-length header.
If you Write to a stream, then the Position is left at the end of the stream; 2 simple options:
rewind the stream; between the Write and the Deserialize, put:
ms.Position = 0;
initialize the stream from the blob:
MemoryStream mStream = new MemoryStream(exception.Response.Body);
I'd usually use the latter.

Restful WCF Service - returning byte[]?

I'm working with a RESTful WCF service. One of the service methods returns byte[] (which contains a file).
On the client side, I have some code that uses the WebRequest class to invoke that particular service method. Using the WebRequest, I'm getting the response stream like:
Stream stream = webReq.GetResponse().GetResponseStream();
From this stream, I am then reconstructing a byte[] and then outputting the File locally. The problem is that the reconstructed file on the client-side doesn't resemble the file that was returned from the service side (I get a corrupt PDF file that is much larger in size than the one sent from the service side). Just before the service method returns the byte[], I outputted that byte[] to disk on the service side and it created the file fine... This points to something going wrong between that method returning the byte[] and my client side reconstructing the byte[] from a Stream on the client side... to reconstruct the byte[] from the Stream, I'm using the following method which someone posted in the past on stackoverflow:
public static byte[] ReadFully(Stream input)
{
byte[] buffer = new byte[16*1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
Any ideas what could be going wrong?
I guess that the response from the server contains some envelope in addition to the raw bytes. Like a XML envelope or something. Which would of course suppose that the bytes are base64 encoded string in the response because you cannot store binary data into XML. It would also explain why you are getting a bigger buffer on the client than the actual PDF that the server has sent.
This will of course depend on what binding your WCF service uses and how is it configured. When you dump the contents of the MemoryStream you are reading on the client what exactly do you see? This should give you further hints on how the actual PDF file is encoded in the HTTP response body.

Stream text to client via handler ASP.NET

To get around twitters streaming API not having a crossdomain file to access it from client side( in this case Silverlight) I have made a Generic Handler file in a web project which basically downloads the stream from twitter and as it reads it, writes it to the client.
Here is the handler code:
context.Response.Buffer = false;
context.Response.ContentType = "text/plain";
WebRequest request = WebRequest.Create("http://stream.twitter.com/1/statuses/filter.json?locations=-180,-90,180,90");
request.Credentials = new NetworkCredential("username", "password");
StreamReader responseStream = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.GetEncoding("utf-8"));
while (!responseStream.EndOfStream)
{
string line = "(~!-/" + responseStream.ReadLine() + "~!-/)";
context.Response.BinaryWrite((Encoding.UTF8.GetBytes(line)));}
And this does work, but the problem is that once the client disconnects the handler just carry's on downloading. So how do I tell if the client is still busy receiving the request and if not, end the while loop?
Also, my second problem is that on the client side doing a "ReadLine()" does nothing, presumably because it is counting the entire stream as one line so never gets the full response. To work around that I read it byte by byte and when it sees "(~!-/" around something it know that is one line. VERY hacky, I know.
Thanks!
Found the answer!
while (context.Response.IsClientConnected)
:)

Optimizing HttpWebResponse - GetResponse

I'm using the following lines of code to read the response of an asynchronous HttpWebRequest. This seems to be the largest amount of time spent in a particular operation. Is there anything I can optimize here?
System.Net.HttpWebResponse oResp =(System.Net.HttpWebResponse)oReq.EndGetResponse(oResult);
oResp = (HttpWebResponse)oReq.GetResponse();
StreamReader oStreamReader = new StreamReader(oResp.GetResponseStream());
string sResponse = oStreamReader.ReadToEnd();
...goes on to make an XmlDocument, append some more XML to it, then perform an XSL transform.
Creating the Connections:
HttpWebRequest oReq;
oReq = (HttpWebRequest)WebRequest.Create(sUrl + sQueryString);
oReq.ContentType = sContentType;
oReq.Method = "POST";
oReq.ContentLength = aBytes.Length;
Stream oStream = oReq.GetRequestStream();
oStream.Write(aBytes, 0, aBytes.Length);
oStream.Close();
AsyncState oState = new AsyncState(oReq);
return oReq.BeginGetResponse(fCallBack, oState);
I found one major improvement to the scheme I was using. Rather than using the StreamReader and ReadToEnd to get the Stream into a string, only then to convert it into an XmlDocument. I skipped the middle man and converted the Stream directly into a XmlDocument.
This left me with another problem though, I had to change the parent of the XmlDocument to fit my Xslt (there are a great many and they all expect the structure I had). See How can I add new root element to a C# XmlDocument? for that fix.
This has given me a roughly 2/3 decrease in the time taken to process the results of the webservice call, and a great decrease in the amount of memory used. In the previous version, the response xml was in memory two different times (maybe three if the stream counts)!
In addition, removing the extra GetResponse seemed to help.
using (HttpWebResponse oResp = (HttpWebResponse)oReq.EndGetResponse(oResult))
{
oXml.Load(oResp.GetResponseStream());
XmlNode oApiResult = oXml.RemoveChild(oXml.DocumentElement);
oXml.LoadXml(sOtherXml);
oXml.DocumentElement.AppendChild(oApiResult);
}

Why am I getting System.FormatException: String was not recognized as a valid Boolean on a fraction of our customers machines?

Our c#.net software connects to an online app to deal with accounts and a shop. It does this using HttpWebRequest and HttpWebResponse.
An example of this interaction, and one area where the exception in the title has come from is:
var request = HttpWebRequest.Create(onlineApp + string.Format("isvalid.ashx?username={0}&password={1}", HttpUtility.UrlEncode(username), HttpUtility.UrlEncode(password))) as HttpWebRequest;
request.Method = "GET";
using (var response = request.GetResponse() as HttpWebResponse)
using (var ms = new MemoryStream())
{
var responseStream = response.GetResponseStream();
byte[] buffer = new byte[4096];
int read;
do
{
read = responseStream.Read(buffer, 0, buffer.Length);
ms.Write(buffer, 0, read);
} while (read > 0);
ms.Position = 0;
return Convert.ToBoolean(Encoding.ASCII.GetString(ms.ToArray()));
}
The online app will respond either 'true' or 'false'. In all our testing it gets one of these values, but for a couple of customers (out of hundreds) we get this exception System.FormatException: String was not recognized as a valid Boolean Which sounds like the response is being garbled by something. If we ask them to go to the online app in their web browser, they see the correct response. The clients are usually on school networks which can be fairly restrictive and often under proxy servers, but most cope fine once they've put the proxy details in or added a firewall exception. Is there something that could be messing up the response from the server, or is something wrong with our code?
Indeed, it's possible that the return result is somehow different.
Is there any particular reason you are doing the reasonably elaborate method of reading the repsonse there? Why not:
string data;
using(HttpWebResponse response = request.GetResponse() as HttpWebResponse){
StreamReader str = new StreamReader(response.GetResponseStream());
data = str.ReadToEnd();
str.Close();
}
string cleanResult = data.Trim().ToLower();
// log this
return Convert.ToBoolean(cleanResult);
First thing to note is I would definitely use something like:
bool myBool = false;
Boolean.TryParse(Encoding.ASCII.GetString(ms.ToArray()), myBool);
return myBool;
It's not some localisation issue is it? It's expecting the Swahili version of 'true', and getting confused. Are all the sites in one country, with the same language, etc?
I'd add logging, as suggested by others, and see what results you're seeing.
I'd also lean towards changing the code as silky suggested, though with a few further changes from me (code 'smell' issues, IMO); Use using around the stream reader, as well as the response.
Also, I don't think the use of as is appropriate in this instance. If the Response can't be cast to HttpWebResponse (which, admittedly is unlikely, but still) you'll get a NullRef exception on the response.GetResponseStream() bit which is both a vague error, and you've lost the original line number. Using (HttpWebResponse)request.GetResponse() will give you a more correct error, and the correct line number of the actual error.