none
How save and load pictures from Database... RRS feed

  • Question

  • Hi,
    i need to save some picture on the Database (SqlServer) ,i use LinqToSql to make this operation but i have a trouble.
    I don't know if my way to to work out this feature is right .
    I show you an example:
    I have a database with 3 fields :
    - ID (int_autoincreasing) PK;
    - Pic (VarbinaryMAX); // the field where i save my picture;
    - Note (Nvarchar); // the Path Url of the picture saved;

    Here the code how i save the picture to the database;
    public partial class Window1 : Window
        {
            private DataClasses1DataContext dc;
            public Window1()
            {
                InitializeComponent();
            }
            string avatarPhotoPath;
            
    
            private void Add_Record(object sender, RoutedEventArgs e)
            {
                dc = new DataClasses1DataContext();
                string message = "Are you sure you want to proceed?";
                byte[] inputBuffer = System.IO.File.ReadAllBytes(txtNote.Text);// here i don't if it's exactly ,txtnote is the Path Url of the image that i store
                try
                {
                    if(txtNote.Text.Length >0)
                    {
                        Tabolo tabolo = new Tabolo();
                       tabolo.Pic = new Binary(inputBuffer);
                        tabolo.Note = txtNote.Text;
                       if (MessageBox.Show(message, "Add New Record", MessageBoxButton.YesNo,
     MessageBoxImage.Exclamation) == MessageBoxResult.Yes)
                       {
                           dc.Tabolos.InsertOnSubmit(tabolo);
                           dc.SubmitChanges();
                           
                           MessageBox.Show("Record added!!!", "Operation Completed");
    
                       }
                       else
                       {
                           MessageBox.Show("You have clicked NO", "Record aborted.");
                    
                       }
                    }
                    else
                    {
                        MessageBox.Show("Check out the record's field.Miss some parameter.", "Info", MessageBoxButton.OK,
                                     MessageBoxImage.Warning);
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("Sorry,an error deny to save the current record!!!", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    
                    throw;
                }
            }
    
        }
    Now How i try to store the picture from the database:

     public partial class Window3 : Window
        {
            private DataClasses1DataContext dc;
            public Window3()
            {
                InitializeComponent();
                dc = new DataClasses1DataContext();
                var query = from d in dc.Tabolos select new {d.ID, d.Note, d.Pic};
                this.listView1.ItemsSource = query;
                dc.SubmitChanges();
            }
    
    
     public class ImageDataConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter,
            System.Globalization.CultureInfo culture)
            {
                return value;
            }
    
            public object ConvertBack(object value, Type targetType, object parameter,
            System.Globalization.CultureInfo culture)
            {
                throw new NotSupportedException();
            }
        }
    }
    }
    In the XAML :

    <Window x:Class="ProvaVarbinary.Window3"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:local="clr-namespace:ProvaVarbinary"
        Title="Window3" Height="300" Width="300">
        <Window.Resources>
            <local:ImageDataConverter x:Key="imageconverter"/>
        </Window.Resources>
        <Grid>
            <ListView Name="listView1" VerticalContentAlignment="Stretch" HorizontalContentAlignment="Stretch">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <Border Margin="5" BorderThickness="1" BorderBrush="SlateGray" CornerRadius="4">
                            <Grid Margin="3">
                                <Grid.RowDefinitions>
                                    <RowDefinition></RowDefinition>
                                    <RowDefinition></RowDefinition>
                                    <RowDefinition></RowDefinition>
                                </Grid.RowDefinitions>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition></ColumnDefinition>
                                </Grid.ColumnDefinitions>
                                <TextBlock FontWeight="Bold" Text="{Binding Path=ID}"></TextBlock>
                                <TextBlock Grid.Row="1" Text="{Binding Path=Note}"></TextBlock>
                                <Image Grid.Row="2" Source="{Binding Path=Pic , Converter={StaticResource imageconverter}}"></Image>
                            </Grid>
                        </Border>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
    
        </Grid>
    </Window>
    After these step i cannot show the picture in he ListView .
    Sincerely it's the first time i do something like that and i don't know where i wrong ,so can you point me in the right direction  where i wrong or there is a better way to work out this characteristic?

    Thanks for your attention.

    Have a happy time.
    • Moved by Hua Chen Friday, May 29, 2009 10:00 AM Linq to SQL issue. (From:Windows Presentation Foundation (WPF))
    Thursday, May 28, 2009 2:55 AM

All replies

  • Hello  JonnyNH,

       It should be a Linq to SQL issue.

       Move to Linq to SQL forum.

       You can get a faster answer there.

       Thanks.
     


    Please mark the replies as answers if they help and unmark them if they provide no help
    • Edited by Hua Chen Friday, May 29, 2009 9:58 AM Edit..
    Friday, May 29, 2009 9:58 AM
  • Is the image being saved successfully in the database?

    If so, the problem may be in binding the Binary type back to the Image in WPF. I found a post on stackoverflow that talks about binding a byte[] to an Image in XAML that may prove useful. Remember you can the byte[] from the Binary type by calling ToArray.

    http://stackoverflow.com/questions/686461/how-do-i-bind-a-byte-array-to-an-image-in-wpf-with-a-value-converter
    Blog - http://blogs.rev-net.com/ddewinter/ Twitter - @ddewinter
    Sunday, May 31, 2009 3:30 PM
    Answerer
  • I suspect this is a binding issue on read rather than a problem saving the values. You may find it helpful to see the LINQ enabled version of the Personal Web Starter kit (http://code.msdn.microsoft.com/LinqPersonalWeb) for a similar example. It uses ASP.Net rather than WPF, but the concepts as far as image storage with LINQ to SQL should be similar.

    In an additional note, I did see in your Load handler, you are querying the database to set-up the binding and then calling SubmitChanges. SubmitChanges only needs to be called if you actually change anything. I don't see any reason in your code to call that until the Add_Record method.

    Jim Wooley
    www.ThinqLinq.com
    http://www.LinqInAction.net - "LINQ In Action", The book is now available. Don't wait for the movie
    Monday, June 1, 2009 8:41 PM
    Moderator
  • Hi all,
    thanks to reply me , ifound out the solution change adding a new code line in the Converter as follow :

     public class ImageDataConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter,
            System.Globalization.CultureInfo culture)
            {
                byte[] image = ((System.Data.Linq.Binary)value).ToArray();// New line added
                return image;
            }
    
            public object ConvertBack(object value, Type targetType, object parameter,
            System.Globalization.CultureInfo culture)
            {
                throw new NotSupportedException();
            }
        }
    and now i can populate the ListView with image.
    But i'm in doubt if my process ,to save and load image in database,is right or not,however i can save and load image from database.
    If you have a better way to work out this feature i'm happy to listen your suggestion.
    Thanks as forever for your care.

    Nice Regards
    Tuesday, June 2, 2009 8:03 AM