Hi.
This question is based on a previous question: https://www.ghielectronics.com/community/forum/topic?id=12569
I’m having trouble downloading a file from a .net web Api onto a G120. The file is around 400 kb in size and I have never experienced downloading the file via the Api when connecting through, for instance WebFetch or when running the code below in the full framework.
On the G120, sometimes it works, sometimes not. When not working it is as if the data are not coming to the device. That is, input.DataAvailable is false and remains false. Note that it never fails directly but often after perhaps 1/10 of the data has been downloaded.
Does anyone have any idea of why it fails and have any suggeestion on how I can solve the problem?
public bool GetServerStream(string url, Stream outputStream, HashAlgorithmType checksumHashType, out byte[] checkSum)
{
checkSum = null;
bool succeeded = false;
byte[] buffer = new byte[4096];
byte[] oldBuffer = new byte[4096];
int bytesRead, oldBytesRead, awaitTime;
long totalBytesRead;
byte[] check = new byte[0];
HashAlgorithm hash = new HashAlgorithm(checksumHashType);
hash.Initialize();
if (_ethernet.EthernetIsConnected)
{
using (HttpByteStreamRequest request = HttpByteStreamRequest.Create(url))
{
request.Method = "GET";
var response = request.GetResponse();
if (response.StatusCode == 200)
{
NetworkStream input = response.GetResponseStream();
bytesRead = input.Read(buffer, 0, buffer.Length);
totalBytesRead = bytesRead;
do
{
oldBytesRead = bytesRead;
oldBuffer = buffer;
buffer = new byte[4096];
if (totalBytesRead < response.ContentLength)
{
awaitTime = 0;
while (!input.DataAvailable)
{
Thread.Sleep(1000);
Debug.Print("Awaiting data");
awaitTime += 1000;
if (awaitTime >= 1000 * 20)
{
throw new HttpGetException("Server stream timeout");
}
}
bytesRead = input.Read(buffer, 0, buffer.Length);
totalBytesRead += bytesRead;
Thread.Sleep(500);
Debug.Print("Read: " + bytesRead.ToString());
}
else
{
bytesRead = 0;
}
if (bytesRead == 0)
{
hash.TransformFinalBlock(oldBuffer, 0, oldBytesRead);
}
else
{
hash.TransformBlock(oldBuffer, 0, oldBytesRead, oldBuffer, 0);
}
outputStream.Write(oldBuffer, 0, oldBytesRead);
}
while (bytesRead > 0);
checkSum = hash.Hash;
succeeded = true;
input.Close();
}
else
{
succeeded = false;
}
}
}
else
{
throw new HttpGetException("Ethernet is down");
}
return succeeded;
}