Posts Tagged ‘SQL Server’

A good way to handle your resources in ASP.NET MVC is by storing them in a database. With Microsoft SQL Server 2008 supporting streaming (read more), keeping your resources in the database gives you all of Microsoft SQL Server’s features for free. (ie. querying, profiling, backup, synchronisation and not to mention speed)

In the past we would normally create a HTTP handler to write to the Response.OutputStream, but with ASP.NET MVC we simply need to create another action on our preferred controller…

First we create an ‘ImageResult’ class which will handle our output.

public class ImageResult : ActionResult
{
    public Image Image { get; set; }
    public string ContentType { get; set; }
    public ImageFormat ImageFormat { get; set; }

    public ImageResult(Image image, string contentType, ImageFormat imageFormat)
    {
        Image = image;
        ContentType = contentType;
        ImageFormat = imageFormat;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        context.HttpContext.Response.Clear();
        context.HttpContext.Response.ContentType = ContentType;
        Image.Save(context.HttpContext.Response.OutputStream, ImageFormat);
    }
}

And then we simply create an action for our specific needs:

public ActionResult ResourceImage(string key)
{
    var resourceItem = _provider.GetResourceItem(key);
    var bitMap = new Bitmap(resourceItem.Stream);

    return new ImageResult(bitMap, resourceItem.ContentType, resourceItem.Format);
}

public ActionResult ResourceFile(string key)
{
    var resourceItem = _provider.GetResourceItem(key);
    return File(resourceItem.Stream, resourceItem.Format, key);
}

All you need to do is create your own provider that would find the key in the database and return the stream and the format of the file.


If you like the new publishing feature of Microsoft SQL Server 2008 and find yourself at a company that still uses 2000 or 2005 (god forbid), then this tool might come in handy.
The complete publishing wizard comes with very handy command line tools that you can use in your NAnt or MsBuild tasks to create or backup your databases.

Link to download version 1.1 of the ‘Microsoft SQL Server Database Publishing Wizard’ below:

Microsoft SQL Server Database Publishing Wizard