Sending object from Android Client App to C# Server App - c#

Java Code:
public class EMessage implements Serializable
{
private Bitmap image;
private String type;
EMessage()
{}
}
...
EMessage eMessage=new EMessage();
outToServer = new DataOutputStream(clientSocket.getOutputStream());
objectOutputStream=new ObjectOutputStream(outToServer);
objectOutputStream.writeObject(eMessage);
C# Code:
[Serializable]
class EMessage
{
private Bitmap image;
private String type;
EMessage()
{ }
}
client = server.AcceptTcpClient();
Connected = client.Connected;
ns = client.GetStream();
IFormatter formatter = new
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
EMessage recievedmsg = (EMessage)formatter.Deserialize(ns);
When I send an object from Android Client App (java coded) and I recieve the object in C# Server App but with an Exception.
"The Input Stream is not a valid binary format. The Starting Content(in bytes) are:
00-05-73-72-00-1D-63-6F-6D-2E etc";
Please suggest any simple solution. My project isn't that much complex. I just need to send an EMessage object.

Serialization formats are specific to the platforms, and Java and .NET serialization aren't compatible with each other. Use JSON instead (and it's easier to debug as well).

Why not use SOAP, here's an article on exactly what you're doing (android to .net)
http://www.codeproject.com/Articles/29305/Consuming-NET-Web-Services-via-the-kSOAP-library

I suggest you drop the Serialization for the above mentioned reasons (Java serialization being different from C# serialization), and transfer your data between your Java and C# applications in plain byte arrays.
You can convert your Bitmap image to a byte array like so (taken from this post on SO):
Bitmap bmp = intent.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Of course you could change the CompressFormat if circumstances so require. After that, you could convert your type string to a byte array too, and add a null-terminator to the end of it.
Once you're there, you can send your type string first, and add the byte array of the bitmap after it. On the C# end, you could read the incoming data until you reach the 0 terminator, at which point you'll know you've read the string portion of your EMessage object, and then read the rest of the bytes you've sent over and parse them into a Bitmap object.
That way you'll be sure that between your Java and C# implementations, you won't run into any compatibility issues. It may require a bit more code and a little more understanding to do, but it's far more reliable than serializing between two languages.

Related

Base64.getEncoder().encode and generate PDF in C#

I am working on a project that uses a web service developed in Java. The response of this web service is a json file with a key generated with this java method (Base64.getEncoder().encode(array), where "array" is byte[]. This key is supposedly a binary to generate the pdf, but as much as I try, the pdf is not generated correctly, it cannot be opened.
Can anybody help me to generate a pdf with this response in C#?
You need to convert from Base64, to byte and then get the pdf:
Check this example:
string base64EncodedFile = // Get the string representation from the api
using (System.IO.FileStream stream = System.IO.File.Create("c:\\saved.pdf))
{
System.Byte[] byteArray = System.Convert.FromBase64String(base64EncodedFile);
stream.Write(byteArray, 0, byteArray.Length);
}
For more information check wikipedia on base 64
Base64 is a way to encode binary data into an ASCII character set
known to pretty much every computer system, in order to transmit the
data without loss or modification of the contents itself
And that is why the java service does the conversion.

Send Pillow/numpy image over ZeroMQ socket

I need to take a Pillow image and either convert it to a byte array or pack it somehow to send it over a ZeroMQ socket. Since the other socket connection isn't in python (it's c#), I can't use pickle, and I'm not sure JSON would work since it's just the image (dimensions sent separately). I'm working with an image created from a processed numpy array out of opencv, so I don't have an image file. Sending the numpy array over didn't work, either.
Since I can't read the image bytes from a file, I've tried Image.getdata() and Image.tobytes() but I'm not sure either were in the right form to send over the socket. What I really need is a bytestream that I can reform into an array after crossing the socket.
UPDATE: So now I'm specifically looking for anything easily undone in C#. I've looked into struct.pack but I'm not sure there's an equivalent to unpack it. Turning the image into an encoded string would work as long as I could decode it.
UPDATE 2: I'm thinking that I could use JSON to send a multidimensional array, then grab the JSON on the other side and turn it into a bitmap to display. I'm using clrzmq for the C# side, though, and I'm not sure how that handles JSON objects.
In case anyone was wondering, here's what I ended up doing:
On the python side:
_, buffer = cv2.imencode('.jpg', cFrame )
jpg_enc = base64.b64encode(buffer).decode('utf-8')
self.frameSender.send_string(jpg_enc)
self.frameSender.send_string(str(height))
self.frameSender.send_string(str(width))
On the C# side:
byte[] bytebuffer = Convert.FromBase64String(frameListener.ReceiveFrame().ReadString());
int height = int.Parse(frameListener.ReceiveFrame().ReadString());
int width = int.Parse(frameListener.ReceiveFrame().ReadString());
using (MemoryStream ms = new MemoryStream(bytebuffer)) //image data
{
Bitmap img = new Bitmap(Image.FromStream(ms), new Size(height, width));
pictureboxVideo.BeginInvoke((MethodInvoker)delegate{pictureboxbVideo.Image = img;});
}

protobuf-net - Serialize class and save it to object

I have been using a Xml serializer to serialize an class and saved it into an object which i later will send to a server. Due the amount of messages i send to the server i decided to change the serialization method into something that will result into something smaller in size.
I found protobuf-net but i only did find documentation about how to serialize a class into a file stream. It seems to me that saving to a file then send it to the server would not be very effective if you send over 100 packages every second.
So my question is , how can i serialize a class and save it into an object?
protobuf-net can write to (or read from) any Stream implementation. FileStream is just an example. In the case of communications between machines, this could be a NetworkStream. If you just want to get an in-memory form, then use MemoryStream. For example:
byte[] chunk;
using(var ms = new MemoryStream())
{
Serializer.Serialize(ms, obj);
chunk = ms.ToArray();
}
// now do something interesting with 'chunk'

Manipulating Mp3's as Array Using NAudio

I'm trying to reimplement an existing Matlab 8-band equalizer GUI I created for a project last week in C#. In Matlab, songs load as a dynamic array into memory, where they can be freely manipulated and playing is as easy as sound(array).
I found the NAudio library which conveniently already has Mp3 extractors, players, and both convolution and FFT defined. I was able to open the Mp3 and read all its data into an array (though I'm not positive I'm going about it correctly.) However, even after looking through a couple of examples, I'm struggling to figure out how to take the array and write it back into a stream in such a way as to play it properly (I don't need to write to file).
Following the examples I found, I read my mp3's like this:
private byte[] CreateInputStream(string fileName)
{
byte[] stream;
if (fileName.EndsWith(".mp3"))
{
WaveStream mp3Reader = new Mp3FileReader(fileName);
songFormat = mp3Reader.WaveFormat; // songFormat is a class field
long sizeOfStream = mp3Reader.Length;
stream = new byte[sizeOfStream];
mp3Reader.Read(stream, 0, (int) sizeOfStream);
}
else
{
throw new InvalidOperationException("Unsupported Exception");
}
return stream;
}
Now I have an array of bytes presumably containing raw audio data, which I intend to eventually covert to floats so as to run through the DSP module. Right now, however, I'm simply trying to see if I can play the array of bytes.
Stream outstream = new MemoryStream(stream);
WaveFileWriter wfr = new WaveFileWriter(outstream, songFormat);
// outputStream is an array of bytes and a class variable
wfr.Write(outputStream, 0, (int)outputStream.Length);
WaveFileReader wr = new WaveFileReader(outstream);
volumeStream = new WaveChannel32(wr);
waveOutDevice.Init(volumeStream);
waveOutDevice.Play();
Right now I'm getting errors thrown in WaveFileReader(outstream) which say that it can't read past the end of the stream. I suspect that's not the only thing I'm not doing correctly. Any insights?
Your code isn't working because you never close the WaveFileWriter so its headers aren't written correctly, and you also would need to rewind the MemoryStream.
However, there is no need for writing a WAV file if you want to play back an array of byes. Just use a RawSourceWaveStream and pass in your MemoryStream.
You may also find the AudioFileReader class more suitable to your needs as it will provide the samples as floating point directly, and allow you to modify the volume.

Binary stream 'NN' does not contain a valid BinaryHeader

I am passing user defined classes over sockets. The SendObject code is below. It works on my local machine, but when I publish to the WebServer which is then communicating with the App Server on my own machine it fails.
public bool SendObject(Object obj, ref string sErrMsg)
{
try
{
MemoryStream ms = new MemoryStream();
BinaryFormatter bf1 = new BinaryFormatter();
bf1.Serialize(ms, obj);
byte[] byArr = ms.ToArray();
int len = byArr.Length;
m_socClient.Send(byArr);
return true;
}
catch (Exception e)
{
sErrMsg = "SendObject Error: " + e.Message;
return false;
}
}
I can do this fine if it is one class in my tools project and the other class about UserData just doesn't want to know. Frustrating!
Ohh. I think it's because the UserData class has a DataSet inside it. Funnily enough I have seen this work, but then after 1 request it goes loopy and I can't get it to work again.
Anyone know why this might be? I have looked at comparing the dlls to make sure they are the same on the WebServer and on my local machine and they look to be so as I have turned on versioning in the AssemblyInfo.cs to double check.
Possible causes are invalid stream or object version change between serialization and deserialization.
Edit:
Ok it seems that the problem is with size. If I keep it under 1024 byes ( I am guessing here) it works on the web server and doesn't if it has a DataSet inside it.k In fact this is so puzzling I converted the DataSet to a string using ds.GetXml() and this also causes it to blow up. :( So it seems that across the network something with my sockets is wrong and doesn't want to read in the data.
This is solved by a better question I have posted here :
Sending large serialized objects over sockets is failing only when trying to grow the byte Array, but ok when using a massive byte array
Obviously I had a static buffer that I had lifted from some toy example, and then when I started passing populated datasets they were too large. The answers to some dynamic buffer problems I was having cover this too.

Categories

Resources