Friday, November 21, 2008

SiteMap


http://techiefromsurat.blogspot.com/2008/11/captcha-image-using-c-in-aspnet.html

http://techiefromsurat.blogspot.com/2008/11/microsoft-virtual-techdays.html

http://techiefromsurat.blogspot.com/2008/11/dynamic-table-in-aspnet-using-c.html

http://techiefromsurat.blogspot.com/2008/11/custom-paging-in-aspnet-with-data-grid.html

Thursday, November 20, 2008

Captcha Image using C# in Asp.Net

Captcha Image using C# in Asp.Net

 

What is Captcha Image?

 

In web when ever you are registering on any site normally they are asking at the end of page for enter Image code/Challenge Image/Image verification code etc. This type of image called Captcha Image.

 

 

What is the use of Captcha?

 

(Source: http://en.wikipedia.org/wiki/Captcha)

 

Captcha is a type of challenge-response test used in computing to ensure that the response is not generated by a computer. The process usually involves one computer (a server) asking a user to complete a simple test which the computer is able to generate and grade. Because other computers are unable to solve the CAPTCHA, any user entering a correct solution is presumed to be human.

 

A best technique to restrict automatic form submissions when developing a web page is to add some kind of verification. And as per my knowledge image verification is the best way, it’s also called Captcha image. In this process dynamically we are creating a image with random string either string, number or alphanumeric and display on the web page. After that at the time of form submission user is asked to enter same code in the text box as shown in that image. Once form is submitted then we can compare both auto generated value and entered by user. Because there id no other good way to protect your webworms from spammers (auto submission).

 

 

How can we do that?

 

Here is the details explanation with Code snippets.

 

This is the default.aspx (partially)

Html Code

 

    <asp:Label ID="lblmsg" runat="server" Font-Bold="True" ForeColor="Red" Text="">asp:Label>

    <br />

    Enter code shown below in text box.

    <asp:TextBox ID="txtimgcode" runat="server" ValidationGroup="1">asp:TextBox><br />

        <img height="70" width="200" src="CImage.aspx" width="176" alt="" />

        <br />

    div>

    <asp:Button ID="Button1" runat="server" Text="Validate" onclick="Button1_Click" />

 

In above code there are three control Lable control to display message weather entered code is matched or not. TextBox to take input from user and Image box to hold a image autogenerated by CImage.aspx page. Before that we will see default.aspx.cs page code

 

 

protected void Button1_Click(object sender, EventArgs e)

    {

        if (this.txtimgcode.Text == this.Session["CaptchaImageText"].ToString())

        {

            lblmsg.Text = "Excellent.......";

        }

        else

        {

            lblmsg.Text = "image code is not valid.";

        }

        this.txtimgcode.Text = "";

    }

 

In button’s click event we are just checking entered value with stored value in session. And display appropriate message on the screen.

 

CImage.aspx page

Remove all the code except first line

 

Like 

 

Main code is here witch is calling a method to generate random no string and pass it to class file which will generate image with same string and retrun it as a Jpeg format.

 

Here is the details code.

 

using System.Drawing.Imaging;

 

public partial class CImage : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        // Create a random code and store it in the Session object.

        this.Session["CaptchaImageText"] = GenerateRandomCode();

 

        // Create a CAPTCHA image using the text stored in the Session object.

        RandomImage ci = new RandomImage(this.Session["CaptchaImageText"].ToString(), 300, 75);

 

        // Change the response headers to output a JPEG image.

        this.Response.Clear();

        this.Response.ContentType = "image/jpeg";

 

        // Write the image to the response stream in JPEG format.

        ci.Image.Save(this.Response.OutputStream, ImageFormat.Jpeg);

 

        // Dispose of the CAPTCHA image object.

        ci.Dispose();

    }

  

    // Function to generate random string with Random class.

 

    private string GenerateRandomCode()

    {

        Random r = new Random();

        string s = "";

        for (int j = 0; j <>

        {

            int i = r.Next(3);

            int ch;

            switch (i)

            {

                case 1:

                    ch = r.Next(0, 9);

                    s = s + ch.ToString();

                    break;

                case 2:

                    ch = r.Next(65, 90);

                    s = s + Convert.ToChar(ch).ToString();

                    break;

                case 3:

                    ch = r.Next(97, 122);

                    s = s + Convert.ToChar(ch).ToString();

                    break;

                default:

                    ch = r.Next(97, 122);

                    s = s + Convert.ToChar(ch).ToString();

                    break;

            }

            r.NextDouble();

            r.Next(100, 1999);

        }

        return s;

    }

}

 

 

And finally at last the code for RandomImage class which is genrating Image with the help of BitMap class.

 

//Extra name space

using System.Drawing;

using System.Drawing.Drawing2D;

using System.Drawing.Imaging;

using System.Drawing.Text;

public class RandomImage

{

//Default Constructor

      public RandomImage(){}

//property

      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 variable

    private string text;

    private int width;

    private int height;

    private Bitmap image;

 

    private Random random = new Random();

    //Methods decalration

    public RandomImage(string s, int width, int height)

    {

          this.text = s;

          this.SetDimensions(width, height);

          this.GenerateImage();

    }

 

    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 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(FontFamily.GenericSansSerif, 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);

        path.AddString(this.text, font.FontFamily, (int)font.Style, 75, 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.Percent10, Color.Black, Color.SkyBlue);

          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;

    }

}

 Happy protecting Auto submission...................



Tuesday, November 18, 2008

Custom Paging in Asp.Net with Data Grid or Grid View

Custom Paging in Asp.Net with Data Grid or Grid View


Purpose:


When ever in any large application lots of data are there, and we want to display all the data on the page so long scroll will come, and might be some alignment issue can arise. For that purpose to display some specific no of data on the page and at the bottom or top of the page display page no list so user can move easily on the specific page quickly.



But Grid view and Data grid is giving in built paging facility. So there is no need to develop it independently right? No it’s wrong; Let me come to the point, suppose we are developing any shopping cart application. In that application user is searching for particular item and that item is suppose mobile device. Now in store there are 1000 different models. But you are displaying only 20,30 or 50 models on the page and then paging is there. But when ever you are retrieving data from database all 1000 record will come into result. On the client end rest of data will be eliminated by grid and display particular no of data on the page. So why we are retrieving extra data from database?, why we will use network bandwidth?, why we will create overhead on server, database and network? For that we need custom page to retrieve data effectively.


What is custom paging?



Custom paging in the sense implement the paging facility in web page by programmatically. In this procedure how can we achieve this functionality just see it here. In our application when ever large amount of data is there to be displayed. Then write a Stored Procedure and pass two parameter one for page id and second for no of data. And from procedure retrieve specific no of data that’s it. It’s very simple.



Here is the sample code for stored procedure.



CREATE Procedure [dbo].[CustomePaging]


-- Declare parameters.


@CurrPage As int,


@PageSize As int


As


Set NoCount On



-- Declare variables.


Declare @FRec int


Declare @LRec int


-- Initialize variables.


Set @FRec = (@CurrPage - 1) * @PageSize


Set @LRec = (@CurrPage * @PageSize + 1)



-- Create a temporarily table to hold the current page of data


--Guess we are retrieving from emp table name and age


Create Table #Temp


(


RecId int IDENTITY PRIMARY KEY,


Emp_Name varchar(100),


Emp_Age int)


--Fill the temp table with the reminders


Insert Into #Temp


(


Emp_Name, Emp_Age)


Select Emp_Name,Emp_Age from emp Order By Emp_Id Desc -- Assume Emp_Id is primary key


--Select one page of data based on the record numbers above


Select * From #Temp Where RecId > @FRec And RecId < @LRec


Drop Table #Temp



In above procedure we are passing two parameters CurrentPage and PageSize. On base upon we set First Record and Last record No. Then we create Temp Table select all the data from original table and insert into that temp table. From there we are retrieving all the data between First and Last Record.



In webpage set CurrentPage=1 during page load event then put two arrow button on page like previous and next and on the click of that button set current page index either CurrentPage -1 or CurrentPage +1 and then again retrieve data and bind to grid or datagrid.


Happy custom paging…………….





Monday, November 17, 2008

Virtual TechDays

Microsoft Virtual TechDays is Back: Register Now?



Virtual TechDay
Don’t miss this opportunity. Get trains on the latest Microsoft technology.


Here is an opportunity to learn new Microsoft Technology and product online by Microsoft Expert. And also participate into quiz and win the excellent prizes.

Also meet new attendees by attending this event live with Windows live meeting software. If you don’t have, download it from here.

And there is no fee to attend it online. It’s totally free. You can attend it from anywhere.

This event will focus on the below product. Just have a look

Exchange Server 2007
SQL Server 2008
Visio 2007
Windows Essential Business Server 2008
Microsoft Office Communications Server 2007
Windows Server 2008
Internet Explorer 8

Above all the latest product will be discusses with example and details.

So be sure to be there.

On
November
24 – 26, 2008
10.00 Am – 6:30 PM IST(GMT + 5:30)

Join Virtual TechDays

And be the part of Virtual Techdays

Friday, November 14, 2008

Dynamic Table in Asp.Net using C#

Dynamic Table in Asp.Net using C#

What is Dynamic Table?

Dynamic table in the sense to create a data table dynamically and add rows one by one programmatically. After creating Data Table and adding rows we can bind that data table to any data grid or grid view as a data source.

Why and where we need it?

Suppose when ever we are developing Shopping Cart application or Creating wish list or adding sub category and want to add database after adding category that time we need any data source to hold it temporarily. In above circumstances we can use data table very effectively.

Here is the working code

I had created Class file for creating a DataTable and Column but you can use as per requirement.

--DynamicTable.cs Class File

Here we will create a table width name and Id two fields.

public class DynamicTable

{

public DynamicTable() { }

public DataTable CreateDataSource()

{

DataTable dt = new DataTable();

DataColumn identity = new DataColumn("ID", typeof(int));

dt.Columns.Add(identity);

dt.Columns.Add("Name", typeof(string));

return dt;

}

//This is the AddRow method to add a new row in Table dt public void AddRow(int id,string name, DataTable dt)

{

dt.Rows.Add(new object[] { id,name,pname });

}

}

Here our aspx page is there

<body>

<form id="form1" runat="server">

<div>

<table style="width:50%;">

<tr>

<td>

Add Nametd>

<td>

<asp:TextBox ID="TextBox1" runat="server">asp:TextBox>

td>

tr>

<tr>

<td>

td>

<td>

<asp:Button ID="Button1" runat="server" Text="Add Name"

onclick="Button1_Click" />

td>

tr>

<tr>

<td>

td>

<td>

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"

DataKeyNames="ID" EmptyDataText ="There are no data here yet!"

onrowcommand="GridView1_RowCommand"

onrowdatabound="GridView1_RowDataBound" onrowdeleting="GridView1_RowDeleting" >

<Columns>

<asp:TemplateField>

<HeaderTemplate>NameHeaderTemplate>

<ItemTemplate>ItemTemplate>

asp:TemplateField>

<asp:TemplateField HeaderText="Remove">

<ItemTemplate>

<asp:LinkButton ID="LinkButton1" CommandArgument=''

CommandName="Delete" runat="server">Removeasp:LinkButton>

ItemTemplate>

asp:TemplateField>

Columns>

asp:GridView>td>

tr>

table>

div>

form>

body>

Here is the aspx.cs file

When add new name to datatable this code will fire. Here we are maintaing session for datacolumid and to hold that datatable line has it’s own comment so you can understand easily.

protected void Button1_Click(object sender, EventArgs e)

{

DynamicTable Dt = new DynamicTable();

DataTable d = null;

//If session is not there means first time addinf record.

if (Session["dt"] == null)

{

d = Dt.CreateDataSource();

Session["IDClm"] = 1;

}

//else we are converting session of datatable to data table and increament the column id by 1;

else

{

Session["IDClm"] = Convert.ToInt16(Session["IDClm"]) + 1;

d = (DataTable)Session["dt"];

}

//Assign both fields with data

int ID = Convert.ToInt16(Session["IDClm"]);

string name = TextBox1.Text;

//call AddNew method and pass id,name and object of datatable

Dt.AddRow(ID, name, d);

//Again bind it with gridview

GridView1.DataSource = d;

GridView1.DataBind();

//finally assign to session also.

Session["dt"] = d;

}

When ever user want to delete record from Data Table then ask for confirmation that Are you sure? Some thing like this. This code I impletment in RowDataBound Event of the gridView1 as follow

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

{

if (e.Row.RowType == DataControlRowType.DataRow)

{

//We are checking if new row is adding then bind javascript function to ask confirmation from user for deletion record.

LinkButton l = (LinkButton)e.Row.FindControl("LinkButton1");

l.Attributes.Add("onclick", "javascript:return " +

"confirm('Are you sure you want to delete this Name " +

DataBinder.Eval(e.Row.DataItem, "id") + "')");

}

}

//This code for delete the record in RowCommand event

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)

{

if (e.CommandName == "Delete")

{

//We are deleteing records from datatable

int ID = Convert.ToInt32(e.CommandArgument);

DataTable updt = (DataTable)Session["dt"];

int i = 0;

while (i <>

{

if (Convert.ToInt16(updt.Rows[i]["ID"]) == ID)

updt.Rows[i].Delete();

i++;

}

//After delete data from datatable accept the changes and then bind it to gridview again

updt.AcceptChanges();

GridView1.DataSource = updt;

GridView1.DataBind();

//And finally update the session with modified datatable;

Session["dt"] = updt;

}

}

//This code block for handling the RowDeleteing event there is no lines of code inside this event but still it’s necessary otherwise it will generate error.

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e){}

Template by - Abdul Munir | Daya Earth Blogger Template