Reading Binary/Byte from SQL on C# ASP - c#

Im trying to read the Binary Data of the Document Stored on SQL.
But when im suppose to store it in my Template Class i can't.
presentation.presentationDocBinData = byte.Parse(dr["presentationDocBinData"].ToString());
public byte[] presentationDocBinData
{
get;
set;
}
So im reading it from a DataRow. I tried byte[], Byte, byte, Byte[]. Im pretty lost on what to do.. any enlightment would be much appreciated.

You can simply cast object to byte array:
var result = (Byte[])dr["presentationDocBigData"];

Try to convert it in byte[](byte array)
presentation.presentationDocBinData = (byte[])dr["presentationDocBinData"];
public byte[] presentationDocBinData
{
get;
set;
}
byte.Parse() converts only single value into byte. for example if you have a value like "A" and you want to convert it into byte then you can use byte.Parse() method to convert value into byte.

Related

How to Convert from byte? to byte[]?

I am trying to convert a byte received from a database query.
EF Core returns nullable tinyint as byte? and I need to convert it to decimal.
Is there any way to convert it OnModelCreating with model builder in the DbContext?
I am not very familiar with EF Core. So far I only managed to do this - after I already got my object in handler:
decimal? newDecimal = Convert.ToDecimal(BitConverter.ToDouble(AddByteToArray(priceByte), 0)));
private static byte[] AddByteToArray(byte? newByte)
{
if (newByte != null)
{
if(newByte == 0)
{
return Enumerable.Repeat((byte)0x0, 8).ToArray();
}
byte[] bArray = new byte[1];
// Not sure how to convert a non null and byte > 0 to byte[]?? As double requires byte[] while the tinyint return byte from the database
return bArray;
}
return null;
}
I think you are getting a little confused by the types here. The DB returns a byte? for a tinyint because a tinyint has only 8 bits of data. But otherwise it is an integer. If you want to convert it to a decimal, you would use the same mechanism as you would to convert an int or a long to a decimal: cast it. You do not want to convert a byte array to a decimal as that will try to interpret the data in the array as a binary representation of a decimal (see my last paragraph). So this code should suffice to do the conversion.
decimal? d = newByte == null ? null : (decimal)newByte;
See that such a conversion is possible here: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/numeric-conversions
Note the remarks section here that indicates we are dealing with a binary representation of the number, where care must be taken in dealing with endianness, etc.
https://learn.microsoft.com/en-us/dotnet/api/system.bitconverter?view=net-6.0#remarks
Basically, numbers larger than a byte are technically stored as an array of bytes (since all memory is byte addressable in x86) but the interpration of those bytes into a number depends on the type of the number. For floating point numbers especially the structure of data inside the byte array is complex, broken into fields that represent the base, exponent and sign. And those are not always interpreted in a straightforward way. If you just give a byte array with 27 as the first byte, you don't know where that ends up in the several fields that make up the binary representation of a double. It may well work, but probably not.
Instead of
byte[] bArray = new byte[1];
You can use
byte[] bArray = {(byte)newByte};

c# error - Can not convert Array to byte array

I am trying cast a Json data to byte array and then save it in SQL image field, code is below
public string Post([FromBody] dynamic data)
{
foreach (var item in data)
{
imgPhoto1 = (byte[])item["Photo1"];
}
}
But getting error Can not convert Array to byte array
byte[] imgPhoto1 = (byte[])item["Photo1"];
Values in field item["Photo1"] is look like below
[255,216,255,224]
any help will be appreciated
If your parameter data is JToken, then you need convert it to desired type.
Try to use:
var obj = item["Photo1"].ToObject<byte[]>();
And will be better explicit declare your parameter data as JToken.

C# Convert Hex string to byte

Little bit stuck on this, I have a var called PORTBhex holding a value in the range 0x00 to 0x3F which is written to an external device via USB. The problem I am having is getting the value into this bit of code:
public bool PORTBwrite()
{
Byte[] outputBuffer = new Byte[65];
outputBuffer[0] = 0;
outputBuffer[1] = 0x00; //Command tells PIC18F4550 we want to write a byte
outputBuffer[0] = 0;
//Must be set to 0
outputBuffer[2] = IO.PORTBhex;
//Hex value 0x00 - 0x3F to write to PORTB
//above line gives the error cannot implicity convert string - byte
//IO.PORTBhex is returned from the code in second snippet
if (writeRawReportToDevice(outputBuffer))
{
return true; //command completed OK
}else{
return false; //command failed .... error stuff goes here
}
}
Now the problem is the value i have is an integer that is converted to hex using:
public static string ToHex(this int value)
{
return string.Format("0x{0:X}", value);
}
The value starts off as an integer and is converted to hex however I cannot use the converted value as its of the wrong type I am getting Cannot implicitly convert type 'string' to 'byte'.
Any idea what I can do to get around this please?
Thanks
EDIT:
I think I might have poorly described what I'm trying to achieve, I have an int variable holding a value in the range 0-255 which I have to convert to Hex which must be formatted to be in the range 0x00 to 0xFF and then set outputBuffer[2] to that value to send to the microcontroller.
The integer var has some maths performed on it before it needs to be converted so i cannot solely use byte vars and has to be converted to a hex byte afterwards.
Thanks
To solution is to change PORTBhex to be of type byte and don't use that ToHex method at all:
Instead of IO.PORTBhex = ToHex(yourIntValue) use this:
IO.PORTBhex = checked((byte)yourIntValue);
It would be even better if you could make yourIntValue to be of type byte, too.
outputBuffer[2] = Convert.ToByte(IO.PORTBhex, 16);
Although personally I'd probably try to avoid strings here in the first place, and just store the byte

How do I check if an object contains a byte array?

I'm having an issue with the following code.
byte[] array = data as byte[]; // compile error - unable to use built-in conversion
if (array != null) { ...
I only want to assign the data to array variable if the data is actually a byte array.
How about this:
byte[] array = new byte[arrayLength];
if (array is byte[])
{
// Your code
}
Try
if(data.GetType().Name == "Byte[]")
{
// assign to array
}
As soon as I asked this I realised that the type of data was not object.
Making it of type object (its coming in via a type converter in Silverlight) and it worked.

Failed to convert parameter value from a Int64 to a Byte[]

I am getting the error:
Failed to convert parameter value from
a Int64 to a Byte[].
Here is what I am doing...
I have a table in my database with the column:
sessionid | binary(32) | null
When I assign to it, I do this:
user.LastActivityDate = DateTime.Now;
user.SessionId = user.LastActivityDate.ToBinary();
SessionId is an inherited property from an interface:
long? SessionId { get; set; }
And here it is being accessed in my User class:
[SettingsAllowAnonymous(false), CustomProviderData("SessionId;string")]
public long? SessionId { get { return base["SessionId"] as long?; } set { base["SessionId"] = value; } }
In my custom profile provider, the following command assigns the value:
sqlCommand.Parameters.Add("sessionid", SqlDbType.Binary, 32).Value = settingsPropertyValue.PropertyValue;
When the "sqlCommand.ExecuteNonQuery()" command executes an update stored
procedure is executed with the parameter:
#sessionid binary(32)
And the result is the error:
"Failed to convert parameter value
from a Int64 to a Byte[]."
I have tried:
... = Convert.ToByte(settingsPropertyValue.PropertyValue);
... = Convert.ToInt64(settingsPropertyValue.PropertyValue);
Any ideas? Thanks.
SqlDbType.Binary is not correct (when you add the parameter) -- that's for extended binary data of arbitrary length. You want to just represent it as a 64-bit integer, which is SqlDbType.BigInt.
By the way, why are you doing this in the first place? SQL has a date-time type; you can just store it like that.
(You could go about it in the opposite, perverse way and instead convert the long to an eight-byte array and pass that, but there's no conceivable reason you would want to store it in that manner.)
ToBinary doesn't do what you think it does.
The DateTime.ToBinary method returns a long value, not a byte array.
What are you trying to do?
If you're trying to store the datetime, you should just use a DataTime column.
If you actually want a byte array, please provide more details.

Categories

Resources