Showing posts with label Database. Show all posts
Showing posts with label Database. Show all posts

Saturday, June 28, 2014

Programming: Asp.net dynamic image access.

A side project in asp.net has me working with a dump-truck's worth of images; Uploading, naming, sorting, serving, renaming, moving... are just some of the operations the solution is expected to perform.

For the purposes of this post I will call this 'Project potato' since it is currently unreleased, and potatoes are unsung heroes.

The common solution that you tend to find is to store an item in a database as blob data and retrieve it using a .ashx file. This has a number of advantages.

First you don't need to deal with the server's file system - meaning you don't need to deal with mirroring changes across multiple servers/having a dedicated image server. Secondly you do not have to deal with file permissions.

A lazy architect (or an over-controlling sysadmin) loves storing images in the database. Somebody needs to tell these people that blob data has issues.

So how does one use the file system instead of the database? There is a (short) check-list of things you need to do.

1) Web-readable, internally modifiable file share
To cover the internally modifiable requirement you need to set the permissions for asp.net to access the files. This requires slightly different things for older or newer implementations of iis.

Project potato itself uses Content/images as the place for images, and uses a newer version of iis on windows 2012. (Sidebar: one thing I have noticed is that the user that asp.net is configured to use for file access will, naturally, be the owner of any file it creates, if this is a problem you may wish to do something about it.)

What do I mean by web readable? Can access with a web browser, at for example:
"www.yoururl.com/content/images/image.png".

There's too many ways to make resources web-available to go into detail here though.

2) Set the location
If you know that all images will be in content/images you do not need to store that part of the path, adding it in at runtime. All you need to do is set the image control to point at the core path, eg.

image.ImageUrl = Path.Combine(@"\Content\images\", valueFromDB);

(Sidebar: Generally speaking I like to have the @"\Content\images\" part to instead reference a separate configuration class. This is so I can modify it to point at wherever I need it to without having to traul through thousands of lines of code to make individual changes.)