How can i define a class to deserialze binary file - c#

I would like to know how can i define a class for a binary file which contains objects with float array of size 19.
please see the attached picture of how data looks like in Hex Editor Neo. when displayed as float
i have tried following but no luck. please tell what i am doing wrong here.
[ProtoContract]
public class ChannelData
{
[ProtoMember(1)]
public List<float> array = new List<float>(19);
}
using (var file = File.OpenRead("0.cnl"))
{
ChannelData newchannel = Serializer.Deserialize<ChannelData>(file);
}
I am using protobuff for deserialize. Thankyou!
that binary file is not serialized using any binary serializer its raw file.
so i think it can not be deserialize using any deserializer? may be need to do with BitConverter but have no idea..

You can load floats to the list, then split it to Channels, like
public static unsafe List<float> LoadToList(byte[] bytes)
{
var list = new List<float>();
var step = sizeof (float);
for (int i = 0; i < bytes.Length; i += step)
{
fixed (byte* pbyte = &bytes[i])
{
list.Add(*((float*)pbyte));
}
}
return list;
}

Related

How can I assing a certain array member to a member variable of a class which is also an array

Sorry for the confusing title! I'll try to simplify it.
I have a class which I created to immitate the behavior of typedef in C/C++. I want to use a user defined type Pixel for all pixel values because today it is byte but in the future it can be a uint16.
I am scanning all the places that pixels are handled and there are operations like this:
private void ParseImageData()
{
byte[] data = new byte[imageSize];
foreach (byte[] packet in ImagePackets)// private readonly List<byte[]> ImagePackets;
{
byte[] datapacket = SomeFunction(packet);// private byte[] SomeFunction(byte[] imagePacket)
datapacket.CopyTo(data, count);
count += PACKET_SIZE;
}
// do something with Pixel type
}
So this code block basically transfer data that is stored in a list to a array. The problematic part is the CopyTo line. If I convert data from byte[] to Pixel[], it will try to copy bytes to Pixels. Which is not right. I know that this doesn't make sense but If I could write something like this datapacket.CopyTo((pixel.Value)[], count) my problems would be solved!.
So now I added a for loop to copy the content manually. But I hated this method and I am not sure it will work if Pixel.Value will be something other than byte. I am also considering to add a new class for pixel arrays but I don't think that is an elegnat way to do it either. Here is my (hopefully)temporary solution:
private void ParseImageData()
{
Pixel[] pixels = new Pixel[imageSize];
foreach (byte[] packet in ImagePackets)
{
byte[] datapacket = SomeFunction(packet);
for(int i = 0; i< PACKET_SIZE; i++,count++)
{
pixels[i].Value = datapacket[i];
}
}
// do something with Pixel type
}
Here is the Pixel class and a potantial Pixel array class:
public class Pixel
{
public Pixel(byte val)
{
this.Value = val;
}
public byte Value { get; set; }
}
public class PixelArr
{
public PixelArr(ushort size)
{
this.Value = new byte[size];
}
public byte[] Value { get; set; }
}
You do not want a Pixel class; an object per pixel would be catastrophic. Honestly, I think you should just eat the byte => ushort conversion later if you need to, but if you really really want a Pixel struct that is basically a fancy byte, you could do something like:
public readonly struct Pixel // readonly *very* deliberate here
{
private readonly byte _value;
public Pixel(byte value) => _value = value;
public byte Value => _value;
// TODO: add equality/hash/tostring, etc
// TODO: operators?
}
Now, you can't use variance with value-type arrays, but: you can use reinterpret operations on spans. If you want to go that route: MemoryMarshal.Cast<byte, Pixel> (or the other way around) may help. It the two types are of different sizes, the output span will have a different length than the input, accordingly. But: if you're changing from byte to ushort, that then prompts questions about "endianness" and which CPUs you need this to work on!
However, and I can't emphasize this enough: I think you'd be better off just eating the change to ushort later and dealing with raw values.

C# JSON import: could not convert string to byte array

I've developed an application where is possible to import data from a JSON file.
This is the code I'm using to deserialize JSON:
var json_serializer = new JavaScriptSerializer();
var json_tpp = json.tpp;
ThermalPowerPlant tpp = json_serializer.Deserialize<ThermalPowerPlant>(json_tpp);
Everything was working fine, but lately I've modified the ThermalPowerPlant class to include a PDF that I save as byte array.
So, now, my JSON contains this field and if I try to import it again, application returns an exception that says it can not convert type String to Byte Array.
How can I handle this case?
EDIT
This is the byte array field in my JSON:
"Map": "JVBERi0xLjQKJeLjz9MKMyAwIG9iago8PC9MZW5ndGggNTU1My9GaWx0ZXIvRmxhdGVEZWNvZGU+PnN0cmVhbQp4nJ1d23IcN5J951dU7JPmgeW6X/atR2xreoMi6WZbMeE3jkx7uUGwZYqeifDXL1CFS2YCmSgpHA4xC+dUnkQB2aebxeo/Lv5+uminop/64vTrRVVcTk1Zt/bnppvKarBB3XTlAtqfLn66+GP5vyn+Rw99uKj1yH/0T+a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eXBlMS9CYXNlRm9udC9IZWx2ZXRpY2EvRW5jb2RpbmcvV2luQW5zaUVuY29kaW5nPj4KZW5kb2JqCjQgMCBvYmoKPDwvVHlwZS9QYWdlcy9Db3VudCAxL0tpZHNbNSAwIFJdPj4KZW5kb2JqCjYgMCBvYmoKPDwvVHlwZS9DYXRhbG9nL1BhZ2VzIDQgMCBSPj4KZW5kb2JqCjcgMCBvYmoKPDwvUHJvZHVjZXIoaVRleHRTaGFycJIgNS41LjggqTIwMDAtMjAxNSBpVGV4dCBHcm91cCBOViBcKEFHUEwtdmVyc2lvblwpKS9DcmVhdGlvbkRhdGUoRDoyMDE2MDQxMTEzMDAwOCswMCcwMCcpL01vZERhdGUoRDoyMDE2MDQxMTEzMDAwOCswMCcwMCcpPj4KZW5kb2JqCnhyZWYKMCA4CjAwMDAwMDAwMDAgNjU1MzUgZiAKMDAwMDAwNTc1NyAwMDAwMCBuIAowMDAwMDA1ODUwIDAwMDAwIG4gCjAwMDAwMDAwMTUgMDAwMDAgbiAKMDAwMDAwNTkzOCAwMDAwMCBuIAowMDAwMDA1NjM2IDAwMDAwIG4gCjAwMDAwMDU5ODkgMDAwMDAgbiAKMDAwMDAwNjAzNCAwMDAwMCBuIAp0cmFpbGVyCjw8L1NpemUgOC9Sb290IDYgMCBSL0luZm8gNyAwIFIvSUQgWzxmNzAwMjI5ZDUxNzljNDZlNzNiMTFlZThiNTc0NmUxMj48ZjcwMDIyOWQ1MTc5YzQ2ZTczYjExZWU4YjU3NDZlMTI+XT4+CiVpVGV4dC01LjUuOApzdGFydHhyZWYKNjE5NgolJUVPRgo="
PS: I've also checked my JSON and it is correctly formatted.
Your field is Base64. You'll need to define your property as a string (because it is a string, even if it represents a byte array).
Then you can convert it like this:
var myArr = Convert.FromBase64String(tpp.map);
Replace JavaScriptSerializer with JSON.NET
And this code works perfectly:
class Program
{
public class SomeClass
{
public string SomeProperty { get; set; }
public byte[] ByteArrayProperty { get; set; }
}
static void Main()
{
SomeClass sc = new SomeClass()
{
SomeProperty = "la la la",
ByteArrayProperty = new byte[] {1, 2, 3}
};
string json = JsonConvert.SerializeObject(sc);
SomeClass newSC = JsonConvert.DeserializeObject<SomeClass>(json);
}
}
EDIT
json = "{\"SomeProperty\":\"la la la\",\"ByteArrayProperty\":\"JVBERi0xLjQKJeLjz9MKMyAwIG9iago8PC9MZW5ndGggNTU1My9GaWx0ZXIvRmxhdGVEZWNvZGU+PnN0cmVhbQp4nJ1d23IcN5J951dU7JPmgeW6X/atR2xreoMi6WZbMeE3jkx7uUGwZYqeifDXL1CFS2YCmSgpHA4xC+dUnkQB2aebxeo/Lv5+uminop/64vTrRVVcTk1Zt/bnppvKarBB3XTlAtqfLn66+GP5vyn+Rw99uKj1yH/0T+a/4wd9wnLs9Tm7sukL5cJ+1qjni3sGvQyri2Y2wywYDnvwmohHEyEBntDezG0gLAEvpfVC+q4q65rHovEAZ4VjgIKqGN19V5cDYLiYVwTG1cXQzWU983A0HuBsARigiDymhqGvygGQXMyKguPqYqpaw2PhaDzA2RowQBF5TA1uNU9hvbUtkwCN+9XMwtF42CmTtE+ADAvk1vwCXX4SBLQhfVfraRwFNAYEQlowGFVeEKO3a+qyclgX8DoQIFx3loABYF0lhYNRBZXJ66OtzT/+2uhzDK2wRNZxf81ZOBoPK2pJJqwoLCbAubXiCEsgiGmDFHd9WTQGgPXFiccABZVl1o1juJjXhAChb7MEDAgEtggMUERiptc7kosFWRAQ2jdLwIBAYOvAAEUkZvq9I7mYl4UAYWeyBAwAe5+rAwMUkejqMP//ZKxTvfDqoltZg16RU3FSFz/8WBdzcfrt4t3d8fbueNifdsfD7X//7fR/nlLXXTkOgFMVp8+a2FhigcFj2URgefTdh58/XB9uT6ddsbve39/vbq6Ot/CkjWlwM6Vd1nNVVp1GrF4PVNnMo2kXw1gOg6uyHowr1Hrv3/9jf7UrPu7u7nann487kwnT+25Y1npilq52px2anX7synrj5PTjsKy19OSkR9/V9Q9V90NT1QM81aC339BFUzL2Zd+mZmTo+2X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yCjw8L1NpemUgOC9Sb290IDYgMCBSL0luZm8gNyAwIFIvSUQgWzxmNzAwMjI5ZDUxNzljNDZlNzNiMTFlZThiNTc0NmUxMj48ZjcwMDIyOWQ1MTc5YzQ2ZTczYjExZWU4YjU3NDZlMTI+XT4+CiVpVGV4dC01LjUuOApzdGFydHhyZWYKNjE5NgolJUVPRgo=\"}";
newSC = JsonConvert.DeserializeObject<SomeClass>(json);
Works perfectly. ByteArrayProperty is fill with bytes without errors.
Try the accepted solution at (e. g.) Deserializing JSON to abstract class
The asked question comes from another problem, but maybe you need to specify a TypeNameHandling for the JsonSerializerSettings, in order to make a difference between a string and a byte array. The interesting excerpt from the code there (adapted to your problem):
....
var jset = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All };
ThermalPowerPlant tpp = ...;
string json = JsonConvert.SerializeObject(tpp, jset);
....
ThermalPowerPlant tpp2 = (ThermalPowerPlant)JsonConvert.DeserializeObject(json, jset);
Didn't try to compile and maybe you are deserializing in another way, so you might have to improve this thing.

How to deserialize class with array of serializable object

I have class with array of some serialized class (named it elements). I want to serialize this class and then deserialize this. But deserialization is difficult.
Because I don't know type of element of my array before serialized this create two arrays match to elements array. In one (typeOfElements) keep type of element and in other (serializedElemnt) keep serialized string of elements. But I don't know after deserialized how to create my main elements array. How can I convert type to class to create my main array?
[ProtoContract]
class MyClass
{
.
.
public MyClass()
{
}
object[] elements;
[ProtoMember(1)]
string[] SerilizedElements;
[ProtoMember(2)]
string[] TypeOfElements;
[ProtoBeforeSerialization]
void initBeforeSerilize()
{
TypeOfElements = new string[elements.Length];
SerilizedElements = new string[elements.Length];
for (int i = 0; i < elements.Length; i++)
{
TypeOfElements[i] = elements[i].GetType().ToString();
using (MemoryStream ms = new MemoryStream())
{
Serializer.Serialize(ms, elements[i]);
SerilizedElements[i] = Encoding.UTF8.GetString(ms.ToArray());
}
}
}
[ProtoAfterDeserialization]
void initAfterSerilize()
{
for (int i = 0; i < SerilizedElements.Length; i++)
{
Type t = Type.GetType(TypeOfElements[i]);
using(MemoryStream ms=new MemoryStream(Encoding.ASCII.GetBytes(SerilizedElements[i])))
{
//I don't know how to write this line
elements[i]=Serializer.Deserialize<t>(ms);
}
}
}
}
For the "I only know the type at runtime" issue, look at Serializer.NonGeneric, which has all the methods you would want for working with a Type. The non-generic API is also the primary API on the v2 API, aka TypeModel. The string encoding issue has already been noted; if you need strings, base-64 should be used, but personally I'd use a byte[]. I would also suggest thinking about whether inheritance can be used instead of unknown types - this is certainly possible if the number of candidate types is finite and known.

Converting byte[] to an object

I'm trying to convert an object which I have in a byte[] to an object.
I've tried using this code I found online:
object byteArrayToObject(byte[] bytes)
{
try
{
MemoryStream ms = new MemoryStream(bytes);
BinaryFormatter bf = new BinaryFormatter();
//ms.Position = 0;
return bf.Deserialize(ms,null);
}
catch
{
return null;
}
}
SerializationException: "End of Stream encountered before parsing was
completed.".
I've tried it with the ms.Position = 0 line uncommented of course too...
bytes[] is only 8 bytes long, each byte isn't null.
Suggestions?
[edit]
The byte[] was written to a binary file from a c++ program using something along the lines of
void WriteToFile (std::ostream& file,T* value)
{
file.write(reinterpret_cast<char*>(value), sizeof(*T))
}
Where value may be a number of different types.
I can cast to some objects okay from the file using BitConverter, but anything BitConverter doesn't cover I can't do..
As was stated by cdhowie, you will need to manually deserialize the encoded data. Based on the limited information available, you may either want an array of objects or an object containing an array. It looks like you have a single long but there is no way to know from your code. You will need to recreate your object in its true form so take the below myLong as a simple example for a single long array. Since it was unspecified I'll assume you want a struct containing an array like:
public struct myLong {
public long[] value;
}
You could do the same thing with an array of structs, or classes with minor changes to the code posted below.
Your method will be something like this: (written in the editor)
private myLong byteArrayToObject(byte[] bytes) {
try
{
int len = sizeof(long);
myLong data = new myLong();
data.value = new long[bytes.Length / len];
int byteindex = 0;
for (int i = 0; i < data.value.Length; i++) {
data.value[i] = BitConverter.ToInt64(bytes,byteindex);
byteindex += len;
}
return data;
}
catch
{
return null;
}
}

Converting an ArrayList of Points to a byte array to store in a SQL database

I have part of an application which is used to save a users signature on a hand-held device.
I have managed to do this by having an arraylist of "Lines" which contains an arraylist of "points".
I need to store this information in a SQL database. The only info I have seen to do this, is to use the image data type and pass it a byte array. There being the question. How would I do this, or is there a better way?
If you convert this data into an image, some information (which point belongs to which line) is lost. If you want to keep this information, you should serialize your data.
Decide on the format: You could use something terribly verbose like XML...
<Line>
<Point X="3" Y="4" />
<Point X="3" Y="5" />
...
</Line>
<Line>
<Point X="10" Y="10" />
...
</Line>
...
...or some custom text-based format:
3,4-3,5-...;10,10-...;...
Of course, you'll be most efficient storing the data in some kind of binary encoding.
If you use a text- (or XML-)based format, your serialization will yield a string which you can store in a varchar(MAX) or text field in SQL Server. If you decide on a binary encoding, the serialization will result in a byte array. For this, varbinary(MAX) or image is the data type of choice. Note that the name image might be misleading: This does not necessarily mean that your data is encoded as an "image" (jpeg, png, etc.).
Implementation: For XML and a standard binary encoding, .NET provides built-in functions. Here's an introduction and links to walkthroughs on MSDN:
Serialization (C# and Visual Basic)
If you decide on some custom text-based or custom binary encoding, you will need to code the serialization and deserialization parts yourself. If you want help with that, you need to provide some more information: How does your data structure look exactly? What data types are your X and Y coordinates?
It sounds like you want some form of binary serialization; here is a working version using protobuf-net (note I changed ArrayList to List<T>):
using System.Collections.Generic;
using System.IO;
using ProtoBuf;
[ProtoContract]
class Line
{
private readonly List<Point> points = new List<Point>();
[ProtoMember(1, DataFormat = DataFormat.Group)]
public List<Point> Points { get { return points; } }
}
[ProtoContract]
class Point
{
[ProtoMember(1)]
public int X { get; set; }
[ProtoMember(2)]
public int Y { get; set; }
}
static class Program
{
static void Main()
{
var lines = new List<Line> {
new Line { Points = {
new Point { X = 1, Y = 2}
}},
new Line { Points = {
new Point { X = 3, Y = 4},
new Point { X = 5, Y = 6}
}},
};
byte[] raw;
// serialize
using (var ms = new MemoryStream())
{
Serializer.Serialize(ms, lines);
raw = ms.ToArray();
}
List<Line> clone;
// deserialize
using (var ms = new MemoryStream(raw))
{
clone = Serializer.Deserialize<List<Line>>(ms);
}
}
}
So you let the user create a bitmap-graphic by signing with a stylus?
Sounds perfectly reasonable to me to store this as an image.
create bitmap from array
Just create a black and white bitmap from your data and then convert your bitmap to PNG image using .NET library:
MemoryStream pngbuffer = new MemoryStream();
Bitmap.Save(pngbuffer,ImageFormat.Png)
And store it as a binary data. Most databases have a format for storing binary data: PostgreSQL bytea, MySQL and Oracle blob, MSSQL image etc.

Categories

Resources