Unable to read beyond the end of stream? - c#

Trying to read a string from a BinaryReader as following:
var req = HttpWebRequest.Create( url + context.Request.Url.Query + "&cql_filter=strSubstring(codigo,0,3)=%27" + 201 + "%27");
var resp = req.GetResponse();
var stream = resp.GetResponseStream();
var br = new BinaryReader(stream);
var texto = br.ReadString();
But I get the title exception. Tried to solve it as mentioned here, but I can't do sizeof(String).
var count = br.BaseStream.Length / sizeof(String);
for (var i = 0; i < count; i++)
{
string v = br.ReadString();
texto = texto + v;
}
How can I solve this? Thanks!

Related

BSON Encoding and Decoding C#

I used this code to decode bytes sent from the server
packets = SimpleBSON.Load(ReceivedBytes);
for (int i = 0; i < packets["mc"]; i++)
{
BSONObject packet = packets["m" + i] as BSONObject;
//here i can use the received packet
packet["hey"] = "hello";
}
But I am struggling in encoding it back again
I am using Kernys.BSON
I tried this
var obj = new BSONObject();
obj["m" + 0] = new BSONObject();
obj["m" + 0]["hey"] = "hi";
But for some reason this is not working
this is how I fixed it
var GPd = new BSONObject();
GPd["m" + 0] = new BSONObject();
GPd["m" + 0]["hey"] = "hi";
GPd["mc"] = 1;
byte[] mainsend = SimpleBSON.Dump(GPd);
MemoryStream memoryStream = new MemoryStream();
using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream))
{
byte[] bsonDump = SimpleBSON.Dump(GPd);
binaryWriter.Write(bsonDump.Length + 4);
binaryWriter.Write(bsonDump);
}
//memorystream.ToArray is the encoded bytes
}

computing git blob hash in c#

I am trying to compute the sha1 of a file using the below method. The result is different from what is reported by "git ls-tree HEAD". What's wrong with my code?
static public string ComputeSha1()
{
//"blob " + <size_of_file> + "\0" + <contents_of_file>
var content = File.ReadAllBytes(#"c:\projects\myproj\Word.docx");
var contentLength = Encoding.UTF8.GetByteCount(Encoding.UTF8.GetString(content));
var blob = "blob " + contentLength + "\0" + Encoding.UTF8.GetString(content);
using (SHA1 sha1 = SHA1.Create())
{
byte[] bytes = sha1.ComputeHash(Encoding.UTF8.GetBytes(blob));
StringBuilder builder = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
builder.Append(bytes[i].ToString("x2"));
}
return builder.ToString();
}
}

Convert Opus (.ogg) to PCM (.wav) in .NET

I have a file .ogg and i need to convert it to .wav. I'm tryng to use Opus.Net (that use NAudio) but i get this exception in OpusDecoder.Decode():
"System.Exception: 'Decoding failed - InvalidPacket'"
This is the code:
byte[] audioBynary = File.ReadAllBytes($"{filePath}{fileOgg}");
_decoder = OpusDecoder.Create(48000, 1);
var pcmBinary = _decoder.Decode(audioBynary, audioBynary.Length, out int decodedLenght);
WaveFileWriter.CreateWaveFile($"{filePath}{fileWav}", new WaveFileReader(new MemoryStream(pcmBinary)));
This works for me, I read the ogg/opus file with Concentus, copy it's bytes to a memoryStream and then use it to create a RawSourceWaveStream.
I can get an ISampleProvider from the RawSourceWaveStream, which is what you need to feed
WaveFileWriter.CreateWaveFile16.
Voilá
var filePath = $#"C:\Users\blabla\foo\bar\";
var fileOgg = "testAudio.ogg";
var fileWav = "testAudio.wav";
using (FileStream fileIn = new FileStream($"{filePath}{fileOgg}", FileMode.Open))
using (MemoryStream pcmStream = new MemoryStream())
{
OpusDecoder decoder = OpusDecoder.Create(48000, 1);
OpusOggReadStream oggIn = new OpusOggReadStream(decoder, fileIn);
while (oggIn.HasNextPacket)
{
short[] packet = oggIn.DecodeNextPacket();
if (packet != null)
{
for (int i = 0; i < packet.Length; i++)
{
var bytes = BitConverter.GetBytes(packet[i]);
pcmStream.Write(bytes, 0, bytes.Length);
}
}
}
pcmStream.Position = 0;
var wavStream = new RawSourceWaveStream(pcmStream, new WaveFormat(48000, 1));
var sampleProvider = wavStream.ToSampleProvider();
WaveFileWriter.CreateWaveFile16($"{filePath}{fileWav}", sampleProvider);

C# FileStream reads bytes incorrectly

I am trying to develop an app that will upload large files to a web server running PHP. Almost immediately, I stumbled upon a problem that the file is not split correctly.
Currently I have this piece of code
string adrese = "c:\\directory\\file.jpg";
int garums = 16384;
String ext = Path.GetExtension(adrese);
FileStream file = /*/File.Open(adrese, FileMode.Open);/*/
new FileStream(adrese, FileMode.Open, System.IO.FileAccess.Read);
long fgar = file.Length; //100%
long counter = garums;
first = true;
byte[] chunk = new byte[garums];
while (true)
{
int index = 0;
//long Controll = counter+garums;
while (index < chunk.Length)
{
int bytesRead = file.Read(chunk, index, chunk.Length - index);
if (bytesRead == 0)
{
/*byte[] biti = new byte[index];
for (int i = 0; i < index; i++)
{
biti[i] = chunk[i];
}
chunk = new byte[index];
chunk = biti;*/
break;
}
index += bytesRead;
}
if (index != 0) // Our previous chunk may have been the last one
{
byte[] biti = new byte[index];
for (int i = 0; i < index; i++)
{
biti[i] = chunk[i];
}
chunk = new byte[index];
chunk = biti;
// index is the number of bytes in the chunk
sutam(Convert.ToBase64String(chunk),ext);
}
double procentuali = ((counter * 100) / fgar);
if (procentuali > 99)
{
procentuali = 100;
}
progressBar1.Value = (int)Math.Round(procentuali);
label1.Text = "" + procentuali;
counter = counter+garums;
if (index != garums) // We didn't read a full chunk: we're done
{
return;
}
}
file.Close();
Everything works if I set garums to 1, but who will wait for a year or so to upload a file sized multiple GB's.
I would be pleased if you could tell me what is wrong and how to fix this.
Try this instead to upload in chunks:
private void ConvertToChunks()
{
//Open file
string file = MapPath("~/temp/1.xps");
FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
//Chunk size that will be sent to Server
int chunkSize = 1024;
// Unique file name
string fileName = Guid.NewGuid() + Path.GetExtension(file);
int totalChunks = (int)Math.Ceiling((double)fileStream.Length / chunkSize);
// Loop through the whole stream and send it chunk by chunk;
for (int i = 0; i < totalChunks; i++)
{
int startIndex = i * chunkSize;
int endIndex = (int)(startIndex + chunkSize > fileStream.Length ? fileStream.Length : startIndex + chunkSize);
int length = endIndex - startIndex;
byte[] bytes = new byte[length];
fileStream.Read(bytes, 0, bytes.Length);
ChunkRequest(fileName, bytes);
}
}
private void ChunkRequest(string fileName,byte[] buffer)
{
//Request url, Method=post Length and data.
string requestURL = "http://localhost:63654/hello.ashx";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestURL);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// Chunk(buffer) is converted to Base64 string that will be convert to Bytes on the handler.
string requestParameters = #"fileName=" + fileName + "&data=" + HttpUtility.UrlEncode( Convert.ToBase64String(buffer) );
// finally whole request will be converted to bytes that will be transferred to HttpHandler
byte[] byteData = Encoding.UTF8.GetBytes(requestParameters);
request.ContentLength = byteData.Length;
Stream writer = request.GetRequestStream();
writer.Write(byteData, 0, byteData.Length);
writer.Close();
// here we will receive the response from HttpHandler
StreamReader stIn = new StreamReader(request.GetResponse().GetResponseStream());
string strResponse = stIn.ReadToEnd();
stIn.Close();
}

c# ASP HttpWebRequest Multipart Upload XML and Images

I´ve (tried to) Customize a Method i found here on Stackoverflow to enable a Multipart Upload of one XML File and multiple Images, to process a HTTPWebRequest out a Sharepoint WebPart. For my shame i ve to say that I´m really not familar with that HttpRequest and StreamUpload thing, it`s the first time i seriously try to handle this.
Here`s my coding:
public XmlDocument DoHttpUploadFile(string url, string[] file, string[] paramName, string[] contentType, NameValueCollection nvc, NameValueCollection headerItems, string xmlFileName)
{
var xmlDox = new XmlDocument();
var totalLength = 0;
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
const string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
// First Loop is just need to get the Length of all Parts
for (int i = 0; i < file.Length; i++)
{
string header = "";
if (i == 0)
{
header = string.Format(headerTemplate, paramName[i], xmlFileName, contentType[i]);
}
else
{
var filename = Path.GetFileName(file[i]);
header = string.Format(headerTemplate, paramName[i], filename, contentType[i]);
}
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
var headerLength = headerbytes.Length;
var boundaryLength = boundarybytes.Length;
totalLength = totalLength + headerLength + boundaryLength;
if (file[i].StartsWith("<"))
{
byte[] xmlBytes = System.Text.Encoding.UTF8.GetBytes(file[i]);
var xmlLength = xmlBytes.Length;
totalLength = totalLength + xmlLength;
}
else
{
var client = new WebClient();
var img = new Image { ImageUrl = file[i] };
client.UseDefaultCredentials = true;
// image as Byte into Stream
var fileData = client.DownloadData(img.ImageUrl);
var imgLength = fileData.Length;
totalLength = totalLength + imgLength;
}
}
var wr = (HttpWebRequest)WebRequest.Create(url);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.ContentLength = totalLength;
Stream rs = wr.GetRequestStream();
var read = 0;
var finalLength = 0;
for (int i = 0; i < file.Length; i++)
{
string header = "";
if(i==0)
{
header = string.Format(headerTemplate, paramName[i], xmlFileName, contentType[i]);
}
else
{
var filename = Path.GetFileName(file[i]);
header = string.Format(headerTemplate, paramName[i], filename, contentType[i]);
}
rs.Write(boundarybytes, 0, boundarybytes.Length);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
var headerLength = headerbytes.Length;
var boundaryLength = boundarybytes.Length;
finalLength = finalLength + headerLength + boundaryLength;
rs.Write(headerbytes, 0, headerbytes.Length);
if(file[i].StartsWith("<"))
{
var writer = new StreamWriter(rs);
byte[] xmlBytes = System.Text.Encoding.UTF8.GetBytes(file[i]);
var xmlLength = xmlBytes.Length;
finalLength = finalLength + xmlLength;
writer.Write(file[i]);
}
else
{
var getitem = new GetItemFromList();
var client = new WebClient();
var img = new Image {ImageUrl = file[i]};
client.UseDefaultCredentials = true;
// image as Byte into Stream
var fileData = client.DownloadData(img.ImageUrl);
finalLength = finalLength + fileData.Length;
rs.Write(fileData, 0, fileData.Length);
}
}
finalLength.ToString();
rs.Close(); // Here it stops with Exception 'Bytes are not completely written
WebResponse wresp = null;
try
{
wresp = wr.GetResponse();
var wrlength = wr.ContentLength;
var stream2 = wresp.GetResponseStream();
if (stream2 != null)
{
var reader2 = new StreamReader(stream2);
var backstr = reader2.ReadToEnd();
xmlDox.LoadXml(backstr);
}
}
catch (Exception ex)
{
//log.Error("Error uploading file", ex);
if (wresp != null)
wresp.Close();
wresp = null;
}
finally
{
wr = null; }
return xmlDox;
}
It Stops at rs.Close with the Exception 'Cannot Close Stream bytes are not writen complete'.
I thought maybe this depends on wr.ContentLength and tried to set this manually, as you can see in the above section of the coding.
I cant find a solution i tried the last two Day`s and searched all around the web, especially stackeOverflow.
So, if anyone could tell me what going wrong, pleeeease tell me, thx.
"The Exception is thrown because you are writing less bytes than the WebRequest expects. For example if you have set say 75 bytes in the ContentLength property and you write 69 bytes on the ResquestStream and close it the exception will be thrown."
See this post: Cannot close stream until all bytes are written
Can you check the size of TotalLength making sure you are using the byte length and verify in a debugger?

Categories