Mega Code Archive

 
Categories / ASP.Net Tutorial / Development
 

Creating a Generic Handler

When you  create a Generic Handler, you  create a file that ends with the extension .ashx. Whenever you request the .ashx file, the Generic Handler executes. A Generic Handler is like an ASP.NET page that contains a single method that renders content to the browser.  You can't add any controls declaratively to a Generic Handler.  A Generic Handler doesn't support events such as the Page Load or Page PreRender events. File: ImageTextHandler.ashx <%@ WebHandler Language="C#" Class="ImageTextHandler" %> using System; using System.Web; using System.Drawing; using System.Drawing.Imaging; public class ImageTextHandler : IHttpHandler {     public void ProcessRequest(HttpContext context)     {         string text = context.Request.QueryString["text"];         string font = context.Request.QueryString["font"];         string size = context.Request.QueryString["size"];         Font fntText = new Font(font, float.Parse(size));         Bitmap bmp = new Bitmap(10, 10);         Graphics g = Graphics.FromImage(bmp);         SizeF bmpSize = g.MeasureString(text, fntText);         int width = (int)Math.Ceiling(bmpSize.Width);         int height = (int)Math.Ceiling(bmpSize.Height);         bmp = new Bitmap(bmp, width, height);         g.Dispose();         g = Graphics.FromImage(bmp);         g.Clear(Color.White);         g.DrawString(text, fntText, Brushes.Black, new PointF(0, 0));         g.Dispose();         bmp.Save(context.Response.OutputStream, ImageFormat.Gif);     }     public bool IsReusable     {         get         {             return true;         }     } } You specify the image that you want to return from the handler by making a request that looks like this: /ImageTextHandler.ashx?text=Hello&font=Arial&size=30 The IsReusable property indicates whether the same handler can be reused over multiple requests.  The following page uses the ImageTextHandler.ashx file.  <%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server">     <title>Show ImageTextHandler</title> </head> <body>     <form id="form1" runat="server">     <div>     <img src="ImageTextHandler.ashx?text=Some Text&font=WebDings&size=42" />     <br />     <img src="ImageTextHandler.ashx?text=Some Text&font=Comic Sans MS&size=42" />     <br />     <img src="ImageTextHandler.ashx?text=Some Text&font=Courier New&size=42" />     </div>     </form> </body> </html>