Reputation: 659
First of all I've tried everything, and can't understand why it won't update my varbinary field properly.
out of 1728 bytes only the last byte in the byte array is saved to the field...
I generate my byte array as follows:
public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
I have also tried the one below:
public static byte[] ParseHex(string hex)
{
int offset = hex.StartsWith("0x") ? 2 : 0;
if ((hex.Length % 2) != 0)
{
throw new ArgumentException("Invalid length: " + hex.Length);
}
byte[] ret = new byte[(hex.Length - offset) / 2];
for (int i = 0; i < ret.Length; i++)
{
ret[i] = (byte)((ParseNybble(hex[offset]) << 4)
| ParseNybble(hex[offset + 1]));
offset += 2;
}
return ret;
}
static int ParseNybble(char c)
{
if (c >= '0' && c <= '9')
{
return c - '0';
}
if (c >= 'A' && c <= 'F')
{
return c - 'A' + 10;
}
if (c >= 'a' && c <= 'f')
{
return c - 'a' + 10;
}
throw new ArgumentException("Invalid hex digit: " + c);
}
My c# code to save the data is this:
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DB_Conn"].ConnectionString))
{
byte[] to_store = StringToByteArray(inventory);
//State the Stored Proc and add Values to 'cmd' to pass to the Stored Proc
SqlCommand cmd = new SqlCommand("_USP_store", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@A", TB_A.Text);
cmd.Parameters.Add("@B", SqlDbType.VarBinary, 1728).Value = to_store;
try
{
// Open Connection and execute Stored Proc
conn.Open();
cmd.ExecuteNonQuery();
C2_Wipe_Message.Text = "Storing success";
C2_Wipe_Message.ForeColor = Color.FromArgb(0, 0, 255, 0);
}
catch
{
C2_Wipe_Message.Text = "An error occured..";
C2_Wipe_Message.ForeColor = Color.FromArgb(0, 255, 0, 0);
}
finally
{
if (conn.State == System.Data.ConnectionState.Open)
{
//Close connection IF open
conn.Close();
}
}
}
I've send it as a string, I've send it as plain binary, i've send it as a hexadecimal byte array, etc.
My assumption is to use a while loop in sql, to store it, but that doesn't explain why the last byte is always saved instead of the first byte of the byte array, Please enlighten me cause this is infuriating..
*SQL SP
@A varchar(10),
@B varbinary(1728)
AS
UPDATE Invenotry
SET A = @B
WHERE (Name = @A)
Upvotes: 1
Views: 5100
Reputation: 70528
Your sql should be this:
UPDATE Invenotry
SET B = @B
WHERE A = @A
You can also try the full version of a parameter constructor:
SqlParamter param = new SqlParameter("@B", SqlDbType.VarBinary, 1728, ParameterDirection.Input,
// we have these parameters but they are ignored for input types
false, 0, 0, null, DataRowVersion.Current,
// the data
to_store);
cmd.Parameters.Add(param);
Upvotes: 3