Share Blog

Saturday, December 26, 2015

JQuery Bootstrap Autocomplete Textbox from Database Example in Asp.net using C#

Before Implement This Example First Create One Table Leader in your  SQL Database like as Shown Below

CREATE TABLE Leader(
      [LeaderId] [int] IDENTITY(1,1)Primary Key NOT NULL,
      [Leader_Name] [nvarchar](150) NULL,
      [State] [nvarchar](150) NULL,
      [Lok_Sabha_Place] [nvarchar](150) NULL
)



Once we design table in our Database insert some data in your table to use it in our application that would be like as shown below



Now open your aspx page and write the code like as shown below

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

<!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>Bootstrap Autocomplete Textbox Example in Asp.net Using C#</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel = "Stylesheet" href = "https://twitter.github.io/typeahead.js/css/examples.css"></link>

<script type="text/javascript">
    $(function () {
        $('#txtSearch').keyup(function () {
            $.ajax({
                url: "AutocompleteTextbox .aspx/GetAutoCompleteData",
                data: "{'username':'" + $('#txtSearch').val() + "'}",
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    var val = '<ul id="userlist">';
                    $.map(data.d, function (item) {
                        var itemval = item.split('/')[0];
                        val += '<li class=tt-suggestion>' + itemval + '</li>'
                    })
                    val += '</ul>'
                    $('#divautocomplete').show();
                    $('#divautocomplete').html(val);
                    $('#userlist li').click(function () {
                        $('#txtSearch').val($(this).text());
                        $('#divautocomplete').hide();
                    })
                },
                error: function (response) {
                    alert(response.responseText);
                }
            });
        })
        $(document).mouseup(function (e) {
            var closediv = $("#divautocomplete");
            if (closediv.has(e.target).length == 0) {
                closediv.hide();
            }
        });
    });
</script>
<style type="text/css">
ul li
{
list-style: none;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div style="position: absolute;left: 30%; z-index: 100; text-align:left;">

    <asp:TextBox ID="txtSearch" runat="server" class="typeahead" placeholder="Type Leader Name to search" autocomplete="off" ></asp:TextBox>
<div id="divautocomplete" class="tt-menu" style="display:none">
</div>
</div>
</form>
</body>
</html>

Now add following namespaces in code behind

using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Data.SqlClient;
using System.Configuration;

After completion of adding namespaces you need to write the code like as shown below

using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Data.SqlClient;
using System.Configuration;

public partial class AutocompleteTextbox_ : System.Web.UI.Page
{
    //SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    [WebMethod]
    public static List<string> GetAutoCompleteData(string username)
    {
        List<string> result = new List<string>();
        using (SqlConnection con = new SqlConnection("Data Source=lENOVO-pC;Initial Catalog=Digital_Politices;Integrated Security=True"))
        {
            using (SqlCommand cmd = new SqlCommand("select LeaderId,Leader_Name from Leader where Leader_Name LIKE '%'+@SearchText+'%'",con))
            {
                con.Open();
                cmd.Parameters.AddWithValue("@SearchText", username);
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    result.Add(string.Format("{0}/{1}", dr["Leader_Name"], dr["LeaderId"]));
                }
                return result;
            }

        }
    }
}


DEMO


Thursday, December 17, 2015

How to Generate One Time Password (OTP) in Asp.net Using C#

To Generate Random OTP  in Asp.net Open Your aspx Page and Write the Following Code

<center>
    <div>
Enter Number of Characters: <asp:TextBox ID="TxtCharacters" runat="server"/>
<asp:Button ID="BtnGenerateChar" Text="Generate" runat="server"
            onclick="BtnGenerateChar_Click" /><br />
<asp:Label ID="lblresult" runat="server" ForeColor="Blue" />
</div>
</center>


Now Add following Namespaces in Code behind

using System;
using System.Web;

After Completion of Adding Namespaces You Need to Write the Code like as Shown below


    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void BtnGenerateChar_Click(object sender, EventArgs e)
    {
        // Declare Array string to Generate Random string with Combination of Small,Capital letters Numbers and Special Characters
        char[] charArr = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@#$%&".ToCharArray();
        string stringRandom = string.Empty;
        Random objran = new Random();
        int noofcharacters = Convert.ToInt32(TxtCharacters.Text);
        for (int i = 0; i < noofcharacters; i++)
        {
            //It will not allow Repetation of Characters
            int pos = objran.Next(1, charArr.Length);
            if (!stringRandom.Contains(charArr.GetValue(pos).ToString()))
                stringRandom += charArr.GetValue(pos);
            else
                i--;
        }
        lblresult.Text = stringRandom;

    }


DEMO



Thursday, November 26, 2015

Encryption and Decryption in ASP.NET

Encryption: is the activity of converting data or information into code or a secret key.


Decryption: is the activity of making clear to converting from code into plain text.

Create a Class.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Cryptography;
using System.IO;
using System.Text;


public class Class1
{
    string Encryptionkey = "987";
    public string Encrypt(string originalText)
    {

        byte[] originalbytes = Encoding.Unicode.GetBytes(originalText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(Encryptionkey, new Byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(originalbytes, 0, originalbytes.Length);
                    cs.Close();
                }
                originalText = Convert.ToBase64String(ms.ToArray());
            }
        }
        return originalText;

    }

    public string Decrypt(string cipherText)
    {

        Byte[] cipherBytes = Convert.FromBase64String(cipherText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pbd = new Rfc2898DeriveBytes(Encryptionkey, new Byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x76 });
            encryptor.Key = pbd.GetBytes(32);
            encryptor.IV = pbd.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(cipherBytes, 0, cipherBytes.Length);
                    cs.Close();
                }
                cipherText = Encoding.Unicode.GetString(ms.ToArray());
            }

        }

        return cipherText;
    }


       public Class1()
       {
        //
        // TODO: Add constructor logic here
        //

       }
}

Create Default.aspx file

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table>
            <tr>
                <td>Password</td>
                <td colspan="2">
                    <asp:TextBox ID="TxtPassword" runat="server"></asp:TextBox></td>
            </tr>
            <tr>
                <td>Encryption text=</td>
                <td>
                    <asp:Label ID="lblEncry" runat="server" Text=""></asp:Label></td>
                <td>
                    <asp:Button ID="BtnEncryption" runat="server" Text="Encrypt"
                        onclick="BtnEncryption_Click"  /></td>
            </tr>
            <tr>
                <td>Decryption text=</td>
                <td>
                    <asp:Label ID="lblDecry" runat="server" Text=""></asp:Label></td>
                <td>
                    <asp:Button ID="BtnDecryption" runat="server" Text="Decrypt" Enabled="False"
                        onclick="BtnDecryption_Click"  /></td>
            </tr>
            <tr>
                <td></td>
            </tr>
        </table>

    </div>
    </form>
</body>
</html>


Write in Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Cryptography;
using System.IO;
using System.Text;


public partial class Encryption_decryption : System.Web.UI.Page
{
    Class1 obj = new Class1();
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void BtnEncryption_Click(object sender, EventArgs e)
    {
        lblEncry.Text = obj.Encrypt(TxtPassword.Text.Trim());
        BtnDecryption.Enabled = true;

    }
    protected void BtnDecryption_Click(object sender, EventArgs e)
    {
        lblDecry.Text = obj.Decrypt(lblEncry.Text.Trim());
    }
}


OutPut



Saturday, November 14, 2015

How to Use Session State in Asp.net

Session State: The session state is used to maintain the session of each user throughout the application. Session allows information to be stored in one page and access in another page and support any type of object. In many websites we will see the functionality like once if we login into website they will show username in all the pages for that they will store username in session and they will access that session username in all the pages.
 Whenever user enters into website new session id will generate for that user. This session Id will delete when he leave from that application. If he enters again he will get new session Id.

Step 1:-First open your visual studio -->File-->New-->website-->select ASP.NET Empty website -->OK-->open solution explorer -->Add New Web Form -->drag and drop label,Text box and Button control on the form as shown below:-



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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .style2
        {
            width: 119px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <table style="width:100%;">
            <tr>
                <td class="style2">
                    User Name</td>
                <td>
                    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2" >
                    Password</td>
                <td>
                    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                </td>
                <td>
                    &nbsp;</td>
            </tr>
          
            <tr>
                <td class="style2" >
                    &nbsp;</td>
                <td>
                    <asp:Button ID="Button1" runat="server" onclick="Button1_Click"
                        style="margin-left: 0px" Text="Submit" />
                    <br />
                </td>
                <td>
                    &nbsp;</td>
            </tr>
          
        </table>
   
    </div>
    </form>
</body>
</html>

Step 2:- Double click on Submit button -->write the following codes which are given below:-

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

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

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Session["user"] = TextBox1.Text;
       // Session["pass"] = TextBox2.Text;
        Response.Redirect("Default2.aspx");
        Session.RemoveAll();
    }
}
Step 3:-  No Add a New web Form -->drag and drop label and button control on te web Form as shown below:-





Step 4:- Double click on Logout button-->Write the following codes which are given below:-

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

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

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Session["user"] = TextBox1.Text;
       // Session["pass"] = TextBox2.Text;
        Response.Redirect("Default2.aspx");
        Session.RemoveAll();
    }
}

Step 5:- Now Run the application (press F5)-->Fill the required field details as shown below:-

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


Step 6:-  Now click Submit button --> you will see following output-->now click Logout button--> you will redirect to home page(destroy session).