Click here to Skip to main content
6,596,602 members and growing! (21,148 online)
Email Password   helpLost your password?
Web Development » ASP.NET » General     Intermediate

ImageLabel Control for ASP.NET (Potential CAPTCHA Control)

By Can Erten

Labels are generated as images instead of text to have more privacy without any configurations without httphandlers
Windows, .NET, ASP.NET, Visual Studio, Dev
Posted:28 Dec 2006
Updated:13 Jan 2007
Views:20,559
Bookmarked:24 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
2 votes for this article.
Popularity: 1.30 Rating: 4.31 out of 5

1

2

3
1 vote, 50.0%
4
1 vote, 50.0%
5

Sample Image - ImageLabel.png

Introduction

This an ASP.NET web control for generating labels as images. You might want to do that for providing security for e-mail crawlers or to disallow copy paste of the text. Many similar controls have implemented as HttpHandlers, so you need more configuration to make them work. However this control does not need any configuration. You just need to use just like any other asp.net control like Label. Almost all of the label formatting options are included, like font size, backcolor, forecolor.

How does it work

The code can be separated to 2 parts. First for the variables initializations and then the render part. OnInit event is used for the preparation of url string of the image to be generated. The url string is stored in a private member of the class with the client to make sure that many controls draw itself.
There is a trick here. This control is executed twice by the browser. To make things work the query string is in a predefined format. The browser tries to display the image specified by a tag and the init code tries to read whether it is coming from querystring or not to generate the image.

      protected override void OnInit(EventArgs e)
        {
            
            if (this.Context.Request.QueryString[QueryStringText()] != null)
            {
                DrawImage(this.Text);
            }  
            this.m_URL = Context.Request.Url.AbsolutePath + "?" + secretQueryString+ this.ClientID + "=1";
           base.OnInit(e);
        }
However there is another problem, since the browser is executing twice the control their Controlstate is also different so storing the display text value will not work using the ViewState. As a result I store it in the session variable, that is cleared after rendering the image.
The Text property of the control handles the session and the automatic code generated by the designer. You know when you set the text of the control from the designer after compilation it is executed by the asp.net process. I'm telling this because this control runs two control with different life cycles. "this.Context.Request.QueryString[QueryStringText()]" makes sure that we are coming from the main page, rather than the forked control.
   public string Text
        {
           get
            {
                if (DesignMode)
                {
                    if (ViewState["Text"] == null)
                        ViewState["Text"] = string.Empty;
                    return (string)ViewState["Text"];
                }
                else
                {
                    string s = PossiblequeryString();

                    if (!string.IsNullOrEmpty(s))
                        return (string)Context.Session[s]; 
                   

                    
                    if (Context.Session[SessionText()] == null)
                        Context.Session[SessionText()] = string.Empty;
                    return (string)Context.Session[SessionText()];
                }
            }

            set
            {
                if (DesignMode)
                {
                    ViewState["Text"] = value;
                }
                else
                {

                    if (PossiblequeryString() == null)
                    {
                        Context.Session[SessionText()] = value;
                    }
               
                }
            }
        }
DrawImage function draws the image in memory and save to Response Object. Since Response.End method is executed, Render events will not be fired any more at image generation.
  strOutput.DrawString(Message, msgFont, new SolidBrush(foreColor), 1, 1);
            MemoryStream memStream = new MemoryStream();
            bmp.Save(memStream, System.Drawing.Imaging.ImageFormat.Png);


            Context.Response.Clear();
            Context.Response.ContentType = "image/png";
            Context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            memStream.WriteTo(Context.Response.OutputStream);
            Context.Session.Remove(SessionText());
            Context.Response.OutputStream.Flush();
            Context.Response.OutputStream.Close();
            Context.Response.End();
Render Code is used for the rendering of the image, it is simply an image html tag pointing to the url generated previously on onInit. To make Visual Studio designer happy and stop it complaining about exceptions, I added also to render itself as a normal text control in the designer.
  protected override void Render(HtmlTextWriter writer)
        {
            if (DesignMode)
            {
                base.Render(writer);
            }
            else
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Src, this.m_URL);
                writer.RenderBeginTag(HtmlTextWriterTag.Img);
                writer.RenderEndTag();
            }
          
        }

Conclusion

This control works without any configuration and easy to use as other ASP.NET Web Controls. It can be used to hide information from the crawlers or robots. Although this is not implemented for CAPTCHA control, that functionality can easily added to image generation.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Can Erten


Member
Blog:
aka Coding Day

Occupation: Software Developer
Location: Turkey Turkey

Other popular ASP.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 7 of 7 (Total in Forum: 7) (Refresh)FirstPrevNext
GeneralRuntime Settings PinmemberBrad Bruce10:46 29 Dec '06  
AnswerRe: Runtime Settings PinmemberCan Erten14:30 29 Dec '06  
GeneralRe: Runtime Settings PinmemberBrad Bruce15:08 29 Dec '06  
AnswerRe: Runtime Settings PinmemberCan Erten15:28 29 Dec '06  
GeneralRe: Runtime Settings PinmemberBrad Bruce8:30 30 Dec '06  
AnswerRe: Runtime Settings PinmemberCan Erten14:46 13 Jan '07  
GeneralDown with HttpHandlers PinmemberBrad Bruce6:22 29 Dec '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 13 Jan 2007
Editor:
Copyright 2006 by Can Erten
Everything else Copyright © CodeProject, 1999-2009
Web21 | Advertise on the Code Project