Showing posts with label asp. Show all posts
Showing posts with label asp. Show all posts

Thursday, 28 June 2012

ASP.NET 3.5 Directives



ASP.NET PAGE DIRECTIVE

ASP.NET provides the number of directives with the help of it we can control the behavior of ASP.NET Pages. 
We have 11 directives that we can use in our ASP.NET pages or user controls. 
We can use these directives regardless we are using Inline Coding Model or Code-Behind Model.
These directives are the commands that complier uses when the page is compiled. Format to write the directive is given below

<%@ Directive attribute= value %>

Now lets talk about the number of directives that are provided in ASP.NET one by one



PAGE DIRECTIVE

It specifies the attribute and values that are associated with Web Form Pages (.aspx).
When the compiler complies the project the page directive send command that are basically used for compiling the page. 
Some of the attributes of the page directive is :- Code File, Buffer, Culture, Debug, Language, Inherits. 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>Master Directive
It specifies the attribute and values that are associated with Master Pages (.master).
In it, we specify the properties of the master page (templated page) that we will be conjunction with any number of content page. 
Some of the attributes of the master page directive is :- Code File, Debug, Language, Inherits, EnableView State, MasterPageFile, Src.

<%@ Master Language="C#" %>

Control Directive

It specifies the attribute and values that are associated with WebUserControl (.ascx).
It is used to bind as ASP.NET user control. 
It defines the properties to be inherited by the user control.
When the page is parsed and compiled then these values are assigned then assigned to the use control.
Some of the attributes of the master page directive is :- Code File, Debug, Language, Inherits, EnableView State, Src, ClassName, Description, CompilerOptions

<%@ Control Language="C#" ClassName="WebUserControl" %>

Import Directive

We use the import directive when we want to import any namespace in the ASP.NET page or user control.
When we import any namespace the we are able to use it's classes and interfaces.
This directive has only one attribute called "Namespace".
As much namespace we want to import the same number of import directive must be included.

<%@ Import Namespace="System.Data.SqlClient" %>

Implements Directive


We use the implements directive when we want to import any interface in the ASP.NET page or user control.
When we import any interface the we are able to use it's members.
This directive has only one attribute called "Interface".
As much interface we want to use the same number of implements directive must be included.

<%@ Implements Interface="System.Web.UI.IValidator" %>

h2>Register Directive 
When we drag and drop the web user control on the web form page then in the source page the register directive is automatically included. 
It is used to register the user control on the page so that the control can be accessed on the web form (.aspx) page.
Some of the attribute of register directive is :- assembly, namespace, src, tagname, tagprefix.

<%@ Register src="WebUserControl.ascx" tagname="WebUserControl" tagprefix="uc1" %>

Assembly Directive

It associates the assemblies to the ASP.NET page or user control so that at the compile time assembly's classes and interface is available to the page.
Attribute of the register directive is :- name and src

<%@ Assembly Name="Baljeet" Src="Baljeet.cs" %>

PreviousPageType Directive

It defines the page from which any cross-page posting originate.
It is new in the ASP.NET 3.5.
Attribute of the previouspagetpype is :- typename, virtualpath.MasterType Directive

It is applied on the Web Forms not on WebUserControl. 
When we define this directive then we get the references or members contained in the specified master page.
Attribute of the MasterType is :- typename, virtualpath.

<%@ MasterType VirtualPath="~/MasterPage.master" %>

OutputCache Directive

It control the output caching of the ASP.NET pages or user control.
Attribute of the outputcache is :- cacheprofile, duration, location, varybycontrol, varybycustom, shared.

<%@ OutputCache Duration="180" VaryByParam="None" %>

Reference Directive

It define the another ASP.NET page or user control that should be complied along with active page or control.
It support only one attribute :- virtualpath. 

<%@ Reference VirtualPath="~/WebUserControl.ascx" %>

Wednesday, 27 June 2012

Captcha Image in C# .NET

Captcha (Completely Automated Public Turing test to tell Computers and HumansApart.)

The Captcha technology help you to make sure your site is reasonably secure against automated attacks.

Step:1 Write the following code in a class named CaptchaText.cs or you can download it here 


public class CaptchaText
{
   public string Text
   {
     get { return this.text; }
   }
   public Bitmap Image
   {
     get { return this.image; }
   }
   public int Width
   {
     get { return this.width; }
   }
   public int Height
   {
     get { return this.height; }
   }

   private string text;
   private int width;
   private int height;
   private string familyName;
   private Bitmap image;
   private Random random = new Random();
   public CaptchaText(string s, int width, int height)
   {
     this.text = s;
     this.SetDimensions(width, height);
     this.GenerateImage();
   }
   public CaptchaText(string s,int width,int height,string familyName)
   {
     this.text = s;
     this.SetDimensions(width, height);
     this.SetFamilyName(familyName);
     this.GenerateImage();
   }
   ~CaptchaText()
   {
     Dispose(false);
   }
   public void Dispose()
   {
     GC.SuppressFinalize(this);
     this.Dispose(true);
   }
   protected virtual void Dispose(bool disposing)
   {
     if (disposing)
     this.image.Dispose();
   }
   private void SetDimensions(int width, int height)
   {
    if (width <= 0)
    throw new ArgumentOutOfRangeException("width",width,"Argument out of range,
                                                                                must be greater than zero.");
    if (height <= 0)
    throw new ArgumentOutOfRangeException("height",height,"Argument out of range,
                                                                                must be greater than zero.");
    this.width = width;
    this.height = height;
   }
   private void SetFamilyName(string familyName)
   {
      try
      {
        Font font = new Font(this.familyName, 12F);
        this.familyName = familyName;
        font.Dispose();
      }
      catch (Exception ex)
      {
        this.familyName = System.Drawing.FontFamily.GenericSerif.Name;
      }
   }
private void GenerateImage()
{
Bitmap bitmap = new Bitmap(this.width,this.height,PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(bitmap);
g.SmoothingMode = SmoothingMode.AntiAlias;
Rectangle rect = new Rectangle(0, 0, this.width, this.height);
HatchBrush hatchBrush=new HatchBrush(HatchStyle.SmallConfetti,Color.LightGray,Color.White);
g.FillRectangle(hatchBrush, rect);
   SizeF size;
   float fontSize = rect.Height + 1;
   Font font;
   do
   {
     fontSize--;
     font = new Font(this.familyName, fontSize, FontStyle.Bold);
     size = g.MeasureString(this.text, font);
   } while (size.Width > rect.Width);

  StringFormat format = new StringFormat();
  format.Alignment = StringAlignment.Center;
  format.LineAlignment = StringAlignment.Center;
 GraphicsPath path = new GraphicsPath();
 path.AddString(this.text,font.FontFamily,(int)font.Style,font.Size,rect,format);
 float v = 4F;
 PointF[] points =
 {
  new PointF(this.random.Next(rect.Width) / v, this.random.Next(rect.Height) / v),
  new PointF(rect.Width - this.random.Next(rect.Width) / v, this.random.Next(rect.Height) / v),
  new PointF(this.random.Next(rect.Width) / v, rect.Height - this.random.Next(rect.Height) / v),
  new PointF(rect.Width - this.random.Next(rect.Width) / v,rect.Height - 
                                                                                      this.random.Next(rect.Height) / v)
  };
    Matrix matrix = new Matrix();
    matrix.Translate(0F, 0F);
    path.Warp(points, rect, matrix, WarpMode.Perspective, 0F);
    hatchBrush = new HatchBrush(HatchStyle.LargeConfetti, Color.LightGray, Color.DarkGray);
    g.FillPath(hatchBrush, path);
    int m = Math.Max(rect.Width, rect.Height);
    for (int i = 0; i < (int) (rect.Width * rect.Height / 30F); i++)
      {
            int x = this.random.Next(rect.Width);
            int y = this.random.Next(rect.Height);
            int w = this.random.Next(m / 50);
            int h = this.random.Next(m / 50);
            g.FillEllipse(hatchBrush, x, y, w, h);
      }
         font.Dispose();
         hatchBrush.Dispose();
         g.Dispose();
         this.image = bitmap;
    }
 } 

Step:2 Create a page named "Captcha.aspx" and add code in Captcha.aspx.cs


protected void Page_Load(object sender, EventArgs e) {   if (Session["CaptchaImageText"] != null)    {       CaptchaText ci = new CaptchaText(this.Session["CaptchaImageText"].ToString(), 200, 50, "Century Schoolbook");        this.Response.Clear();        this.Response.ContentType = "image/jpeg";        ci.Image.Save(this.Response.OutputStream, ImageFormat.Jpeg);        ci.Dispose();    }  }


Step:3 Now Call Captcha.aspx in that page you want to appear it for ex: "Default.aspx"

Add code in Default.aspx


<table width="100%">     <tr>       <td align="left">         <img id="imgcaptcha" runat="server" src="~/Captcha.aspx" alt="Enter the code shown" />        </td>     </tr>     <tr>       <td align="left">           <asp:Label runat="server" ID="lblBox" Text="Enter the code shown"></asp:Label>            <br />           <asp:TextBox ID="CodeNumberTextBox" runat="server"></asp:TextBox>           <asp:Label ID="lblerrCaptcha" runat="server" Visible="false"></asp:Label>         </td>      </tr>     <tr>      <td align="left">         <asp:LinkButton ID="lnkGetQuotes" Text="GetQuotes"  runat="server" OnClick="btnGetQuotes_Click">      </td>    </tr> </table>

Now,Compare that to value to what the users had keyed in to your text box, To do that add code in Default.aspx.cs


private Random random = new Random();
 protected void Page_Load(object sender, EventArgs e)
 {
   if (!IsPostBack)
    {
       Session["CaptchaImageText"] = "";
       Session["CaptchaImageText"] = GenerateRandomCode();
    }
 }
private string GenerateRandomCode()
{
            string s = "";
            for (int i = 0; i < 6; i++)
                s = String.Concat(s, this.random.Next(10).ToString());
            return s;
}
protected void btnGetQuotes_Click(object sender, EventArgs e)
{
   if (Convert.ToString(Session["CaptchaImageText"]) != "" &&
             Convert.ToString(CodeNumberTextBox.Text) != "")
   {
     if (CodeNumberTextBox.Text == Session["CaptchaImageText"].ToString())
     { 
        // add your code for the button
     }
    else
     {
         lblerrCaptcha.Visible = true;
         lblerrCaptcha.Text = "Please enter the correct code";
     }
}
else
   {
          lblerrCaptcha.Visible = true;
          lblerrCaptcha.Text = "Please enter the code"; 
   }
} 

The output is like as: