Share Blog

Thursday, August 07, 2014

Custom Validator For Email And Mobile Number in Asp.net

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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 runat="server">
    <title></title> 
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <table>
           <tr>
           <td >
          Email</td>
                <td>
                    <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
                    <asp:CustomValidator ID="CustomValidator1" runat="server"
                        ControlToValidate="TextBox3" ErrorMessage="Enter Valid Email" Font-Bold="True"
                        ForeColor="Red" onservervalidate="Validate_Email"></asp:CustomValidator>
                </td>
            </tr>
            <tr>
                <td>
                    Mobile</td>
                <td>
                    <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
                    <asp:CustomValidator ID="CustomValidator2" runat="server"
                        ControlToValidate="TextBox4" Display="Dynamic"
                        ErrorMessage="Enter Valid mobile " ForeColor="Red"
                        onservervalidate="Validate_Mobile"></asp:CustomValidator>
                </td>
            </tr>
            <tr>
                  <td >
                    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Save" />
                </td>
                <td></td>
            </tr>
        </table>
        </div>
    </form>
</body>

</html>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {


    }
  
    protected void Validate_Email(object source, ServerValidateEventArgs e)
    {
        //System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("^[0-9]+$");
        System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
        e.IsValid = r.IsMatch(TextBox3.Text);
    }
    protected void Validate_Mobile(object source, ServerValidateEventArgs e)
    {
        System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(@"^[987]+\d{9}$");
        e.IsValid = r.IsMatch(TextBox4.Text);
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
       
    }
}


Wednesday, August 06, 2014

How To Generate Random Password in Asp.net And C#

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

public partial class Auto_Generate_password : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    
    }
    public static string NewRandomPassword(int PasswordLength)
    {
        string _allowedChars = "0123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ";
        Random randNum = new Random();
        char[] chars = new char[PasswordLength];
        int allowedCharCount = _allowedChars.Length;
        for (int i = 0; i < PasswordLength; i++)
        {
            chars[i] = _allowedChars[(int)((_allowedChars.Length) * randNum.NextDouble())];
        }
        return new string(chars);
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Label1.Text = NewRandomPassword(10);
    }
}


Monday, August 04, 2014

How To Create your own captcha image generator in asp.net using c#.net


The below example will generate a captcha code with numbers and alphabets (small and capital letters). You can change the variable  “combination” value according to your requirement. 

Create two pages Captcha_image.aspx and Registration.aspx

Captcha_image.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Captcha_image.aspx.cs" Inherits="Captcha_image" %>

<!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 runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div></div>
    </form>
</body>
</html>


Captcha_image.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Data.SqlClient;
using System.Text;

public partial class Captcha_image : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["captcha"]!= null)
        {
            int height = 30;
            int width = 100;
            Bitmap bmp = new Bitmap(width, height);
            RectangleF rectf = new RectangleF(10, 5, 0, 0);
            Graphics g = Graphics.FromImage(bmp);
            g.Clear(Color.White);
            g.SmoothingMode = SmoothingMode.AntiAlias;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
            g.DrawString(Session["captcha"].ToString(), new Font("Thaoma", 12, FontStyle.Italic), Brushes.Green, rectf);
            g.DrawRectangle(new Pen(Color.Red), 1, 1, width - 2, height - 2);
            g.Flush();
            Response.ContentType = "image/jpeg";
            bmp.Save(Response.OutputStream, ImageFormat.Jpeg);
            g.Dispose();
            bmp.Dispose();
        }
    }
  
}

Registration.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Registration.aspx.cs" Inherits="Registration" %>

<!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 runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="SM1" runat="server">
        </asp:ScriptManager>
        <table style="border: solid 1px black; padding: 20px; position: relative; top: 50px;"
            align="center">
            <tr>
                <td>
                    Email ID :
                </td>
                <td>
                    <asp:TextBox ID="txtEmailID" runat="server" Width="200px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Password :
                </td>
                <td>
                    <asp:TextBox ID="txtPassword" runat="server" TextMode="Password" Width="200px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Confirm Password :
                </td>
                <td>
                    <asp:TextBox ID="txtConfirmPassword" runat="server" TextMode="Password" Width="200px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Enter Below Code :
                </td>
                <td>
                    <asp:TextBox ID="txtCaptcha" runat="server" Width="200px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                </td>
                <td valign="middle">
                    <asp:UpdatePanel ID="UP1" runat="server">
                        <ContentTemplate>
                            <table>
                                <tr>
                                    <td style="height: 50px; width:100px;">
                                        <asp:Image ID="imgCaptcha" runat="server" />
                                    </td>
                                    <td valign="middle">
                                        <asp:Button ID="btnRefresh" runat="server" Text="Refresh" OnClick="btnRefresh_Click" />
                                    </td>
                                </tr>
                            </table>
                        </ContentTemplate>
                    </asp:UpdatePanel>
                </td>
            </tr>
            <tr>
                <td colspan="2" align="center">
                    <asp:Button ID="btnRegiser" runat="server" Text="Register" OnClick="btnRegister_Click" />
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

Registration.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Data.SqlClient;
using System.Text;

public partial class Registration : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            FillCapctha();
        }
    }
    void FillCapctha()
    {
        try
        {
            Random random = new Random();
            string combination = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
            StringBuilder captcha = new StringBuilder();
            for (int i = 0; i < 6; i++)
                captcha.Append(combination[random.Next(combination.Length)]);
            Session["captcha"] = captcha.ToString();
            imgCaptcha.ImageUrl = "Captcha_image.aspx?" + DateTime.Now.Ticks.ToString();
        }
        catch
        {

            throw;
        }
    }
    protected void btnRegister_Click(object sender, EventArgs e)
    {
        if (Session["captcha"].ToString() != txtCaptcha.Text)
            Response.Write("Invalid Captcha Code");
        else
            Response.Write("Valid Captcha Code");
        FillCapctha();
    }
    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        FillCapctha();
    }

}

RESULT

Export GridView Data to Excel, Word, Pdf, Text and Csv Format and Print Using in Asp.Net

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<!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></title>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <link href="Styles/nivo-slider.css" rel="stylesheet" type="text/css" />
    <link href="Styles/Default.css" rel="stylesheet" type="text/css" />
    <link href="Styles/nivo-slider.css" rel="stylesheet" type="text/css" />
    <script src="Scripts/Demo.js" type="text/javascript"></script>
    <script type="text/javascript">
        function PrintGridData() {
            var prtGrid = document.getElementById('<%=gvDetails.ClientID %>');
            var prtwin = window.open('', 'PrintGridView',
'left=100,top=100,width=400,height=400,tollbar=0,scrollbars=1,status=0,resizable=1');
            prtwin.document.write(prtGrid.outerHTML);
            prtwin.document.close();
            prtwin.focus();
            prtwin.print();
            prtwin.close();
        }
   </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td colspan="3" align="center">
                    <asp:GridView ID="gvDetails" runat="server" AutoGenerateColumns="false">
                        <Columns>
                            <asp:BoundField DataField="CustomerID" HeaderText="Employee Id" />
                            <asp:BoundField DataField="Name" HeaderText="Last Name" />
                            <asp:BoundField DataField="company" HeaderText="Company" />
                        </Columns>
                    </asp:GridView>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="btnExel" runat="server" Text="Export to Exel" OnClick="btnExel_Click" />
                </td>
                <td>
                    <asp:Button ID="btnWord" runat="server" Text="Export to Word" OnClick="btnWord_Click" />
                </td>
                <td>
                    <asp:Button ID="btnPdf" runat="server" Text="Export to Pdf" OnClick="btnPdf_Click" />
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="btnCsv" runat="server" Text="Export to Csv" OnClick="btnCsv_Click" />
                </td>
                <td>
                    <asp:Button ID="btnText" runat="server" Text="Export to Text" OnClick="btnText_Click" />
                </td>
                <td>
                    <asp:Button ID="btnPrint" runat="server" Text="Print"
                        OnClientClick="PrintGridData();" onclick="btnPrint_Click" />
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

</html>




using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;


public partial class Default3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Bind();
        }
    }
    public void Bind()
    {
        SqlConnection con = new SqlConnection("Data Source=SERVER02\\sqlserver;Initial Catalog=EMPLOYEE;User ID=***;Password=********");

        SqlDataAdapter da = new SqlDataAdapter("select *  from customers", con);
        DataSet ds = new DataSet();
        da.Fill(ds);
        gvDetails.DataSource = ds;
        gvDetails.DataBind();

    }
    protected void btnExel_Click(object sender, EventArgs e)
    {
        Bind();
        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Documents.xls"));
        Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter ht = new HtmlTextWriter(sw);
        gvDetails.RenderControl(ht);
        Response.Write(sw.ToString());
        Response.End();
    }
    protected void btnWord_Click(object sender, EventArgs e)
    {
        Bind();
        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Documents.doc"));
        Response.ContentType = "application/ms-word";
        StringWriter sw = new StringWriter();
        HtmlTextWriter ht = new HtmlTextWriter(sw);
        gvDetails.RenderControl(ht);
        Response.Write(sw.ToString());
        Response.End();
    }
    protected void btnPdf_Click(object sender, EventArgs e)
    {
        Bind();
        Response.ContentType = "Sunil/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=Documents.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        gvDetails.RenderControl(hw);
        StringReader sr = new StringReader(sw.ToString());
        Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
        PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        pdfDoc.Open();
        htmlparser.Parse(sr);
        pdfDoc.Close();
        Response.Write(pdfDoc);
        Response.End();
    }
    protected void btnText_Click(object sender, EventArgs e)
    {
        Bind();
        Response.ClearContent();
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Documents.txt"));
        Response.ContentType = "application/text";
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < gvDetails.Columns.Count; i++)
        {
            str.Append(gvDetails.Columns[i].HeaderText + ',');
        }
        str.Append("\n");
        for (int j = 0; j < gvDetails.Rows.Count; j++)
        {
            for (int k = 0; k < gvDetails.Columns.Count; k++)
            {
                str.Append(gvDetails.Rows[j].Cells[k].Text + ',');
            }
            str.Append("\n");
        }
        Response.Write(str.ToString());
        Response.End();
    }
    protected void btnPrint_Click(object sender, EventArgs e)
    {
        Bind();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
    }
    protected void btnCsv_Click(object sender, EventArgs e)
    {
        Bind();
        Response.ClearContent();
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Documents.txt"));
        Response.ContentType = "application/text";
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < gvDetails.Columns.Count; i++)
        {
            str.Append(gvDetails.Columns[i].HeaderText + ',');
        }
        str.Append("\n");
        for (int j = 0; j < gvDetails.Rows.Count; j++)
        {
            for (int k = 0; k < gvDetails.Columns.Count; k++)
            {
                str.Append(gvDetails.Rows[j].Cells[k].Text + ',');
            }
            str.Append("\n");
        }
        Response.Write(str.ToString());
        Response.End();
    }
}