Popular Posts

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>


Saturday, 21 December 2013

Using Google Co-op's Custom Search Engine

Using Google Co-op's Custom Search Engine



Using google free api you can add a search Engine for your own website ,just need to have a gmail id and follow these steps:

Creating Your Search Engine

The very first step you must take is to visit http://www.google.com/coop/cse.
 (Note that you must have a Google Account. If you don’t have one, Create one. follow the instructions to create your custom search engine.

Where to Host the Custom Search Engine

You have two options on how you can display your search engine to users: Google can host it for you, or you can host the search box and results on your site. For this article, I opted for the latter.
To configure this option:
  1. Return to the Google Co-op Custom Search Engine site’s home page (http://www.google.com/coop/cse).
  2. Click on the My Search Engines link.
  3. When the list of your custom search engines shows up, click on the link that says “Control Panel”.
  4. Next, click on the link that says “Code”.
  5. Select the radio button next to the option that says “Host a search box and search results on your own site…”.
  6. Also, specify the URL of the page on your site where you want the search results to appear.
  7. Finally, after you select the location where you want to display the AdSense ads in your search results, click the Save Changes button.


AFTER REGISTERING THE WEBSITE YOU GET THE CODE JUST PASTE THE CODE IN DIV TAG ON YOUR PAGE WHERE YOU WANT YOUR SEARCH.FOLLOW THE SCREENSHOTS:


1.REGISTER YOUR SITE




2. CREATE YOUR CUSTOM LOOK AND FEEL




3.EXTRACT THE CODE AND PASTE ON YOUR ASPX PAGE



4.DEMO TEST RESULT FOR SEARCH ON YOUR REGISTERED SITE



----------------------------------------------------------------------------------------------------------------------

TO CREATE COUNTDOWN TIMER USING AJAX IN ASP.NET

TO CREATE COUNTDOWN TIMER USING AJAX IN ASP.NET


Friends today we will see how to create a countdown timer with the help of ajax.
 

THE DESIGN PAGE:


You need to frst Register the AJAXCONTROLTOOLKIT in your ASPX page .
then follow the simple code:


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="testpage.aspx.cs" Inherits="testpage" MasterPageFile="~/MasterPages/MasterPage.master"%>

 <%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">

   
    <style type="text/css">
        .circle
        {
         text-align:center;
        float:left;
        width:60px;
        height:60px;
        background-color:#ffffff;
        border: 1px solid #000000;
        padding:20px 20px 20px 20px;
        -moz-border-radius: 50px;
        -webkit-border-radius: 50px;
        border-radius: 50px;
     
         font-family:Cambria;
         font-size:35px;
        }
        .styletable
        {
          font-family:Cambria;
            font-size:15px;
         font-weight:bold;
        }
     </style>

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="cpMainContent" Runat="Server">

  
    <div id="countdowntimerform" runat="server"><br />
        <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
        </asp:ToolkitScriptManager>
        <br />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
         <asp:Timer ID="Timer1" runat="server" Interval="1000" ontick="Timer1_Tick">
        </asp:Timer>
        <br />
        <br />
        <table width="260">
        <tr>
         <td><div class="circle"><asp:Label ID="Label1" runat="server"></asp:Label></div></td>
         <td><div class="circle"><asp:Label ID="Label2" runat="server"></asp:Label></div></td>
         <td><div class="circle"><asp:Label ID="Label3" runat="server"></asp:Label></div></td>
         <td><div class="circle"><asp:Label ID="Label4" runat="server"></asp:Label></div></td>
        </tr>
        <tr align="center"><td><b>DAYS</b></td><td><b>HOURS</b></td><td><b>MIN</b></td><td><b>SEC</b></td></tr></table
        </ContentTemplate>
        </asp:UpdatePanel>
         </div>
   </asp:Content>


THE CODE BEHIND:

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;
using System.Data;

public partial class testpage : System.Web.UI.Page
{
    static DateTime setdt;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        { 
            
        
            DateTime time = DateTime.Now;              // Use current time
            string format = "d mm yyyy HH:mm:ss ";    // Use this format
            Console.WriteLine(time.ToString(format));  // Write to console


          DateTime  date1 = (time.AddMinutes(3));  
//HERE I HAVE ADDED THE TIMER TO 3 MINUTES FROM THE CURRENT TIME.SO THE //COUNTDOWN WILLSTARTS WITH 3 MINUTES REMAINING.
  
        Session["addedtime"] = date1;
          Timer1.Enabled = true;
        }
    }


    protected void Timer1_Tick(object sender, EventArgs e)
    {
        DateTime dt = DateTime.Now;
        TimeSpan differ;
        
      //   System.DateTime date1 = new System.DateTime();
        DateTime date1 = (DateTime)Session["addedtime"];
        differ = date1.Subtract(dt);
        double t = differ.TotalSeconds;

        if (t > 0)
        {
            double yr, mnth, dy, h, m, s;
            dy = differ.Days;
            h = differ.Hours;
            m = differ.Minutes;
            s = differ.Seconds;
            Label1.Text = dy.ToString();// +" Days " + h + " Hours " + m + " Minutes " + s + " Seconds left for celebration";
            Label2.Text = h.ToString();
            Label3.Text = m.ToString();
            Label4.Text = s.ToString();
        }
        else
        {
            Timer1.Enabled = false;
//and perform your other logic here
        }
    }
   
}

 

SENDING SMS THROUGH ASP.NET PROGRAMM

SENDING SMS OTP(ONE TIME  PASSWORD) TO USER MOBILE NO.


Hello friends this post explains the way where you can send the sms to any user mobile ,where i am sending or applying the concept on OTP to be send to registered user for his authentication.

In general, there are two ways to send SMS messages from a computer / PC to a mobile phone:
  1. Connect a mobile phone or GSM/GPRS modem to a computer / PC. Then use the computer / PC and AT commands to instruct the mobile phone or GSM/GPRS modem to send SMS messages.
  2. Connect the computer / PC to the SMS center (SMSC) or SMS gateway of a wireless carrier or SMS service provider. Then send SMS messages using a protocol / interface supported by the SMSC or SMS gateway.
HERE WE WILL DISCUSS THE SECOND WAY.TO REFER THE FIRST WAY I FOUND AN ARTICLE  ON CODE PROJECT:

THE DESIGN PAGE:

The design page will consists of user register form where he fills up the data and wait to recieve the sms code and need to enter the OTP and validation will be done.


THE CODE BEHIND:
TO SEND SMS:


this is the simple function created to send the OTP  to user mobile no:

   protected Int32 sendonetimepass(string username, string mobileno, string emailid)
    {
        try
        {
         

            Random _r = new Random();  //random number function to generate OTP

            int n = _r.Next(10000);


            System.IO.Stream Str = null;
            System.IO.StreamReader srRead = null;  //object of streamReader
            string PageContent = null;
            string strTmpContact = string.Empty;
            string message = "Dear User " + username + " ,Your One Time Password(OTP) is " + n + " ,please enter to confirm your identity/authenticity";
            if (n > 0)
            {
                string url = ("http://www.URPROVIDER.in/SendTestSMS/SendTESTMsg.php?uname=URREGISTERDNAME&pass=URPASSWORD&send=URREGISTRATIONNO&dest=91" + mobileno + "&msg=TITLE_OF_MESSAGE ") + message + "";


// the string Url consistis of  the the url string provided to u by the SERVICE PROVIDER TO SEND SMS.
// You can send SMS using ASP.net web application. First you hunt for good SMS provider API.    //API should be capable of sending long messages more than 160 characters.    //It works with http Get Method. Below is the code snippet to deal with an API.                


 System.Net.WebRequest req = System.Net.WebRequest.Create(url);
                System.Net.WebResponse resp = req.GetResponse();
                Str = resp.GetResponseStream();
                srRead = new System.IO.StreamReader(Str);
                // read all the text
                PageContent = srRead.ReadToEnd();

            }
            if ((srRead != null) & (Str != null))
            {
                srRead.Close();
                Str.Close();
            }
            return n;
        }

        catch (Exception ex)
        {
            return 0;

        }

    }



TO VALIDATE THE SMS ENTERED BY USER:

Once the sms is send successfully then you can save the sms of the user with his name and others details in the DB and can check when he enters.LIKE:



string query = "insert into userotpdetails values('" + txtUserName.Text + "','" + txtUserID.Text + "','" + txtPassword.Text + "','" + txtMobile.Text + "','" + txtEmailID.Text + "'," + otp + ",'" + currentdatetime + "')";
                DBAccess obj1 = new DBAccess();
                string result = obj1.OracleExecute(query);
                if (result == "Success")
                {
SYSTEM.OUT.PRINTLN("DETAILS SUBMMITED SUCCESFULLY");
               }

----------------------------------------------------------------------------------------------------------