Popular Posts

Sunday, 20 July 2014

simple captcha in asp.net

SIMPLE OWNED CAPTCHA TO FOREPLAY BOTS...........



Here is the code for adding a simple captcha in your aspx code rather than using any third party.
use ur imagination and create your own.


THE ASPX PAGE:


<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
   
    <p>
        CAPTCHA :</p>
    <p>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> + <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label> =
        <asp:TextBox ID="TextBox1" runat="server" Width="40px"></asp:TextBox>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    </p>
   
</asp:Content>




Here we have added two lables and one text box to display the number (random ) and to get the result from the user respectively..


THE CODE BEHIND PAGE:


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

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Random _r = new Random();
            int n = _r.Next(10);
            Label1.Text = "0";
            Label2.Text = n.ToString();
        }

    }
    protected void Button1_Click(object sender, EventArgs e)
    {

        int result = Convert.ToInt32(TextBox1.Text            );
        int cal=Convert.ToInt32(Label1.Text)+Convert.ToInt32(Label2.Text);
        if (result.Equals(cal))
        {
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "errmsg", "alert('CORRECT CAPTCHA LOGIN SUCCESSFULL!!')", true);

        }
        else
        {

            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "errmsg", "alert('INCORRECT TRY AGAIN')", true);

        }

    }
}


AND ITS DONE ..





Friday, 11 July 2014

HOW TO UPDATE LARGE TABLES IN FASTEST WAY....... IN SQL SERVER

FASTEST WAY TO UPDATE ROWS IN A LARGE TABLES IN SQL SERVER




The key concept here will be to improve the performance of an update operation by updating the tables in smallest manner.

For E.G:

consider a table called test with contains more than 5 millions records rows. Let us also assume what we need to update,,,say there are over 3  millions rows in that column that has a negative number so we need to update all the rows (i.e upto 3 millions) containing the negative numbers to positive numbers .


NOW normal query will be(not recommended):

update test set columnname=0 where columnanme<0;


THAT IS ROWCOUNT TO RESCUE>>>>>>>>>>>>>>>>>>>


set rowcount 10000

update test set columnname=0 where columnanme<0;

while @@rowcount>0

BEGIN
set rowcount 10000

update test set columnname=0 where columnanme<0;



//
I.E
it will updates 10000 row at a time and then loop continues till @@rowcount>0.
this will ensure that table will not locked and updation is done smoothly in less time.

DELETE DUPLICATE DATA FROM SQL SERVER CONTAINING NO PRIMARY /PRIMARY KEY.

HOW TO DELETE DUPLICATE VALUES FROM SQL TABLE


Their are severals ways this can be achieved .below are the discussed two ways:


Table structure:
username varchar2
password varchar2


--using CTE COMMON TABLE EXPRESSION and row_number function


WITH CTE AS(
   SELECT username, Password,
       RN = ROW_NUMBER()OVER(PARTITION BY username ORDER BY username)
   FROM dbo.users
)
DELETE FROM CTE WHERE RN > 1







--using auto id column


ALTER TABLE dbo.users ADD AUTOID INT IDENTITY(1,1)

select username,count(username) as counts from users group by username
having count(username)>1


delete from users where AUTOID  not in (select min(AUTOID) from users group by username)


Thus simply done..

Wednesday, 26 February 2014

UPLOAD AND DOWNLOAD MULTIPLE FILES WITH SIMPLE JAVASCRIPT

UPLOAD AND DOWNLOAD MULTIPLE FILES WITH SIMPLE JAVASCRIPT


DESIGN PAGE:


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

<!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>
    <style type="text/css">
    .fileUpload{
    width:255px;    
    font-size:11px;
    color:#000000;
    border:solid;
    border-width:1px;
    border-color:#7f9db9;    
    height:17px;
    }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <div id="fileUploadarea"><asp:FileUpload ID="fuPuzzleImage" runat="server" CssClass="fileUpload" /><br /></div><br />
    <div><input style="display:block;" id="btnAddMoreFiles" type="button" value="Add more images" onclick="AddMoreImages();" /><br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Upload" />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:Button ID="Button2" runat="server" Text="SHOW FILES" 
            onclick="Button2_Click" />
        &nbsp;&nbsp;&nbsp;&nbsp;
        <br />
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label>

        </div>
        <div id="download" runat="server">
        
      <p>  ALL AVAILABEL FILES :<br /></p>
      <br />
        
        </div>
    </div>
    <script language="javascript" type="text/javascript">
        function AddMoreImages() {
            if (!document.getElementById && !document.createElement)
                return false;
            var fileUploadarea = document.getElementById("fileUploadarea");
            if (!fileUploadarea)
                return false;
            var newLine = document.createElement("br");
            fileUploadarea.appendChild(newLine);
            var newFile = document.createElement("input");
            newFile.type = "file";
            newFile.setAttribute("class", "fileUpload");

            if (!AddMoreImages.lastAssignedId)
                AddMoreImages.lastAssignedId = 100;
            newFile.setAttribute("id", "FileUpload" + AddMoreImages.lastAssignedId);
            newFile.setAttribute("name", "FileUpload" + AddMoreImages.lastAssignedId);
            var div = document.createElement("div");
            div.appendChild(newFile);
            div.setAttribute("id", "div" + AddMoreImages.lastAssignedId);
            fileUploadarea.appendChild(div);
            AddMoreImages.lastAssignedId++;
        }
   
    </script>
    </form>
</body>
</html>




Here we are adding asp control upload dynamically (up to max 6 optionally) on btnAddMoreFiles button click and call the java script  function AddMoreImages .

Button2 Is used to list all the files been upoaded successfully . 



CODE BEHIND PAGE:

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.Collections;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using System.Threading;

public partial class Test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       
       }
  protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            Label1.Text = "";
            HttpFileCollection hfc = Request.Files;
            
                for (int i = 0; i < hfc.Count; i++)
                {
                    HttpPostedFile hpf = hfc[i];
                    string type = hpf.FileName.Split(".".ToCharArray())[1].ToString();
                    if (type == "doc" || type == "docx" || type == "DOC" || type == "DOCX")
                    {
                        if (hpf.ContentLength > 0 && hpf.ContentLength < 5242880)
                        {
                            hpf.SaveAs(Server.MapPath("~/uploads/") + System.IO.Path.GetFileName(hpf.FileName));
                            Label1.Text += "<br/>file "+ hpf.FileName+" uploaded successfully...<br/>";

                        }
                        else
                        {

                            Label1.Text += "FILE of size more than 5 mb ("+hpf.FileName+") are not allowed<br />";
                        }
                    }
                    else
                    {

                        Label1.Text += "only docs file are allowed"+hpf.FileName+" NOT UPLOADED";
      
                    
                    }
                   
                }
           
               
        }
        catch (Exception)
        {
            
            throw;
        } 
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/uploads"));
        int i = 0;
        foreach (FileInfo fi in di.GetFiles())
        {
            HyperLink HL = new HyperLink();
            HL.ID = "HyperLink" + i++;
            HL.Text = fi.Name;
            HL.NavigateUrl = "Download.aspx?file=" + fi.Name;
            download.Controls.Add(HL);
            download.Controls.Add(new LiteralControl("<br/>"));
        }
    }
    }



HERE I have made a restriction that only doc files will be uploaded and of size less than 5 mb.
it depends upon you what are the conditions.
 
On button2_Click the files been uploaded are shown in hyperlink and on clicking the hyper link the file are been downloaded.


BELOW IS THE CODE FOR DOWNLOAD FILE:


using System.IO;
using System.Threading;

public partial class Download : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string filename = Request["file"].ToString();
        fileDownload(filename, Server.MapPath("~/uploads/" + filename));
    }
    private void fileDownload(string fileName, string fileUrl)
    {
        Page.Response.Clear();
        bool success = ResponseFile(Page.Request, Page.Response, fileName, fileUrl, 1024000);
        if (!success)
            Response.Write("Downloading Error!");
        Page.Response.End();

    }
    public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
    {
        try
        {
            FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            BinaryReader br = new BinaryReader(myFile);
            try
            {
                _Response.AddHeader("Accept-Ranges", "bytes");
                _Response.Buffer = false;
                long fileLength = myFile.Length;
                long startBytes = 0;

                int pack = 10240; //10K bytes
                int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1;
                if (_Request.Headers["Range"] != null)
                {
                    _Response.StatusCode = 206;
                    string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
                    startBytes = Convert.ToInt64(range[1]);
                }
                _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                if (startBytes != 0)
                {
                    _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
                }
                _Response.AddHeader("Connection", "Keep-Alive");
                _Response.ContentType = "application/octet-stream";
                _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));

                br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;

                for (int i = 0; i < maxCount; i++)
                {
                    if (_Response.IsClientConnected)
                    {
                        _Response.BinaryWrite(br.ReadBytes(pack));
                        Thread.Sleep(sleep);
                    }
                    else
                    {
                        i = maxCount;
                    }
                }
            }
            catch
            {
                return false;
            }
            finally
            {
                br.Close();
                myFile.Close();
            }
        }
        catch
        {
            return false;
        }
        return true;
    }








Saturday, 11 January 2014

PayPal Gateway Integration in ASP.NET

PayPal Gateway Integration in ASP.NET


Introduction

If you are developing an ASP.NET web application and you require some payment gateway integration, then here is a simplified option to integrate PayPal with your application.

Description

In this article I will explain thoroughly all the requirements and techniques for integrating PayPal in your web application.
Nowadays PayPal is the most popular payment gateway worldwide because it is totally free to integrate and PayPal does not charge anything for opening an account, you will pay PayPal when you get paid. And the amount is also lower than other payment gateways. 



THE DESIGN PAGE :

This is the test page ...you can create as per your requirement.

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

<!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>PAYPAL INTEGRATION IN ASP.NET Page</title>
</head>
<body>
    <form id="form1" runat="server">
   <div style="color: #324143; margin: 30px 0 0 60px; font-family: Arial;">
    <span style="font-size: small;">Your Name:</span>
    <asp:TextBox runat="server" ValidationGroup="save" ID="txtName" Style="margin-left: 30px; width: 200px;
        background-image: url('../images/txtBoxbg.jpg') no-repeat;"></asp:TextBox>
    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" ControlToValidate="txtPurpose"
        ErrorMessage="Please enter your Name" runat="server" 
        ValidationGroup="save" ForeColor="red"></asp:RequiredFieldValidator>
    <br />
    <br />
    <span style="font-size: small;">Your Email Id:</span><asp:TextBox runat="server" ValidationGroup="save"
        Style="margin-left: 20px;width: 200px; background-image: url('../images/txtBoxbg.jpg') no-repeat;"
        ID="txtEmailId"></asp:TextBox>
    <asp:RegularExpressionValidator ID="regexEmailValid" runat="server" 
        ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
        ControlToValidate="txtEmailId" ValidationGroup="save" 
        ErrorMessage="Invalid Email Format" 
        ForeColor="red"></asp:RegularExpressionValidator><br />
    <br />
    <span style="font-size: small;">Your Phone No:</span>
    <asp:TextBox runat="server" ID="txtPhone" ValidationGroup="save" Style="margin-left: 6px;
        width: 200px; background-image: transparent url('../images/txtBoxbg.jpg') no-repeat;"></asp:TextBox>
    <asp:RegularExpressionValidator ID="RegularExpressionValidator4" runat="server" ControlToValidate="txtPhone"
        ForeColor="red" ErrorMessage="Invalid Phone No"
        ValidationGroup="save" ValidationExpression="^([0-9\(\)\/\+ \-]*)$"></asp:RegularExpressionValidator>
    <br />
    <br />
    <span style="font-size: small;">Enter Amount:</span><asp:TextBox runat="server" ID="txtAmount" ValidationGroup="save"
        Style="margin-left: 16px; width: 200px; background-image: url('../images/txtBoxbg.jpg') no-repeat;"></asp:TextBox>
    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="txtAmount"
        runat="server" ForeColor="red" ErrorMessage="Please enter the amount."></asp:RequiredFieldValidator>
    <br />
    <br />
    <span style="font-size: small;">Currency:</span>
    <asp:DropDownList runat="server" ID="ddlCurrency" Style="margin-left: 42px; 
        width: 204px; background-image: transparent url('../images/txtBoxbg.jpg') no-repeat;">
        <asp:ListItem>- Select -</asp:ListItem>
        <asp:ListItem>INR</asp:ListItem>
        <asp:ListItem>USD</asp:ListItem>
        <asp:ListItem>EURO</asp:ListItem>
        <asp:ListItem>Pound</asp:ListItem>
    </asp:DropDownList>
    <br />
    <br />
    <span style="font-size: small;">Your Purpose:</span><asp:TextBox TextMode="MultiLine" 
        Rows="10" runat="server" ID="txtPurpose"
        Height="50px" 
        Style="margin-left: 17px; margin-left: 19px; width: 200px; 
               background-image: url('../images/txtBoxbg.jpg') no-repeat;"></asp:TextBox>
    <asp:RequiredFieldValidator ID="RequiredFieldValidator6" ControlToValidate="txtPurpose"
        ErrorMessage="Can not be left blank" ValidationGroup="save" 
        runat="server" ForeColor="red"></asp:RequiredFieldValidator>
    <br />
    <asp:Button ID="btnPay" runat="server" Text="Pay Now" CssClass="button" Style="font-size: 12px;
        cursor: pointer; height: 27px; margin-left: 207px; margin-top: 10px; width: 93px;"
        OnClick="btnPay_AsPerYourChoice" ValidationGroup="save"></asp:Button>
</div>
    </form>
</body>
</html>




THE CODE BEHIND:

HERE BEFORE ADDING CODE YOU NEED TO HAVE AN AUTHORIZED ACCOUNT OR TRY WITH TESTING VERSION AS I HAVE DID::::

  //<!--Here i used sandbox site url only if you hosted in live change sandbox to live paypal URL-->
        //paypal account sandbox URL:  https://www.sandbox.paypal.com/cgi-bin/webscr
         
   // <add key="PayPalSubmitUrl" value="https://www.paypal.com/cgi-bin/webscr"/>

   // <add key="FailedURL" value="http://www.mrsoft.co.in/ProceedToPayment.aspx"/>

   // <add key="SuccessURL" value="http://www.mrsoft.co.in/ProceedToPayment.aspx"/>

using System;
using System.Collections;
using System.Configuration;
using System.Data;
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.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class PaymentIntegration : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
      
    }
    protected void PayWithPayPal(string amount, string itemInfo, string name,
          string phone, string email, string currency)
    {
        string redirecturl = "";

        //Mention URL to redirect content to paypal site
        redirecturl += "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_xclick&business=" +
                       ConfigurationManager.AppSettings["paypalemail"].ToString();

        //First name i assign static based on login details assign this value
        redirecturl += "&first_name=" + name;

        //City i assign static based on login user detail you change this value
        redirecturl += "&city=BANGALORE";

        //State i assign static based on login user detail you change this value
        redirecturl += "&state=YELHANKA NEW TOWM";

        //Product Name
        redirecturl += "&item_name=" + itemInfo;

        //Product Name
        redirecturl += "&amount=" + amount;

        //Phone No
        redirecturl += "&night_phone_a=" + phone;

        //Product Name
        redirecturl += "&item_name=" + itemInfo;

        //Address 
        redirecturl += "&address1=" + email;

        //Business contact id
        // redirecturl += "&business=piyushrana1991@gmail.com";

        //Shipping charges if any
        redirecturl += "&shipping=0";

        //Handling charges if any
        redirecturl += "&handling=0";

        //Tax amount if any
        redirecturl += "&tax=0";

        //Add quatity i added one only statically 
        redirecturl += "&quantity=1";

        //Currency code 
        redirecturl += "&currency=" + currency;

        //Success return page url
        redirecturl += "&return=" +
          ConfigurationManager.AppSettings["SuccessURL"].ToString();

        //Failed return page url
        redirecturl += "&cancel_return=" +
          ConfigurationManager.AppSettings["FailedURL"].ToString();

        Response.Redirect(redirecturl);


         
    }
    protected void btnPay_AsPerYourChoice(object sender, EventArgs e)
    {
        PayWithPayPal(txtAmount.Text.ToString(),txtPurpose.Text.ToString(), txtName.Text.ToString(), txtPhone.Text.ToString(), txtEmailId.Text.ToString(), ddlCurrency.SelectedItem.Text.ToString());
    }
}



      //The COMPLETE URL GENERATED AFTER EXECTION
    //   https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_xclick&business=piyushrana1991@live.com&first_name=piyush&city=BANGALORE&state=YELHANKA NEW TOWM&item_name=TESTING PURPOSE&amount=500&night_phone_a=9538774446&item_name=TESTING PURPOSE&address1=piyushrana1991@gmail.com&shipping=0&handling=0&tax=0&quantity=1&currency=INR&return=http://www.mrsoft.co.in/ProceedToPayment.aspx&cancel_return=http://www.mrsoft.co.in/ProceedToPayment.aspx
        
        // THE URL BEEN SHOWN BY PAYPAL(HTTPS)
        //https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_flow&SESSION=vvkc3WmzlBWoW6IQujCZ4L-egHt00STTbbNLkH4ZK-kf33C46xxdUCf4ZWC&dispatch=50a222a57771920b6a3d7b606239e4d529b525e0b7e69bf0224adecfb0124e9b61f737ba21b081986471f9b93cfa01e00b63629be0164db1





ADD DYNAMIC ROWS IN GRIDVIEW

ADD ROWS DYNAMICALLY IN GRIDVIEW


THE DESIGN PAGE:

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

<!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>AddDynamicRowsInGridview Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text="ADD EMPLOYER DETAILS IN THE GRIDVIEW(EXAMPLE CODE)"></asp:Label>
        <asp:GridView ID="grvEmployeeDetails" runat="server" 
                ShowFooter="True" AutoGenerateColumns="False"
                CellPadding="4" ForeColor="#333333" 
                GridLines="None" OnRowDeleting="grvEmployeeDetails_RowDeleting" 
            >
    <Columns>
        <asp:BoundField DataField="RowNumber" HeaderText="SNo" />
        <asp:TemplateField HeaderText="Employee Name">
            <ItemTemplate>
                <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Employee Age">
            <ItemTemplate>
                <asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Employee Address">
            <ItemTemplate>
                <asp:TextBox ID="txtAddress" runat="server" 
                   Height="55px" TextMode="MultiLine"></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Gender">
            <ItemTemplate>
                <asp:RadioButtonList ID="RBLGender" 
                           runat="server" RepeatDirection="Horizontal">
                    <asp:ListItem Value="M">Male</asp:ListItem>
                    <asp:ListItem Value="F">Female</asp:ListItem>
                </asp:RadioButtonList>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Qualification">
            <ItemTemplate>
                <asp:DropDownList ID="drpQualification" runat="server">
                    <asp:ListItem Value="G">Graduate</asp:ListItem>
                    <asp:ListItem Value="P">Post Graduate</asp:ListItem>
                </asp:DropDownList>
            </ItemTemplate>
            <FooterStyle HorizontalAlign="Right" />
            <FooterTemplate>
                <asp:Button ID="ButtonAdd" runat="server" 
                        Text="Add New Employee Details" OnClick="ButtonAdd_Click" />
            </FooterTemplate>
        </asp:TemplateField>
        <asp:CommandField ShowDeleteButton="True" />
    </Columns>
    <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
    <RowStyle BackColor="#EFF3FB" />
    <EditRowStyle BackColor="#2461BF" />
    <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
    <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
    <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
    <AlternatingRowStyle BackColor="White" />
</asp:GridView>
    </div>
    </form>
</body>
</html>


Here we created the gridview with custom columns .just edit as per your requirnment..
...


THE CODE BEHIND PAGE:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;


public partial class AddDynamicRowsInGridview : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            FirstGridViewRow();
        
        }
    }
    private void FirstGridViewRow()
    {
        DataTable dt = new DataTable();
        DataRow dr = null;
        dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
        dt.Columns.Add(new DataColumn("Col1", typeof(string)));
        dt.Columns.Add(new DataColumn("Col2", typeof(string)));
        dt.Columns.Add(new DataColumn("Col3", typeof(string)));
        dt.Columns.Add(new DataColumn("Col4", typeof(string)));
        dt.Columns.Add(new DataColumn("Col5", typeof(string)));
        dr = dt.NewRow();
        dr["RowNumber"] = 1;
        dr["Col1"] = string.Empty;
        dr["Col2"] = string.Empty;
        dr["Col3"] = string.Empty;
        dr["Col4"] = string.Empty;
        dr["Col5"] = string.Empty;
        dt.Rows.Add(dr);

        ViewState["CurrentTable"] = dt;

        grvEmployeeDetails.DataSource = dt;
        grvEmployeeDetails.DataBind();
    }
    private void AddNewRow()
    {
        int rowIndex = 0;

        if (ViewState["CurrentTable"] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
            DataRow drCurrentRow = null;
            if (dtCurrentTable.Rows.Count > 0)
            {
                for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                {
                    TextBox TextBoxName =
                      (TextBox)grvEmployeeDetails.Rows[rowIndex].Cells[1].FindControl("txtName");
                               TextBox TextBoxAge =
                      (TextBox)grvEmployeeDetails.Rows[rowIndex].Cells[2].FindControl("txtAge");
                    TextBox TextBoxAddress =
                      (TextBox)grvEmployeeDetails.Rows[rowIndex].Cells[3].FindControl("txtAddress");
                    RadioButtonList RBLGender =
                      (RadioButtonList)grvEmployeeDetails.Rows[rowIndex].Cells[4].FindControl("RBLGender");
                    DropDownList DrpQualification =
                      (DropDownList)grvEmployeeDetails.Rows[rowIndex].Cells[5].FindControl("drpQualification");
                    drCurrentRow = dtCurrentTable.NewRow();
                    drCurrentRow["RowNumber"] = i + 1;

                    dtCurrentTable.Rows[i - 1]["Col1"] = TextBoxName.Text;
                    dtCurrentTable.Rows[i - 1]["Col2"] = TextBoxAge.Text;
                    dtCurrentTable.Rows[i - 1]["Col3"] = TextBoxAddress.Text;
                    dtCurrentTable.Rows[i - 1]["Col4"] = RBLGender.SelectedValue;
                    dtCurrentTable.Rows[i - 1]["Col5"] = DrpQualification.SelectedValue;
                    rowIndex++;
                }
                dtCurrentTable.Rows.Add(drCurrentRow);
                ViewState["CurrentTable"] = dtCurrentTable;

                grvEmployeeDetails.DataSource = dtCurrentTable;
                grvEmployeeDetails.DataBind();
            }
        }
        else
        {
            Response.Write("ViewState is null");
        }
        SetPreviousData();
    }

    private void SetPreviousData()
    {
        int rowIndex = 0;
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    TextBox TextBoxName = (TextBox)grvEmployeeDetails.Rows[rowIndex].Cells[1].FindControl("txtName");
                    TextBox TextBoxAge = (TextBox)grvEmployeeDetails.Rows[rowIndex].Cells[2].FindControl("txtAge");
                    TextBox TextBoxAddress =
                      (TextBox)grvEmployeeDetails.Rows[rowIndex].Cells[3].FindControl("txtAddress");
                    RadioButtonList RBLGender =
                      (RadioButtonList)grvEmployeeDetails.Rows[rowIndex].Cells[4].FindControl("RBLGender");
                    DropDownList DrpQualification =
                      (DropDownList)grvEmployeeDetails.Rows[rowIndex].Cells[5].FindControl("drpQualification");

                    TextBoxName.Text = dt.Rows[i]["Col1"].ToString();
                    TextBoxAge.Text = dt.Rows[i]["Col2"].ToString();
                    TextBoxAddress.Text = dt.Rows[i]["Col3"].ToString();
                    RBLGender.SelectedValue = dt.Rows[i]["Col4"].ToString();
                    DrpQualification.SelectedValue = dt.Rows[i]["Col5"].ToString();
                    rowIndex++;
                }
            }
        }
    }
    protected void grvEmployeeDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        SetRowData();
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            DataRow drCurrentRow = null;
            int rowIndex = Convert.ToInt32(e.RowIndex);
            if (dt.Rows.Count > 1)
            {
                dt.Rows.Remove(dt.Rows[rowIndex]);
                drCurrentRow = dt.NewRow();
                ViewState["CurrentTable"] = dt;
                grvEmployeeDetails.DataSource = dt;
                grvEmployeeDetails.DataBind();

                for (int i = 0; i < grvEmployeeDetails.Rows.Count - 1; i++)
                {
                    grvEmployeeDetails.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
                }
                SetPreviousData();
            }
        }
    }
    private void SetRowData()
    {
        int rowIndex = 0;

        if (ViewState["CurrentTable"] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
            DataRow drCurrentRow = null;
            if (dtCurrentTable.Rows.Count > 0)
            {
                for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                {
                    TextBox TextBoxName = (TextBox)grvEmployeeDetails.Rows[rowIndex].Cells[1].FindControl("txtName");
                    TextBox TextBoxAge = (TextBox)grvEmployeeDetails.Rows[rowIndex].Cells[2].FindControl("txtAge");
                    TextBox TextBoxAddress = (TextBox)grvEmployeeDetails.Rows[rowIndex].Cells[3].FindControl("txtAddress");
                    RadioButtonList RBLGender =
                      (RadioButtonList)grvEmployeeDetails.Rows[rowIndex].Cells[4].FindControl("RBLGender");
                    DropDownList DrpQualification =
                      (DropDownList)grvEmployeeDetails.Rows[rowIndex].Cells[5].FindControl("drpQualification");
                    drCurrentRow = dtCurrentTable.NewRow();
                    drCurrentRow["RowNumber"] = i + 1;
                    dtCurrentTable.Rows[i - 1]["Col1"] = TextBoxName.Text;
                    dtCurrentTable.Rows[i - 1]["Col2"] = TextBoxAge.Text;
                    dtCurrentTable.Rows[i - 1]["Col3"] = TextBoxAddress.Text;
                    dtCurrentTable.Rows[i - 1]["Col4"] = RBLGender.SelectedValue;
                    dtCurrentTable.Rows[i - 1]["Col5"] = DrpQualification.SelectedValue;
                    rowIndex++;
                }

                ViewState["CurrentTable"] = dtCurrentTable;
                //grvStudentDetails.DataSource = dtCurrentTable;
                //grvStudentDetails.DataBind();
            }
        }
        else
        {
            Response.Write("ViewState is null");
        }
        //SetPreviousData();
    }
    protected void ButtonAdd_Click(object sender, EventArgs e)
    {

        AddNewRow();
    }
}


Here we created four function to add new row...AddNewRow() and set previous data in gridview.



Friday, 10 January 2014

FileUpload Check Constraints File Type and File Extension and File Size

SIMPLE PROGRAM TO CHECK THE VARIOUS CONSTRAINT REQUIRED AT  FOR FILE UPLOAD


THE DESIGN PAGE:

<%@ 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>FILE UPLOAD FILTERS</title>
    <script src="jquery-1.9.1.min.js" type="text/javascript"></script>
    
    <script type="text/javascript">
        $(document).ready(function () {
             var validFilesTypes = ["bmp", "gif", "png", "jpg", "jpeg", "doc", "docx", "xls", "xlsx", "htm", "html", "rar", "zip", "txt", "pdf"];
            $('.s').change(function () {
                CheckExtension(this);
                validateFileSize(this);
            });
            function CheckExtension(e) {
                /*global document: false */
                var file = e;
                var path = file.value;
                var ext = path.substring(path.lastIndexOf(".") + 1, path.length).toLowerCase();
                var isValidFile = false;
                for (var i = 0; i < validFilesTypes.length; i++) {
                    if (ext == validFilesTypes[i]) {
                        isValidFile = true;
                        break;
                    }
                }
                if (!isValidFile) {
                    e.value = null;
                    alert("Invalid File. Unknown Extension Of Tender Doc" + "Valid extensions are:\n\n" + validFilesTypes.join(", "));
                }
                return isValidFile;
            }
            function validateFileSize(e) {
                /*global document: false */
                var file = e;
                var fileSize = file.files[0].size;
                var isValidFile = false;
                if (fileSize !== 0 && fileSize <= 4194304) {
                    isValidFile = true;
                }
                if (!isValidFile) {
                    e.value = null;
                    alert("File Size Should be Greater than 0 and less than 4 mb");
                }
                return isValidFile;
            }
        });
    
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text="SELECT THE FILE TO UPLOAD"></asp:Label>
        <asp:FileUpload ID="FileUpload1" CssClass="s" runat="server" />
    </div>
    </form>
</body>
</html>