Share via


Sample for Displaying Images from the Database using Dynamic Data

I'm posting a sample project that shows some custom field template controls for Dynamic Data that allow images to be viewed/edited from a database. The sample also shows how you can view images that have their filenames in the database but the images on the physical disk. You can download the sample by clicking this download link: DOWNLOAD SAMPLE

Here are the basics sets that are required if you want to add this functionality into you own Dynamic Data project:

 

1) Reference the DbImageAPI library in the sample to your Dynamic Data website.

2) Copy DbImage.ascx., DbImage.ascx.cs, DbImage_Edit.ascx, DbImage_Edit.ascx.cs, FileImage.ascx, FileImage.ascx.cs from the samples App_Shared/DynamicDataFields directory to the App_Shared/DynamicDataFields directory on your website.

3) Copy the Blank.gif from the samples App_Shared/Images to the App_Shared/Images directory in your website.

4) In the Web.Config file add "

<add verb="*" path="ImageHandler.ashx" type="DbImageAPI.ImageHandler"/>
" to the <httpHandlers> section.

 

Once these are done you just need to apply renderhints to the data model. For example if the table in the database is Categories you would create a partial class called Category and add the following metadata to the partial class:

[ImageFormat("Picture", 100, 100)]
[RenderHint("Picture", "DbImage")]
public partial class Category {

}

 

The RenderHint tells it to use the DbImage field template control to render the Picture column. There is also an additional attribute added which allows the width and height the image to be set as well. The ImageFormat attribute causes the control the dynamically scale the image keeping the proper aspect ratio.

 

If you have a database column that has filenames of images that exist in a directory in the website you can use the FileImage control. Here is an example:

[RenderHint("Filename", "FileImage")]
[ImageUrl("Filename", "~/images/{0}")]
[ImageFormat("Filename", 100, 100)]
public partial class FilePicture {
}

 

In this case the table in the database is FilePictures and a partial class of FilePIcture has been created to apply the attributes. The RenderHint tells it to render the Filename column using the FileImage field template control. The ImageUrl attribute is used to specify where on the website the images are located, in this cas the images are in the images directory underneath the root. And once again the ImageFormat attribute is used to specify a width/height. In the case of file based images this attribute just changes the width and height tags on the image.

 

I will go into much more detail about how these controls were created in a future blog post.

Comments

  1. I had an issue with empty Data / no cache key Thank you for the cool post.  Keep it up! //LinqImageHelper object value = null;            if (member.Type == typeof(Guid))            {                value = new Guid(primarykeyvalue);            }            else            {                value = Convert.ChangeType(primarykeyvalue, member.Type, CultureInfo.InvariantCulture);            } // DBImage_Edit if (MetadataAttributes.TryGetValue("ImageFormat", out metadata))        {            string tablename = MetaMember.MetaTable.Name;            string primarykeyname = MetaMember.MetaTable.IdentityMetaMembers[0].Name;            string primarykeyvalue = DataBinder.GetPropertyValue(DataItem, primarykeyname).ToString();            string cachekey = string.Format("{0}:{1}:{2}", tablename, DataField, primarykeyvalue);            ViewState["CacheKey"] = cachekey;            //check if image exists            if (DataValue == null || metadata == null)            {                return;            }            SavedDataValue = DataValue;            //metadata            int width = 100;            int height = 100;            bool displayinedit = true;            IDictionary<string, object> metadatadict = (IDictionary<string, object>)metadata;            width = (int)metadatadict["Width"];            height = (int)metadatadict["Height"];            displayinedit = (bool)metadatadict["DisplayInEdit"];            //display picture if in edit mode,            if (TemplateMode == DynamicTemplateMode.EditItemTemplate && displayinedit)            {                //set image properties                PlaceHolderImage.Visible = true;                ImageEdit.ImageUrl = "~/ImageHandler.ashx?table=" + tablename + "&column=" + DataField + "&pkv=" + primarykeyvalue + "&width=" + width.ToString() + "&height=" + height.ToString();            }        }
  • Anonymous
    May 13, 2008
    Are you planning on making a generic file handler?

  • Anonymous
    May 19, 2008
    the MetadataAttribues.TryGetValue is causing an error for me.

  • Anonymous
    June 16, 2008
    I posted a sample back in January on how to display images from databases or the file system using Dynamic

  • Anonymous
    July 17, 2008
    I cannot compile DbImageAPI in VS 2008 (without SP1) with 3.5 Beta framework. I got the following errors: The type or namespace name 'BaseMetadataAttribute' could not be found (are you missing a using directive or an assembly reference?) The type or namespace name 'ValidationAttribute' could not be found (are you missing a using directive or an assembly reference? What could be wrong? Nice example, Thank you.

  • Anonymous
    October 24, 2008
    Nice one Scott. But its made for extension CTP? I got SP1 and can't compile it. It needs 3.6 extension. But in sp1 is 3.5.

  • Anonymous
    November 09, 2008
    I work on VB and in my case I only see the original images in DB, but updating and inserting new ones, not work. Ps- You had any version in VB?

  • Anonymous
    March 17, 2009
    Can anyone tell me where can I find ImageHandler.ashx

  • Anonymous
    March 21, 2009
    The comment has been removed

  • Anonymous
    October 02, 2009
    This is great! Once files are attached as dbimage or linked to the filesystem for instance PDF, do you know a way to call that PDF into an RDLC report as an image frame along with other data fields from the table(s)? Thank you!

  • Anonymous
    December 07, 2009
    Maybe you build this example with CTP release? I try to update the example with SP1 and the hints from http://www.asp.net/(S(ywiyuluxr3qb2dfva1z5lgeg))/downloads/3.5-SP1/Readme/ but it still wont compile. Here are my errors: The type or namespace name 'BaseMetadataAttribute' could not be found (are you missing a using directive or an assembly reference?) ImageUrlAttribute.cs DbImageAPI The type or namespace name 'ValidationAttribute' could not be found (are you missing a using directive or an assembly reference?) ImageFormat.Attribute.cs DbImageAPI Kind regards Ralf

  • Anonymous
    March 28, 2010
    Hi Scott Any plans to update this?  As Ralf noted above this doesn't compile with later versions of VS 2010.  Just tried with the RC and get a multitude of errors while compiling.  Shame as a really useful addition. Thanks John

  • Anonymous
    December 01, 2010
    Hi Scott, I'd like to add to the requests to have this code updated so that it compiles with runtime 3.5, or 4. Thanks! -Jameson

  • Anonymous
    June 06, 2011
    Is there any update on this yet? Very interesting post, but like you guys I can't compile.

  • Anonymous
    July 19, 2011
    This sample is outdated. Please post an update.

  • Anonymous
    January 25, 2012
    I compiled but couldnt accesed the databas :( its not adding picture in in database any idea how can i do it?