Tuesday, December 4, 2012

Custom HTTPHandler

==================
web.config
==================
<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <system.web>
    <httpHandlers>
      <add path="*" verb="*" type="Kompas.KompasPageHandler" />
    </httpHandlers>
    <compilation debug="true" targetFramework="4.0"/>
  </system.web>
</configuration>


==================================
HTTPHandler (dimasukkan di App_Code)
=================================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for KompasPageHandler
/// </summary>
namespace Kompas
{

    public class KompasPageHandler : IHttpHandler
    {
        public KompasPageHandler()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {

            //context.Response.Write(context.Request.RawUrl);
            //context.Response.Write("Halooo...");

            string kata = context.Request.QueryString["kata"];

            int width = 600; //int.Parse(context.Request.QueryString["width"]);
            int height = 400; //int.Parse(context.Request.QueryString["height"]);

            Bitmap bitmap = new Bitmap(width, height);
            Font drawFont = new Font("Arial", 16);
            SolidBrush drawBrush = new SolidBrush(Color.Black);
            SolidBrush drawBrushWhite = new SolidBrush(Color.White);
            PointF drawPoint = new PointF(150.0F, 350.0F);
            Pen whitePen = new Pen(Color.White, 1);

            Graphics g = Graphics.FromImage((Image)bitmap);
            g.FillRectangle(Brushes.Red, 0f, 0f, bitmap.Width, bitmap.Height); // fill the entire bitmap with a red rectangle

            for (float i = 0f; i <= 1500f; i += 20f)
            {
                g.DrawLine(whitePen, 0, i/5, i, 500f);
            }
            g.DrawString(kata, drawFont, drawBrush, drawPoint);

            MemoryStream mem = new MemoryStream();
            bitmap.Save(mem, ImageFormat.Png);

            byte[] buffer = mem.ToArray();

            context.Response.ContentType = "image/png";
            context.Response.BinaryWrite(buffer);
            context.Response.Flush();

        }
    }
}


No comments:

Post a Comment