It grabs the PDC logo from Microsoft, calculates the days until PDC,
and renders a new image to the outgoing Response stream, as a JPEG
image. I've tossed this code up on CodeBetter, so if you want to
add this image to your blog, you just need to add this HTML:
<a href="http://msdn.microsoft.com/events/pdc/"><img src="/pdccountdownimage.ashx"></a>
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Net;
using System.Web;
using System.Web.Caching;
public class PdcCountdownImage : IHttpHandler
{
public bool IsReusable
{
get { return true; }
}
/// <summary>
/// Processes the request.
/// </summary>
/// <param name="ctx">CTX.</param>
public void ProcessRequest(HttpContext ctx)
{
Byte[] imageBytes = null;
// Check if the cache contains the image.
Object cachedImageBytes = HttpRuntime.Cache.Get("PDCBYTES");
// We have some cached bytes, use em!
if (cachedImageBytes != null)
{
imageBytes = cachedImageBytes as byte [];
}
else
{
// Gotta go get the PDC image, hope they don't change the location
System.Net.WebClient webClient = new WebClient();
byte [] pdcImageBytes = webClient.DownloadData("http://msdn.microsoft.com/events/pdc/images/home_pdc_masthead.gif");
using(Image inputImage = Image.FromStream(new MemoryStream(pdcImageBytes)))
using(Image outputImage = new Bitmap(inputImage))
{
using(Graphics g = Graphics.FromImage(outputImage))
{
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime pdcStartDate =
DateTime.Parse("9/13/2005",
culture,
DateTimeStyles.NoCurrentDateDefault);
DateTime pdcEndDate =
DateTime.Parse("9/16/2005",
culture,
DateTimeStyles.NoCurrentDateDefault);
DateTime today = DateTime.Today;
string message = String.Empty;
if(today < pdcStartDate)
{
message = String.Format("It's in {0} days!", (pdcStartDate - today).Days);
}
else if(today >= pdcStartDate && today <= pdcEndDate)
{
message = " It's on baby!";
}
else
{
message = " It's over baby!";
}
using(Font font = new Font("Arial", 16))
{
g.DrawString(message, font, Brushes.Gray,1,1);
}
using(MemoryStream stream = new MemoryStream())
{
outputImage.Save(stream, ImageFormat.Jpeg);
imageBytes = stream.GetBuffer();
}
HttpRuntime.Cache.Add("PDCBYTES", imageBytes, null,
today.AddDays(1), new TimeSpan(0, 0, 0),
CacheItemPriority.Normal, null);
}
}
}
ctx.Response.Cache.SetExpires(DateTime.Today.AddDays(1));
ctx.Response.Cache.SetCacheability(HttpCacheability.Public);
ctx.Response.Cache.SetValidUntilExpires(true);
ctx.Response.ContentType = "image/jpg";
ctx.Response.BufferOutput = false;
ctx.Response.OutputStream.Write(imageBytes, 0, imageBytes.Length);
ctx.Response.End();
}
}