Popular Posts

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>