3 Jun 2014

Minimum and Maximum character length Validation (Minimum 10 and Maximum 15 characters required) in asp.net and js

Minimum and Maximum character length Validation (Minimum 10 and Maximum 15 characters required)
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator Display = "Dynamic" ControlToValidate = "TextBox3" ID="RegularExpressionValidator3" ValidationExpression = "^[\s\S]{10,15}$" runat="server" ErrorMessage="Minimum 5 and Maximum 8 characters required."></asp:RegularExpressionValidator>
======================================================
<table cellpadding="0" cellspacing="0" align="center" width="600">
            <tr>
                <td height="30" colspan="2">
                    <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
                </td>
            </tr>
            <tr>
                <td height="30" colspan="2">
                    <b>Resume Upload Retrieve Example</b>
                </td>
            </tr>
            <tr>
                <td height="30">
                    Select Your Resume
                </td>
                <td>
                    <asp:FileUpload ID="FileUpload1" runat="server" />
                </td>
            </tr>
            <tr>
                <td height="30" colspan="2" align="center">
                    <asp:Button ID="Button1" runat="server" Text="Upload" onclick="Button1_Click" />
                </td>
            </tr>
            <tr>
                <td height="30" colspan="2" align="center">
                    <asp:GridView ID="GridView1" runat="server" DataKeyNames="ID" AutoGenerateColumns="false">
                        <Columns>
                            <asp:TemplateField HeaderText="ID">
                                <ItemTemplate>
                                    <%#Eval("ID")%>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Resume File Name">
                                <ItemTemplate>
                                    <asp:HyperLink Target="_blank" ID="HyperLink1" runat="server" NavigateUrl=' <%# "~/Default2.aspx?ID=" + Eval("ID", "{0:d}")%> '><%#Eval("RNAME")%></asp:HyperLink>                                   
                                </ItemTemplate>
                            </asp:TemplateField>
                        </Columns>
                    </asp:GridView>
                </td>
            </tr>

        </table>

======================================================
public partial class Default2 : System.Web.UI.Page
{
  
    SqlCommand sqlcmd = new SqlCommand();
    SqlDataAdapter da = new SqlDataAdapter();
    DataTable dt = new DataTable();
    string qstr;
    byte[] b = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            qstr = Request.QueryString["ID"];
            //Read Resume file from DATABASE table rcontent field
            SqlCommand sqlcmd = new SqlCommand("Select RCONTENT from Rupload where ID='" + qstr + "'", sqlcon); //use condition to retrieve particulatr REsume
            sqlcon.Open();
            da = new SqlDataAdapter(sqlcmd);
            da.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                b = ((byte[])dt.Rows[0][0]);
                //Collect Bytes from database and write in Webpage
                Response.ContentType = "application/msword";
                Response.BinaryWrite(b);
            }
        }
    }
    protected void btnProcess_Click(object sender, EventArgs e)
    {
        string str = string.Empty;
        string strname = string.Empty;
        foreach (GridViewRow gvrow in gvDetails.Rows)
        {
            CheckBox chk = (CheckBox)gvrow.FindControl("chkSelect");
            if (chk != null & chk.Checked)
            {
                str += gvDetails.DataKeys[gvrow.RowIndex].Value.ToString() + ',';
                strname += gvrow.Cells[2].Text + ',';
            }
        }
        str = str.Trim(",".ToCharArray());
        strname = strname.Trim(",".ToCharArray());
        lblmsg.Text = "Selected UserIds: <b>" + str + "</b><br/>" + "Selected UserNames: <b>" + strname + "</b>";
    }
    protected void GetSelectedRecords(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Name"), new DataColumn("Country") });
        foreach (GridViewRow row in GridView1.Rows)
        {
            if (row.RowType == DataControlRowType.DataRow)
            {
                CheckBox chkRow = (row.Cells[0].FindControl("chkRow") as CheckBox);
                if (chkRow.Checked)
                {
                    string name = row.Cells[1].Text;
                    string country = (row.Cells[2].FindControl("lblCountry") as Label).Text;
                    dt.Rows.Add(name, country);
                }
            }
        }
        gvSelected.DataSource = dt;
        gvSelected.DataBind();
    }
    foreach(GridViewRow  gvrow in gvDetails.Rows)
{
CheckBox chk = (CheckBox)gvrow.FindControl("chkSelect");
if (chk != null & chk.Checked)
{
str += gvDetails.DataKeys[gvrow.RowIndex].Value.ToString() + ',';
strname += gvrow.Cells[2].Text+',';

}
=========================================================

 SqlConnection sqlcon = new SqlConnection();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            LoadGrid();
        }
        Label1.Text = "";
    }
    void LoadGrid()
    {
        sqlcon.Open();
        SqlCommand sqlcmd;
        SqlDataAdapter da;
        DataTable dt = new DataTable();
        
        sqlcmd = new SqlCommand("select * from RUPLOAD", sqlcon);
        da = new SqlDataAdapter(sqlcmd);
        da.Fill(dt);
        if (dt.Rows.Count > 0)
        {
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
        sqlcon.Close();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            Stream fs = default(Stream);
            fs = FileUpload1.PostedFile.InputStream;
            BinaryReader br1 = new BinaryReader(fs);
            byte[] rbytes = br1.ReadBytes(FileUpload1.PostedFile.ContentLength);
            sqlcon.Open();
            SqlCommand sqlcmd = new SqlCommand("insert into RUPLOAD(RNAME,RCONTENT) values (@rname,@rcon)", sqlcon);
            sqlcmd.Parameters.Add("@rname", FileUpload1.FileName);
            sqlcmd.Parameters.Add("@rcon", rbytes);
            sqlcmd.ExecuteNonQuery();
            sqlcon.Close();
            Label1.Text = "Successfully resume upload to SQL Server database.";
            LoadGrid();
        }      

    }
====================================================================



19 Feb 2014

Signature capture from signature pad in Web Application asp.net using c# (or) web signature capture asp net using mouse asp.net

In this post I Explained about capture the signature from signature pad to connect the Web application.  You have to use web signuature pad for this application.


.aspx code

<form id="form1" runat="server">
        <asp:HiddenField ID="HiddenField1" runat="server" />
        <div id="wPaint" style="position:relative; width:1200px; height:500px; background:#ACACAC; border:solid black 1px; overflow:hidden;"></div>
        <asp:Button ID="BtnSign" runat="server" Text="Save" CssClass="button" OnClientClick="javascript:saveImage();" onclick="BtnSign_Click" />
        <asp:Button ID="BtnClearSign" runat="server" Text="Clear" CssClass="button" OnClientClick="javascript:loadImage();" />
       
        <script type="text/javascript">
                $("#wPaint").wPaint({
                      image: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAECAQGDHihRBAIECBAgYND9AAECBAgQCAgY9ECJIhAgQIAAAYPuBwgQIECAQEDAoAdKFIEAAQIECBh0P0CAAAECBAICBj1QoggECBAgQMCg+wECBAgQIBAQMOiBEkUgQIAAAQIG3Q8QIECAAIGAgEEPlCgCAQIECBAw6H6AAAECBAgEBAx6oEQRCBAgQICAQfcDBAgQIEAgIGDQAyWKQIAAAQIEDLofIECAAAECAQGDHihRBAIECBAgYND9AAECBAgQCAgY9ECJIhAgQIAAgQMI/gEtiL4PDAAAAABJRU5ErkJggg==",
                      drawDown: function(e, element){ $("#canvasDown").val(element.settings.mode +": " + e.pageX + ',' + e.pageY); },
                      drawMove: function(e, element){ $("#canvasMove").val(element.settings.mode +": " + e.pageX + ',' + e.pageY); },
                      drawUp: function(e, element){ $("#canvasUp").val(element.settings.mode +": " + e.pageX + ',' + e.pageY); }
                });
                function loadImage()
                {
                      $("#wPaint").wPaint("image", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAfQCBj1QoggECBAgQMCg+wECBAgQIBAQMOiBEkUgQIAAAQIG3Q8QIECAAIGAgEEPlCgCAQIECBAw6H6AAAECBAgEBAx6oEQRCBAgQICAQfcDBAgQIEAgIGDQAyWKQIAAAQIEDLofIECAAAECAQGDHihRBAIECBAgYND9AAECBAgQCAgY9ECJIhAgQIAAgQMI/gEtiL4PDAAAAABJRU5ErkJggg==");
                }
                function saveImage()
                {
                      var imageSignData = $("#wPaint").wPaint("image");
                    document.getElementById('<%= HiddenField1.ClientID %>').value = imageSignData;
                }
          </script>                                
    </form>

.cs page code

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using System.IO;
using System.Drawing;
using System.Diagnostics;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Drawing.Imaging;

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

        }

        protected void BtnSign_Click(object sender, EventArgs e)
        {
            try
            {
                string PATH = Server.MapPath(ResolveUrl("~\\"));
                string strPhoto = HiddenField1.Value; //Get the image from flash file
                int l = strPhoto.Length;
                strPhoto = strPhoto.Substring(22, l - 22);
                byte[] photo = Convert.FromBase64String(strPhoto);
                FileStream fs = new FileStream(PATH + "Sign.png", FileMode.OpenOrCreate, FileAccess.Write);
                BinaryWriter br = new BinaryWriter(fs);
                br.Write(photo);
                br.Flush();
                br.Close();
                fs.Close();

                string script2 = "alert('Signature Saved..');";
                System.Web.HttpContext.Current.Response.Write("<script language=\"javascript\">" + script2 + "</script>");

                InvertImage();
            }
            catch (Exception Ex)
            {
                string script3 = "alert('" + Ex + "');";
                System.Web.HttpContext.Current.Response.Write("<script language=\"javascript\">" + script3 + "</script>");
            }
        }

        protected void InvertImage()
        {
            Bitmap bimg = (Bitmap)System.Drawing.Image.FromFile(Server.MapPath("~\\Sign.png"));
            Bitmap img = null;
            img = new Bitmap(bimg.Width, bimg.Height);
            for (int x = 0; x < bimg.Width; x++)
            {
                for (int y = 0; y < bimg.Height; y++)
                {
                    //Get the color
                    Color clr = bimg.GetPixel(x, y);
                    //Invert the clr
                    clr = Color.FromArgb(255 - clr.R, 255 - clr.G, 255 - clr.B);
                    //Update the color
                    img.SetPixel(x, y, clr);
                }
            }
            bimg.Dispose();
            img.Save(Server.MapPath("~\\Signature.jpg"), System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }
}


print gridview data in asp.net using c# (or) export gridview to word/excel/pdf/csv in asp.net

In this post I Explained about exporting gridview data to the word or excel format. You can down load the complete grid view data on clicking the image button in the figure.




.Aspx Code :

  <form id="form1" runat="server">
    <div>&nbsp&nbsp&nbsp&nbsp
        <asp:ImageButton ID="ImgBtnBack" runat="server" ImageUrl="~/images/back.png" OnClick="ImgBtnBack_Click" />
        <asp:ImageButton ID="ImgBtnPrint" runat="server" ImageUrl="~/images/print01.png" /> &nbsp&nbsp&nbsp&nbsp
        <asp:ImageButton ID="ImgBtnWord" runat="server" ImageUrl="~/images/Word01.png" OnClick="ImgBtnWord_Click" /> &nbsp&nbsp&nbsp&nbsp
        <asp:ImageButton ID="ImgBtnExcel" runat="server" ImageUrl="~/images/Excel01.png" OnClick="ImgBtnExcel_Click" />
    </div>
    <div id="VQGridView">
        <asp:GridView ID="GridViewResult" runat="server" HorizontalAlign="Center"
            GridLines="None" Width="200%"
            CssClass="pnl-div" EmptyDataText="No Records Avaialable.."  >
            <FooterStyle BackColor="" Font-Bold="true" ForeColor="" />
            <RowStyle BackColor="#FFFFFF" HorizontalAlign="Left" />
            <EditRowStyle BackColor="" Width="100%" />
            <SelectedRowStyle BackColor="" Font-Bold="true" ForeColor="" />
            <PagerStyle BackColor="" ForeColor="" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#17C5F7" ForeColor="#FFFFFF" Font-Bold="true" HorizontalAlign="Left" />
            <AlternatingRowStyle BackColor="#B6EEFF" />
        </asp:GridView>
    </div>
    </form>

.CS Page code :

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

namespace company
{
    public partial class QueryResult : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string UNAME = Convert.ToString(Session["USER_NAME"]);

            string printScript =
            @"function PrintGridView()
            {
            var gridInsideDiv = document.getElementById('VQGridView');
            var printWindow = window.open('VQGridView.htm','PrintWindow','letf=0,top=0,width=1000,height=700,toolbar=1,scrollbars=1,status=1');
            printWindow.document.write(gridInsideDiv.innerHTML);
            printWindow.document.close();
            printWindow.focus();
            printWindow.print();
            printWindow.close();}";
            this.ClientScript.RegisterStartupScript(Page.GetType(), "PrintGridView", printScript.ToString(), true);
            ImgBtnPrint.Attributes.Add("onclick", "PrintGridView();");

           
            SqlConnection cn = new SqlConnection();
            cn.ConnectionString = ConfigurationManager.ConnectionStrings["connecton string here"].ConnectionString;
            cn.Open();
            string QUERY = " Your Sql Query";
            DataTable dt = new DataTable();
            SqlDataAdapter adp = new SqlDataAdapter(QUERY, cn);
            adp.Fill(dt);
            GridViewResult.DataSource = dt;
            GridViewResult.DataBind();
            cn.Close();
        }

        public override void VerifyRenderingInServerForm(Control control)
        {
            /* Verifies that the control is rendered */
        }

        protected void ImgBtnWord_Click(object sender, ImageClickEventArgs e)
        {
            GridViewResult.AllowPaging = false;
            GridViewResult.DataBind();
            Response.ClearContent();
            Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Visitors.doc"));
            Response.Charset = "";
            Response.ContentType = "application/ms-word";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            GridViewResult.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();
        }

        protected void ImgBtnExcel_Click(object sender, ImageClickEventArgs e)
        {
            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Visitors.xls"));
            Response.ContentType = "application/ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            GridViewResult.AllowPaging = false;
            GridViewResult.DataBind();
            //Change the Header Row back to white color
            GridViewResult.HeaderRow.Style.Add("background-color", "#FFFFFF");
            //Applying stlye to gridview header cells
            for (int i = 0; i < GridViewResult.HeaderRow.Cells.Count; i++)
            {
                GridViewResult.HeaderRow.Cells[i].Style.Add("background-color", "#507CD1");
            }
            int j = 1;
            //This loop is used to apply stlye to cells based on particular row
            foreach (GridViewRow gvrow in GridViewResult.Rows)
            {
                //gvrow.BackColor = Color.White;
                if (j <= GridViewResult.Rows.Count)
                {
                    if (j % 2 != 0)
                    {
                        for (int k = 0; k < gvrow.Cells.Count; k++)
                        {
                            gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
                        }
                    }
                }
                j++;
            }
            GridViewResult.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();
        }

        protected void ImgBtnBack_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("back.aspx");
        }
    }

}