19. September 2006 03:00
A little puzzle came up today. Fetch an image out of a database and stream it down to the browser. The trick: we don't know what type of image is stored in the database. So I borrowed a little from our Python friends and this is what I ended up with.
internal static class ImageTypeFinder
internal static string GetMimeType(byte image)
string retval = "image/jpeg";
string imgtype = GetImageType(image);
retval = "image/bmp";
retval = "image/gif";
retval = "image/tiff";
retval = "image/png";
internal static string GetImageType(byte image)
int len = image.Length;
if (len > 32) len = 32;
string first32 = ASCIIEncoding.ASCII.GetString(image, 0, len);
internal static string GetImageType(string first32)
string retval = string.Empty;
if (first32.StartsWith("GIF87a") || first32.StartsWith("GIF89a"))
retval = "gif";
else if (first32.StartsWith("MM") || first32.StartsWith("II"))
retval = "tif";
else if (first32.Substring(6, 4) == "JFIF" || first32.Substring(6, 4) == "Exif")
retval = "jpg";
else if (first32.StartsWith("BM"))
retval = "bmp";
else if (first32.Substring(1, 3) == "PNG")
retval = "png";
It's a bit of an esoteric puzzle, but if you're trying to solve this one, the above code should help.
12. September 2006 17:17
I want a T-shirt with these words on it:
Bad Code is Platform Independent
All the political and religious debates about platform superiority all come to an end when running bad code. It amazes me how much bad code is out there (some of mine included). And yet we so often jump to blame the platform, runtime, operating system, tools, or some other outside element.
Where have all the good coders gone? More to the point. Were there ever any?
Bad coders never die, they just pick a new platform.
1. September 2006 09:52
Some time ago and again today, I had occasion to write an ASP.NET page that had no form in the .ASPX page but would accept and handle POST 'ed data. This was in an effort to support a REST-like interface for non-ASP.NET developers. Here's the way it turned out.
The .ASPX page looks something like this:
<%@ Page Language="C#"
There is nothing else in the file. Now the code behind looks like this:
public partial class extract : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
string alldata = string.Empty;
using (StreamReader sr = new StreamReader(this.Request.InputStream))
alldata = sr.ReadToEnd();
//convert to strings - assumes URL encoded data
string pairs = alldata.Split('&');
NameValueCollection form = new NameValueCollection(pairs.Length);
foreach (string pair in pairs)
string keyvalue = pair.Split('=');
if (keyvalue.Length == 2)
if (alldata.Length > 0 && this.Request.HttpMethod.ToUpper() == "POST")
if (form["text"] != null)
//TODO - do something with the data here
Response.Write("*** 501 Invalid data ***");
Response.Write("*** 599 GET method not supported. ***");
Well, there you have it. There are probably better ways to do this, but I didn't find one.