Publish date: 2007-08-17

How to insert image into the blob field (C#, FW 2.0)

Before run sample you need execute the following DDL query

CREATE TABLE AUTENTIFICATION_LOG
(
 SYSTEM_SETTING_ID INTEGER,
 USE_WINDOWS_AUTHENTICATION INTEGER,
 LOGON_IMAGE BLOB SUB_TYPE 0 SEGMENT SIZE 80
)

C# code sample:

[Ignore("Before run test require executing DDL query")]
[Test(Description = "Insert binary blob as a byte array")]
public void InsertImageIntoTheBlobField()
{
    using (OleDbConnection con = ConnectionProvider.CreateConnection())
    {
        con.Open();
        OleDbTransaction trans = con.BeginTransaction ();

        OleDbCommand cmd = new OleDbCommand(
          "insert into AUTENTIFICATION_LOG \n" +
          "(SYSTEM_SETTING_ID, USE_WINDOWS_AUTHENTICATION, LOGON_IMAGE) \n" +
          "VALUES(?, ?, ?)", con, trans);

        cmd.Parameters.AddWithValue("SYSTEM_SETTING_ID", new Random().Next());
        cmd.Parameters.AddWithValue("USE_WINDOWS_AUTHENTICATION", false);

        // using System.Drawing
        Bitmap bmp = SystemIcons.Warning.ToBitmap();

        OleDbParameter blob = new OleDbParameter();
        blob.OleDbType = OleDbType.LongVarBinary;

        // using System.ComponentModel and convert Bitmap to byte[]
        blob.Value = (byte[])TypeDescriptor.GetConverter(bmp).ConvertTo(bmp, typeof(byte[]));

        cmd.Parameters.Add(blob);

        // using NUnit Framework
        Assert.AreEqual(1, cmd.ExecuteNonQuery());

        trans.Commit();
    }
}

See also