Sunday 19 August 2012

Asp.Net watermark text for textbox using javascript

Here I will explain how to create a watermark text in asp.net using javascript.

Open Visual studio > click on file menu> open new website> give it to name> click on ok button

Design your aspx page like as below:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Watermark Using JavaScript</title>
<script language="javascript" type="text/javascript">
function waterMark(objtext, event) {
var defaultText = "Enter User_name Here";
var defaultpwdText = "Enter  Your Password Here";
if (objtext.id == "txtUserName" || objtext.id == "txtPwd") {
if (objtext.value.length == 0 & event.type == "blur") {
if (objtext.id == "txtUserName") {
objtext.style.color = "Gray";
objtext.value = defaultText;
}
if (objtext.id == "txtPwd") {
document.getElementById("<%= txtTempPwd.ClientID %>").style.display = "block";
objtext.style.display = "none";
}
}
}
// Condition to check textbox value and event type
if ((objtext.value == defaultText || objtext.value == defaultpwdText) & event.type == "focus") {
if (objtext.id == "txtUserName") {
objtext.style.color = "black";
objtext.value = "";
}
if (objtext.id == "txtTempPwd") {
objtext.style.display = "none";
document.getElementById("<%= txtPwd.ClientID %>").style.display = "";
document.getElementById("<%= txtPwd.ClientID %>").focus();
}
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td><b>UserName:</b></td>
<td>
<asp:TextBox ID="txtUserName" runat="server" Text="Enter Username Here" Width="150px" ForeColor="Gray" onblur = "waterMark(this, event);" onfocus = "WaterMark(this, event);" />
</td>
</tr>
<tr>
<td><b>Password:</b></td>
<td>
<asp:TextBox ID="txtTempPwd" Text="Enter  Your  Password Here" runat="server" onfocus="waterMark(this, event);" Width="150px" ForeColor="Gray" />
<asp:TextBox ID="txtPwd" TextMode="Password" Text="Enter Your Password Here" runat="server" Width="150px" Style="display:none" onblur="waterMark(this, event);"/>
</td>
</tr>
</table>
</form>
</body>
</html>
Run your Project and test it.

Saturday 18 August 2012

How to check your Dataset or Datatable is null or empty

Here I will explain to you , how to check dataset or datatable is null or empty.

If you want to check your dataset or datatable is empty or not ,you have to wright some code as given below.

C# code:

SqlDataAdapter da=new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
// Condition to check if dataset tables contains data or not
if (ds.Tables[0].Rows.Count > 0)
{
  Label1.Text= "Dataset table contains data";
}
}
else
{
  Label1.Text= "Dataset does not contains data";
}

And for DataTable:



SqlDataAdapter da=new SqlDataAdapter(cmd);
DataTable dt = new DataTable ();
da.Fill(dt);
// Condition to check if dataset tables contains data or not
if (dt.Rows.Count > 0)
{
  Label1.Text= "DataTable contains data";
}
}
else
{
  Label1.Text= "DataTable does not contains data";
}

How to create button Dynamically and save data into database in asp.net

Here we learn how to create button dynamically means at run time.

Step1:

First create table in database  as below
create table loginDetails(user_name varchar(50),password varchar(50)).

Step2:

For this open VS 2010> go to file menu> open new website > give it to name>click ok.

DEsign of aspx like below:

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

<!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>Create button dynamically and store data in database dynamically</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Panel ID="Panel1" runat="server">
        </asp:Panel>
    </div>
    </form>
</body>
</html>

Code for code behind file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class DynamicControlCreation_DynamicButton : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Table tb = new Table();
        TableCell tc = new TableCell();
        TableCell tc1 = new TableCell();
        TableRow tr = new TableRow();
        Label lb = new Label();
        lb.ID = "username";
        lb.Text = "User Name";
        tc.Controls.Add(lb);
        TextBox txtBox = new TextBox();
        txtBox.ID = "txt_username";
        tc1.Controls.Add(txtBox);
        tr.Cells.Add(tc);
        tr.Cells.Add(tc1);
        tb.Rows.Add(tr);
        Label lb1 = new Label();
        lb1.ID = "password";
        lb1.Text = "Password";
        tc1.Controls.Add(lb1);
        TextBox txtBox1 = new TextBox();
        txtBox1.ID = "txt_pass";
        tc1.Controls.Add(txtBox1);
        tr.Cells.Add(tc);
        tr.Cells.Add(tc1);
        tb.Rows.Add(tr);
        Button btnsubmit = new Button();
        btnsubmit.ID = "btnsubmit";
        btnsubmit.Text = "Submit";
        btnsubmit.Click += new EventHandler(btnsubmit_Click);
        tc1.Controls.Add(btnsubmit);
        tr.Cells.Add(tc);
        tr.Cells.Add(tc1);
        tb.Rows.Add(tr);
        Panel1.Controls.Add(tb);
    }

   protected void btnsubmit_Click(object sender, EventArgs e)
    {
        string str = string.Empty;
        TextBox txtusername = (TextBox)Panel1.FindControl("txt_username");
        TextBox txtpassword = (TextBox)Panel1.FindControl("txt_pass");
        using (SqlConnection con = new SqlConnection("Data Source=SUSHIL-70F1F267;Initial Catalog=sushil;Integrated Security=True"))
        {
            using (SqlCommand cmd = new SqlCommand("INSERT INTO loginDetails(user_name,password) VALUES(@user_name,@password)", con))
            {
                con.Open();
                cmd.Parameters.AddWithValue("@user_name", txtusername.Text);
                cmd.Parameters.AddWithValue("@password", txtpassword.Text);
                cmd.ExecuteNonQuery();
                txtpassword.Text = string.Empty;
                txtusername.Text = string.Empty;
                ClientScript.RegisterClientScriptBlock(this.GetType(), "btn", "<script type = 'text/javascript'>alert('UserDetails saved Successfully');</script>");
            }
        }
    }
   
}

Run the code . Hope this will work perfectly.

How to Insert ,Update,Dlete and Find Data into sql Server Database using WCF services

This artical show you how to insert data into sql server using wcf service in asp.net.
To insert data into database using wcf you have to do 3 thing:
1>Create a database table.
2>create a wcf service
3>create a web application

Step1:

First create database table.
create table RegistrationTable(UserName varchar(50),Password varchar(50),Country varchar(50,Email varchar(50));
execute this code.

Step2:

Now its time to create WCF service.
Open Visual studio>go to file menu> open new project > click on wcf application.> give a namr to it.> click on ok button.

Now you will get three files like
  1. IService.cs
  2. Service.svc
  3. Service.svc.cs

Code For IService.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Data;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService" in both code and config file together.
[ServiceContract]
public interface IService
{

    [OperationContract]
    string GetData(int value);

    [OperationContract]
    CompositeType GetDataUsingDataContract(CompositeType composite);
    string InsertUserDetails(UserDetails userInfo);
    string DeleteUserDetails(UserDetails userInfo);
    DataSet FindUserDetails(UserDetails userInfo);
    //string UpdateUserDetails(UserDetails userInfo);
    // TODO: Add your service operations here
}

// Use a data contract as illustrated in the sample below to add composite types to service operations.
[DataContract]
public class UserDetails
{

    string username = string.Empty;

    string password = string.Empty;

    string country = string.Empty;

    string email = string.Empty;



    [DataMember]

    public string UserName
    {

        get { return username; }

        set { username = value; }

    }

    [DataMember]

    public string Password
    {

        get { return password; }

        set { password = value; }

    }

    [DataMember]

    public string Country
    {

        get { return country; }

        set { country = value; }

    }

    [DataMember]

    public string Email
    {

        get { return email; }

        set { email = value; }

    }

}
public class CompositeType
{
    bool boolValue = true;
    string stringValue = "Hello ";

    [DataMember]
    public bool BoolValue
    {
        get { return boolValue; }
        set { boolValue = value; }
    }

    [DataMember]
    public string StringValue
    {
        get { return stringValue; }
        set { stringValue = value; }
    }
}
 
For inserting data into database you have to write code in service.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Data;
using System.Data.SqlClient;
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service" in code, svc and config file together.
public class Service : IService
{
    SqlConnection con = new SqlConnection("Data Source =SUSHIL-70F1F267; Initial Catalog =sushil; Integrated Security=true");
    public string GetData(int value)
    {
        return string.Format("You entered: {0}", value);
    }

    public CompositeType GetDataUsingDataContract(CompositeType composite)
    {
        if (composite == null)
        {
            throw new ArgumentNullException("composite");
        }
        if (composite.BoolValue)
        {
            composite.StringValue += "Suffix";
        }
        return composite;
    }
   
    //this is used for inserting updating data from database
    public string InsertUserDetails(UserDetails userInfo)
    {
        string Message;
        con.Open();
        string cmd = "insert into RegistrationTable(UserName,Password,Country,Email) values(@UserName,@Password,@Country,@Email)";
        SqlCommand com = new SqlCommand(cmd,con);
        com.Parameters.AddWithValue("@UserName", userInfo.UserName);
        com.Parameters.AddWithValue("@Password", userInfo.Password);
        com.Parameters.AddWithValue("@Country", userInfo.Country);
        com.Parameters.AddWithValue("@Email", userInfo.Email);
        int result = com.ExecuteNonQuery();
        if (result == 1)
        {
            Message=userInfo.UserName + " Details inserted successfully";

        }
        else
            {
                Message = userInfo.UserName + " Details not inserted successfully";
            }
            con.Close();
            return Message;
        }
    public string DeleteUserDetails(UserDetails userInfo)
    {
        string Message;
        con.Open();
        string cmd = " delete from  RegistrationTable where UserName=@UserName";
        SqlCommand com = new SqlCommand(cmd,con);
        com.Parameters.AddWithValue("@UserName",userInfo.UserName);
        int result= com.ExecuteNonQuery();
        if (result == 1)
        {
            Message = userInfo.UserName + " Details inserted successfully";

        }
        else
        {
            Message = userInfo.UserName + " Details not inserted successfully";
        }
        con.Close();
        return Message;
    }
    public DataSet FindUserDetails(UserDetails userInfo)
    {
       
       
        string cmd = "select * from RegistrationTable where UserName=@UserName";
        SqlCommand com = new SqlCommand(cmd,con);
        com.Parameters.AddWithValue("@UserName", userInfo.UserName);
        SqlDataAdapter da = new SqlDataAdapter(com);
        con.Open();

        DataSet ds = new DataSet();

        da.Fill(ds);

        con.Close();

        return ds;
       
    }
    public string UpdateUserDetails(UserDetails userInfo)
    {
        string Message;
        con.Open();
        string cmd = "update RegistrationTable set Password=@Password,Country=@Country,Email=@Email where UserName=@UserName";
        SqlCommand com = new SqlCommand(cmd, con);
        com.Parameters.AddWithValue("@UserName", userInfo.UserName);
        com.Parameters.AddWithValue("@Password", userInfo.Password);
        com.Parameters.AddWithValue("@Country", userInfo.Country);
        com.Parameters.AddWithValue("@Email", userInfo.Email);
        int result = com.ExecuteNonQuery();
        if (result == 1)
        {
            Message = userInfo.UserName + " Update successfully";

        }
        else
        {
            Message = userInfo.UserName + " Do not Update successfully";
        }
        con.Close();
        return Message;
    }
}

now press F5 to run the  service file.

Step3:

Now add one web page into .
Go to solution explorer > right click on project solution > add new item > click on web page> give a name > click on ok button.

aspx.page:

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

<!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>Insert Update and Delete in asp.net using WCF services</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table width="84%" cellpadding="0" cellspacing="0" style="border: solid 1px #3366CC;">

            <tr>

                <td colspan="4" style="height: 30px; background-color: #f5712b;">

                    <span class="TextTitle" style="color: #FFFFFF;">Registration Form</span>

                </td>

            </tr>

            <tr>

                <td height="20px" colspan="0">

                </td>

            </tr>

            <tr>

                <td width="50%" valign="top">

                    <table id="TableLogin" class="HomePageControlBGLightGray" cellpadding="4" cellspacing="4"

                        runat="server" width="100%">

                        <tr>

                            <td colspan="3" align="center">

                                <asp:Label ID="LabelMessage" ForeColor="Red" runat="server" EnableViewState="False"

                                    Visible="False"></asp:Label><br/>

                            </td>

                        </tr>

                        <tr style="font-weight: normal; color: #000000">

                            <td align="right">

                                <span>UserName:</span>;

                            </td>

                            <td align="left" style="padding-left: 10px;">

                                <asp:TextBox ID="TextBoxUserName" runat="server" CssClass="textbox" Width="262px"

                                    MaxLength="50" Height="34px"></asp:TextBox>

                            </td>

                        </tr>

                        <tr>

                            <td align="right">

                                <span class="TextTitle">Password:</span>

                            </td>

                            <td align="left" style="padding-left: 10px;">

                                <asp:TextBox ID="TextBoxPassword" runat="server" CssClass="textbox" Width="261px"

                                    MaxLength="50" TextMode="Password" Height="34px"></asp:TextBox>

                                <br />

                            </td>

                        </tr>

                        <tr>

                            <td align="right">

                                <span class="TextTitle">Country:</span>

                            </td>

                            <td align="left" style="padding-left: 10px;">

                                <asp:TextBox ID="TextBoxCountry" runat="server" CssClass="textbox" Width="258px"

                                    MaxLength="50" Height="34px"></asp:TextBox>

                                <br />

                            </td>

                        </tr>

                        <tr>

                            <td align="right">

                                <span class="TextTitle">Email:</span>

                            </td>

                            <td align="left" style="padding-left: 10px;">

                                <asp:TextBox ID="TextBoxEmail" runat="server" CssClass="textbox" Width="258px"

                                    MaxLength="50" Height="34px"></asp:TextBox>

                                <br />

                            </td>

                        </tr>

                        <tr>

                            <td align="right">

                            </td>

                            <td align="left" style="padding-left: 10px;">

                                <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" Width="87px" />
                                <asp:Button ID="Buttbtn_delete" runat="server" Text="Delete"  Width="87px"
                                    onclick="Buttbtn_delete_Click" />
                                    <asp:Button ID="btn_find" runat="server" Text="Find"  Width="87px"
                                    onclick="btn_find_Click"  />
                                    <asp:Button ID="btn_update" runat="server" Text="Update"  Width="87px" onclick="btn_update_Click"
                                    />
                                <br />

                            </td>

                        </tr>

                    </table>

                </td>

            </tr>

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


code for .cs file:

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

public partial class InsertUpdateDelete : System.Web.UI.Page
{
    Service service = new Service();
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        UserDetails ud = new UserDetails();
        ud.UserName = TextBoxUserName.Text;
        ud.Password = TextBoxPassword.Text;
        ud.Country = TextBoxCountry.Text;
        ud.Email = TextBoxEmail.Text;
        string result = service.InsertUserDetails(ud);
        LabelMessage.Text = result;
    }
    protected void Buttbtn_delete_Click(object sender, EventArgs e)
    {
        UserDetails ud = new UserDetails();
        ud.UserName = TextBoxUserName.Text;
        service.DeleteUserDetails(ud);
    }
    protected void btn_find_Click(object sender, EventArgs e)
    {
        UserDetails udfind = new UserDetails();
        DataSet ds = new DataSet();
        udfind.UserName = TextBoxUserName.Text;
        ds = service.FindUserDetails(udfind);

        if (ds.Tables[0].Rows.Count > 0)

        {
            TextBoxPassword.Text = ds.Tables[0].Rows[0].ItemArray[1].ToString();
            TextBoxCountry.Text = ds.Tables[0].Rows[0].ItemArray[2].ToString();
            TextBoxEmail.Text = ds.Tables[0].Rows[0].ItemArray[3].ToString();
        }
        else
        {
            LabelMessage.Visible = true;
            LabelMessage.Text = "No such Record is available..Sorry";
        }
    }
    protected void btn_update_Click(object sender, EventArgs e)
    {
        UserDetails udupdate = new UserDetails();
        udupdate.UserName = TextBoxUserName.Text;
        udupdate.Password = TextBoxPassword.Text;
        udupdate.Country = TextBoxCountry.Text;
        udupdate.Email = TextBoxEmail.Text;
        string result = service.UpdateUserDetails(udupdate);
        LabelMessage.Visible = true;
        LabelMessage.Text = result;
    }
}

Run the code.

Encryption And Decryption

First We know what is encryption and decryption.
Encryption: It is the process of  translating plain text data in some random form and meaningless.
Decryption: It is the process of translating  encrypted data in  its original form.i.e in meaning full form that means in plain text.

what is the use of encryption and decryption.

By using this process we can hide the original data and display in junk formate so that no one can understand that what was the original.
In this I will explain how to encrypt data and save into the database and how to decrypt encrypted data and show in the gridview.

Design your aspx page like this:

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

<!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>
        Use Name:<asp:TextBox ID="TextBox1" runat="server"/><br />
        Password:<asp:TextBox ID="TextBox2"
            runat="server"></asp:TextBox>

            Encrypted Password Details:
        <asp:GridView ID="IncryptGridView" runat="server">
        </asp:GridView>
            Decrypted Password Details:<br />
            <asp:GridView ID="DecrptGridView" runat="server">
        </asp:GridView>
    </div>
    </form>
</body>
</html>

Code behind page i.e .cs page :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;
using System.Data.SqlClient;

public partial class EncryptionAndDecryprion : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection("Data Source=SUSHIL-70F1F267;Initial Catalog=sushil;Integrated Security=True");
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bindencryptGridView();
            binddecryptGridView();
        }
    }
    public void bindencryptGridView()
    {
        con.Open();
        SqlCommand com = new SqlCommand("select * from loginDetails",con);
        SqlDataAdapter da = new SqlDataAdapter(com);
        DataSet ds = new DataSet();
        da.Fill(ds);
        EncryptGridView.DataSource = ds;
        EncryptGridView.DataBind();
        con.Close();
    }
    public void binddecryptGridView()
    {
        con.Open();
        SqlCommand com = new SqlCommand("select * from loginDetails", con);
        SqlDataAdapter da = new SqlDataAdapter(com);
        DataSet ds = new DataSet();
        da.Fill(ds);
        DecrptGridView.DataSource = ds;
        DecrptGridView.DataBind();
        con.Close();
    }
    private string Encryptdata(string password)
    {
        string strpass = string.Empty;
        byte[] encode = new byte[password.Length];
        encode = Encoding.UTF8.GetBytes(password);
        strpass = Convert.ToBase64String(encode);
        return strpass;

    }
    private string DecryptData(string encryptpwd)
    {
        string strdecrypt = string.Empty;
        UTF8Encoding encodepwd = new UTF8Encoding();
        Decoder decode = encodepwd.GetDecoder();
        byte[] todecode_byte = Convert.FromBase64String(encryptpwd.Replace('0','+'));
        int charCount = decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
        char[] decodeChar=new char[charCount];
        decode.GetChars(todecode_byte, 0, todecode_byte.Length, decodeChar, 0);
        strdecrypt = new string(decodeChar);
        return strdecrypt;
    }

    protected void DecrptGridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string decryptpassword = e.Row.Cells[1].Text;
            e.Row.Cells[1].Text = DecryptData(decryptpassword);
        }
    }
    protected void submit_Click(object sender, EventArgs e)
    {
        string strpassword = Encryptdata(TextBox2.Text);
        con.Open();
        SqlCommand cmd = new SqlCommand("insert into loginDetails(user_name,password) values('" + TextBox1.Text + "','" + strpassword + "')", con);
        cmd.ExecuteNonQuery();
        con.Close();
        bindencryptGridView();
        binddecryptGridView();
    }
}

Run the code.

Friday 3 August 2012

Login Example in asp.net using c#.



First You create a table name login.
Give the column nane user_name and password.

sql query:

create table login(user_name string,password string);

after  that open visual studio 2010. File>open new website>give name >ok.

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

<!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>
         User Name:<asp:TextBox ID="TxtName" runat="server" ></asp:TextBox> 
        Password:<asp:TextBox ID="TxtPassword" runat="server" TextMode="Password"></asp:TextBox>                                           
    </div>
    </form>
</body>
</html>



default.cs







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.Data.SqlClient;
using System.Configuration;
public partial class Home : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
protected void BtnLogin_Click(object sender, EventArgs e)
    {
                string connectionInfo = ConfigurationManager.AppSettings["ConnectionInfo"];
        SqlConnection cn = new SqlConnection();
        cn.ConnectionString = connectionInfo;
        if (cn.State == ConnectionState.Closed)
        {
            cn.Open();
        }
        SqlCommand _com = new SqlCommand("select * from registrations", cn);
        SqlParameter p1 = new SqlParameter("user_id", TxtLogin.Text);
        SqlParameter p2 = new SqlParameter("user_name", TxtPassword.Text);
        _com.Parameters.Add(p1);
        _com.Parameters.Add(p2);
         //cn.Open();
            SqlDataReader _dr = _com.ExecuteReader();
            if (_dr.HasRows)
            {
                while (_dr.Read())
                {
                    Response.Redirect("HomePage.aspx");\\ Home.aspx page will open when username and password will correct.
                }
            }
          
    }
}

change the web.config file  setting as below:
 see the highlited text in red color
<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
    <appSettings>
        <add key="ConnectionInfo" value="Data Source =SUSHIL-70F1F267; Initial Catalog =sushil; Integrated Security=true"/>
    </appSettings>

    <connectionStrings>
        <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
    </connectionStrings>
    <system.web>
        <compilation debug="true" targetFramework="4.0"/>
        <authentication mode="Forms">
            <forms loginUrl="~/Account/Login.aspx" timeout="2880"/>
        </authentication>
        <membership>
            <providers>
                <clear/>
                <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/"/>
            </providers>
        </membership>
        <profile>
            <providers>
                <clear/>
                <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
            </providers>
        </profile>
        <roleManager enabled="false">
            <providers>
                <clear/>
                <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/"/>
                <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/"/>
            </providers>
        </roleManager>
    </system.web>
    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true"/>
    </system.webServer>
</configuration>
run the project.
If any problem regarding this you can contact on this blog or my email id sushil.kumar86@outloook.com

What is WCF?.

Introduction:-

Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. WCF provides a runtime environment for services, enabling you to expose CLR types as services, and to consume other services as CLR types.

WCF is part of .NET 3.0 and requires .NET 2.0, so it can only run on systems that support it.

A WCF service is made up of three parts: the service, one or more endpoints and a hosting environment.
A service is basically a class written in a .Net compliant language which contains some methods that are exposed through the WCF service. A service may have one or more endpoints – an endpoint is responsible for communication from the service to the client.
Endpoints also have three parts which are known as ‘ABC’: ‘A’ for Address, ‘B’ for Binding and ‘C’ for Contracts.
Address: Address specifies the info about where to find the service.
Binding: Binding specifies the info for how to interact with the service.
Contracts: Contracts specifies the info for how the service is implemented and what it offers.

Example:

Example for VS 2010:
open vs2010 >open new project> select wcf using c#> give the name of the project> click ok.
After that your will open.Now write some method.
For example you want to check the user name exist or not in the database.
First create a table registration which have two column user_id ,and user_name.
Fill the two column data.

when u open first time your service looks like below:
Service.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the 
class name "Service" in code, svc and config file together.
public class Service : IService
{
 public string GetData(int value)
 {
  return string.Format("You entered: {0}", value);
 }

 public CompositeType GetDataUsingDataContract(CompositeType composite)
 {
  if (composite == null)
  {
   throw new ArgumentNullException("composite");
  }
  if (composite.BoolValue)
  {
   composite.StringValue += "Suffix";
  }
  return composite;
 }
    
}
  
 after that you add method to retrieve data from database:
//this is used to get userid from database
    public DataSet GetUserId()
    {
        SqlConnection con = new SqlConnection("Data Source =SUSHIL-70F1F267; 
                Initial Catalog =sushil; Integrated Security=true");

        string cmd = "select user_name from registrations";

        SqlDataAdapter da = new SqlDataAdapter(cmd, con);

        con.Open();

        DataSet ds = new DataSet();

        da.Fill(ds);

        con.Close();

        return ds;
    }
 
Finally your Service.cs looks like:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Data;
using System.Data.SqlClient;
// NOTE: You can use the "Rename" command on the "Refactor" menu to change 
the class name "Service" in code, svc and config file together.
public class Service : IService
{
 public string GetData(int value)
 {
  return string.Format("You entered: {0}", value);
 }

 public CompositeType GetDataUsingDataContract(CompositeType composite)
 {
  if (composite == null)
  {
   throw new ArgumentNullException("composite");
  }
  if (composite.BoolValue)
  {
   composite.StringValue += "Suffix";
  }
  return composite;
 }
    //this is used to get userid from database
    public DataSet GetUserId()
    {
        SqlConnection con = new SqlConnection("Data Source =SUSHIL-70F1F267; 
       Initial Catalog =sushil; Integrated Security=true");

        string cmd = "select user_name from registrations";

        SqlDataAdapter da = new SqlDataAdapter(cmd, con);

        con.Open();

        DataSet ds = new DataSet();

        da.Fill(ds);

        con.Close();

        return ds;
    }
}
 
Now add one web form in this project.
Default.aspx
<%@ 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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div><b>Enter User Name</b>
        <asp:TextBox ID="textUserId" runat="server"></asp:TextBox>
        <asp:Button ID="getUserId" runat="server" OnClick="getUserId_Click" 
          Text="Verify" />
        <asp:Label ID="lblMessage" runat="server"></asp:Label>
    </div>
    </form>
</body>
</html>

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.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
    Service wcfService = new Service();
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void  getUserId_Click(object sender, EventArgs e)
   {
         DataSet ds = new DataSet();
        ds = (wcfService.GetUserId());
        if (ds.Tables[0].Rows.Count > 0)
        {
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                string UserId = row["user_name"].ToString();
                if (UserId == textUserId.Text)
                {
                    lblMessage.Text = "Valid";
                    break;

                }
                else
                    lblMessage.Text = "InValid";
            }
        }
    }
    
}


Run the project and test it . If any problem regarding WCF you can ask a 
question or reply me on sushil.kumar86@outlook.com.