Hi, I need to retrieve the url of the image from the database, bind it to a business object, convert it into a bitmap image and map it into the resource dictionary. The resource dictionary is used as a library and I cannot change it.
The database consists of one table that has three columns: id, name, url. It is the SQL CE 3.5 local database. I want to be able to show all images at once.
What I managed to write:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Collections;
using System.Collections.ObjectModel;
using System.Windows.Media.Imaging;
using System.Windows;
using System.Windows.Media;
namespace Library.Components
{
public class ComponentsList : ObservableCollection<Components>
{
public ComponentsList()
{
String connString = @"Provider=Microsoft.SQLSERVER.CE.OLEDB.3.5; Data Source=local_source";
String query = @"SELECT id, name, url FROM GraphicComponents";
// Fill the Set with the data
using (SqlConnection conn = new SqlConnection(connString))
{
try
{
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = query;
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
this.Add(new Components(rdr));
}
}
finally
{
if (conn.State != ConnectionState.Closed) conn.Close();
}
}
}
}
public class Components
{
int _componentID;
string _name;
BitmapImage _url;
public Components(IDataRecord record)
{
_componentID = (int)record["id"];
_name = (string)record["name"];
_url = (string)record["url"];
//Code taken from a tutorial used to convert the url into BitmapImage
CreatePhoto((byte[])record["url"]);
}
void CreatePhoto(byte[] photoSource)
{
_url = new System.Windows.Media.Imaging.BitmapImage();
System.IO.MemoryStream strm = new System.IO.MemoryStream();
int offset = 78;
strm.Write(photoSource, offset, photoSource.Length - offset);
// Read the image into the bitmap object
_url.BeginInit();
_url.StreamSource = strm;
_url.EndInit();
}
public int ComponentID
{
get { return _componentID; }
}
public string Name
{
get { return _name; }
}
public BitmapImage Photo
{
get { return _url; }
}
}
}
In the resource dictionary in XAML I have Images controls. The source of the image is hardcoded; but I need to retrieve it from the database.
Thanks in advance for any help. The code is a mess and I'm sure that there is a simpler way of retrieving the URLs of the images from a database and map them into the resource dictionary.