Friday, December 9, 2011

Learn Tutorial of Asp.net Page Life Cycle




Please visit my new Web Site https://coderstechzone.com



When a user send request to the Web server, the page passes a lot of events during initialization and disposal. Generally an Asp.net aspx page contains a lot of server side controls as well as HTML controls & user controls. Most of the developer does not bother the life cycle events. But its not a good practice because to be a good & knowledgeable developer or programmer you have to learn the Life Cycle of an Asp.net aspx page. Otherwise you will be failed to get advantage specially when developing user controls. It's also a common & crucial or vital question on Asp.net interview viva or written exam.

For better understanding I have divide the Sequential loading of page cycle in two ways as follows:

1. First time request of a page
2. Postback of a page



See the initial level summary from below:

Asp.net interview question page life cycle


First time request of a page:
1. Object Initialization: Creates instance of the server control. The initialization event can be overridden using the OnInit method. The event associated with the cycle is Page_Init. In this phase the page knows the types of objects and how many to create.

2. Loading: The instance of the control is loaded onto the page object in which it is defined. In this phase you can catch the objects through Javascript like objects visibility, width, height and value. The Load event can be overridden by calling OnLoad method. The event associated with the cycle is Page_Load.

3. PreRendering: Associated value of the control is assigned. This is the last time changes of objects to save into the viewstate. After the execution of the method controls value is locked for the viewstate. The PreRender step can be overridden using OnPreRender method. The event associated with the cycle is Page_PreRender.

4. Saving: The state values of the control is saved to the viewstate.The value is attached in the HTML tag which we found in the browser view source action menu. It can be overridden by calling SaveViewState method.

5. Rendering: In this page corresponding HTML tag of the controls will be created. It can be overridden by calling OnPreRender method. The event associated with the cycle is Page_Render.

6. Disposing: At this stage the pages objects will be disposed. Basically this is the cleanup stage. Close all files, DB connections in this stage.

7. Unloading: This is the final event in the life cycle of the server control. In this phase all server control instances will be destroyed. The event associated with the cycle is Page_UnLoad.


Postback of a page:
1. Initializing: Same as before.
2. Loading View State: In this stage controls are populated with the appropriate viewstate data.
3. Loading: Same as before.
4. Loading the postback data: In this phase updates the control state with the correct postback data.
5. PreRendering: Same as before.
6. Saving State: The change of control between the current request and the previous request of the page is saved. For each change, the corresponding event is raised. For example, if the text of a textbox is changed, the new text is saved and a text_change event is raised.
7. Rendering: Same as before.
8. Disposing: Same as before.
9. Unloading: Same as before.

Hope it will help you alot for preparing ASP.net interview viva.

Wednesday, December 7, 2011

The OLE DB provider 'SQLOLEDB' was unable to begin a distributed transaction : SQL SERVER ERROR




Please visit my new Web Site https://coderstechzone.com



In many Sql Server forum i found the error "The operation could not be performed because the OLE DB provider 'SQLOLEDB' was unable to begin a distributed transaction". That's why i am decided to describe this error with a solution that i have resolved yesterday. One simple solution is Sql Server has a service named "Distributed Transaction" which you need to ON to resolve this problem. But one disadvantage of this service is it will take memory space than usual. You have another simple solution which i want to share in the later part of this article.

Full Error:
[OLE/DB provider returned message: New transaction cannot enlist in the specified transaction coordinator. ]
OLE DB error trace [OLE/DB Provider 'SQLOLEDB' ITransactionJoin::JoinTransaction returned 0x8004d00a].
Msg 7391, Level 16, State 1, Line 19
The operation could not be performed because the OLE DB provider 'SQLOLEDB' was unable to begin a distributed transaction.

Reason:
Specially i found this error when i am trying to run a dynamic query to insert data into another server like below:
DECLARE @tbl VARCHAR(8)
SELECT @tbl=CONVERT(VARCHAR(8),DATEADD(day, (DATEDIFF (day, '19800104', getdate()) / 7) * 7, '19800104'),112)

DECLARE @sql nvarchar(2000);

SET @sql='select 
 account_id,
 sum(case when account_balance >=0  and account_balance <99 then 1 else 0 end) b_0to99,
 sum(case when account_balance >=100  and account_balance <499 then 1 else 0 end) b_100to499,
 sum(case when account_balance >=500  and account_balance <999 then 1 else 0 end) b_500to999,
 sum(case when account_balance >1000  then 1 else 0 end) b_g1000
from
 sdp_dedicated_stage_'+ @tbl +'
group by account_id
order by convert(integer,account_id)'

INSERT INTO [SQLDB\SQL100].[RA_CTL_SUMMARY].[dbo].FM_DA_TREND_ANALYSIS
EXEC SP_EXECUTESQL @sql

DROP TABLE #tmpDA
Solution:
First create a table definition within the scope and insert dynamic sql returned data into this table and then insert data into the remote server or another server table like below:
DECLARE @tbl VARCHAR(8)
SELECT @tbl=CONVERT(VARCHAR(8),DATEADD(day, (DATEDIFF (day, '19800104', getdate()) / 7) * 7, '19800104'),112)

CREATE TABLE #tmpDA(account_id int,b_0to99 bigint,b_100to499 bigint,b_500to999 bigint,b_g1000 bigint)

DECLARE @sql nvarchar(2000);

SET @sql='select 
 account_id,
 sum(case when account_balance >=0  and account_balance <99 then 1 else 0 end) b_0to99,
 sum(case when account_balance >=100  and account_balance <499 then 1 else 0 end) b_100to499,
 sum(case when account_balance >=500  and account_balance <999 then 1 else 0 end) b_500to999,
 sum(case when account_balance >1000  then 1 else 0 end) b_g1000
from
 sdp_dedicated_stage_'+ @tbl +'
group by account_id
order by convert(integer,account_id)'

INSERT #tmpDA
EXEC SP_EXECUTESQL @sql

INSERT INTO [SQLDB\SQL100].[RA_CTL_SUMMARY].[dbo].FM_DA_TREND_ANALYSIS
SELECT *,@tbl FROM #tmpDA

DROP TABLE #tmpDA
If you examine the code you will found that i have created a table definition named #tmpDA then i have inserted dynamic sql returned data into the #tmpDA table, after that i have inserted #tmpDA data into the remote server [SQLDB\SQL100]. The problem has been resolved.

Activate your inactive utility folder option task manager




Please visit my new Web Site https://coderstechzone.com



Sometimes in Windows operating system we did not found some utilities like:


1. Folder Option
2. Task Manager
3. Control Panel
4. System Restore
5. Run Menu
6. Context Menu
7. My Computer
8. Search Option
9. Command Console
10. Registry Editor
11. MS Configure

This will happen due to virus attack.

Solution:
One software named Re-Enable will help you to activate inactive utility as per your requirement. Download the Re-Enable software from here.

Its a small software which size is only 773 kb. Its a portable software so no need installation. So you can use this free software in your office laptop easily.

Now open the software & select the utilities whichever you want. Now click on Re-Enable button.

Hope now your inactive utilities will be active. Its easy !!!

You can also use the software for below purposes:

1. Detecting autorun.inf virus
2. Repairing Desktop
3. Change folder attributes

Use this software like charm.

Speed up or keep active the RAM activity




Please visit my new Web Site https://coderstechzone.com



In using of Windows most of the times system creates page files which will act like virtual memory. But those virtual files may not clear automatically when you shut down the PC or Laptop which slows the RAM speed eventually. You can automatically or forcefully remove or delete the virtual files when shutting down your computer.

To do this follow the below steps:

1. Go to Start then Control Panel
2. Select Administrative Tools

3. Select Local Security Policy
4. Select Security Settings
5. Select Local Policies
6. Select Security Options
7. Go to the right hand side "Shutdown : Clear Virtual Memory Page File" & click twice on this option & enable the option
8. Now click on OK button

Now virtual files will be automatically deleted in every shutdown & your RAM speed will be increase surely.

Sometimes also do the below practice:

1. Go to RUN
2. Now type Tree
3. Press Enter

Do the above job sometimes & hope it will also increase your RAM performance.

Can not delete file Now delete file easily




Please visit my new Web Site https://coderstechzone.com



In maximum time virus or for other problems like:

1. The file is in use by another program or user
2. The source or destination file may be in use
3. Make sure the disk is not full or write-protected and that the file is not currently in use
4. Cannot delete file: Access is denied

You may not delete a file easily. For such type of problem the shortest solution is "FileASSASSIN". FileASSASSIN is a free software which you can download from here. Now install it in your system. To delete a file open the software first then choose the problematic file through Browse button or drop the file using mouse. Now if you directly delete the file then checked the "Delete File" option. Else if you want to keep the file but want to keep the file inactive then do not check the option "Delete File" option. At last click on Execute button. Hope now your problem will be resolved. The snapshot of FileAssassin is given below:

This file is used by another program or user


Solution no 2:
1. Start Task Manager
2. Click on Processes Tab
3. Select Explorer.exe

Make sure the disk is not full or write-protected

4. Click on "End Process" - Now your every window will be closed
5. Do not close the Task Manager
6. Now click on File-->New Task (Run..)
7. Now write "Explorer" on Open: input box
8. Now click on OK
9. Now one window is open - browse the problematic file and delete the file normally

Hope your problem will be resolved.

Tuesday, May 17, 2011

Make Regular Expression Checker in 10 minutes using Asp.net C#




Please visit my new Web Site https://coderstechzone.com



In most of the times we need to make or create a regular expression to find matching patterns from a given string or a file. Many languages support this feature like Javascript and also Asp.net C#. Regular expresion makes our life easy. Few days ago i have done a dataminig project where i found that how much necessary the regular expression is. I understand its power and capability. The developer who wants to learn regular expression then first gather some knowledge on regular expression and then use this easy and simple tool to test the pattern matches.It will definitely increases your confidence as well as skills on Regular Expression. So the regular expression example in back & forth.

The output looks like:
Regular Expression Checker

Design the UI in the following way:
<table border="0">
        <tr>
            <td>Regular Expression: </td><td><asp:TextBox ID="txtExp" runat="server" Width="200px"></asp:TextBox></td>
        </tr>
        <tr>
            <td>Contents: </td><td><asp:TextBox ID="txtContent" runat="server" Columns="40" TextMode="MultiLine" Rows="5"></asp:TextBox></td>
        </tr>
        <tr>
            <td>Result: </td><td><asp:TextBox ID="txtResult" runat="server" Width="200px"></asp:TextBox></td>
        </tr>
        <tr>
            <td></td><td><asp:Button ID="cmdExecute" runat="server" Text="Execute" OnClick="cmdExecute_Click" /></td>
        </tr>
    </table>
Now under Execute button click event write the following server code:
protected void cmdExecute_Click(object sender, EventArgs e)
    {
        string content = txtContent.Text;
        string pattern = txtExp.Text;
        MatchCollection mc = Regex.Matches(content, pattern);
        string sWord = "";
        if (mc.Count > 0)
        {
            for (int i = 0; i < mc.Count; i++)
            {
                if (sWord.Length == 0)
                    sWord = mc[i].Value;
                else
                    sWord =sWord+ ","+ mc[i].Value;
            }
        }
        txtResult.Text = sWord;
    }
Hope now you can test regular expressions in many different ways.

Wednesday, May 11, 2011

Create generate on the fly JQuery dynamic content




Please visit my new Web Site https://coderstechzone.com



In many cases developers need to add dynamic contents in a DIV. In my lattest project i have done a critical job. In this post i am sharing just a simple example on how to add dynamic contents in a DIV. By following this example you can generate on the fly dynamic contents, controls like Button, Link etc. The output look like below:

Jquery Dynamic Content



To do this fisrt add an asp.net aspx page. Then paste the below code under body tag:
<asp:Button ID="Button1" runat="server" Text="Add Dynamic Contents" />
    <div id="divDynamic">
    </div>
Now under head tag paste the below JQuery code:
<script type="text/javascript">
        $(document).ready(function() {
            $("#Button1").click(function() {               
                $("#divDynamic").append("<b>This is a dynamic content--JQUERY</b></br>");
                return false;
            });
        });
    </script>

The complete code will be:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Dynamincontents_jquery.aspx.cs" Inherits="Dynamincontents_jquery" %>

<!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>Jquery to add dynamic contents in a DIV</title>
    <script src="Script/jquery.js" type="text/javascript"></script>
    
    <script type="text/javascript">
        $(document).ready(function() {
            $("#Button1").click(function() {               
                $("#divDynamic").append("<b>This is a dynamic content--JQUERY</b></br>");
                return false;
            });
        });
    </script>
        
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    <asp:Button ID="Button1" runat="server" Text="Add Dynamic Contents" />
    <div id="divDynamic">
    </div>
    
    </div>
    </form>
</body>
</html>
Now hope one can generate dynamic contents by using JQuery power script.

Sunday, March 27, 2011

Validate XML aganist an XSD in Asp.Net C#




Please visit my new Web Site https://coderstechzone.com



Most of the times when we are working with XML we need to validate the XML file from an XSD file. Here i am showing an code example how one can validate XML file using an XSD in Asp.Net C#.

To do that add an aspx page in your project.











Now under Page_Load event write the below code:
using System;
using System.Xml;
using System.Text;
using System.Xml.Schema;

public partial class Validate_XML_XSD : System.Web.UI.Page
{
    private StringBuilder sB = new StringBuilder();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string xmlPath = MapPath("MenuXML.xml");
            string xsdPath = MapPath("MenuXML.xsd");

            XmlReaderSettings settings = new XmlReaderSettings();
            settings.ValidationType = ValidationType.Schema;
            settings.Schemas.Add(null, XmlReader.Create(xsdPath));

            XmlReader Oreader = XmlReader.Create(xmlPath, settings);
            XmlDocument Odoc = new XmlDocument();
            Odoc.Load(Oreader);
            ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);

            Odoc.Validate(eventHandler);
            if (sB.ToString() == String.Empty)
                Response.Write("Validation completed successfully.");
            else
                Response.Write("Validation Failed: " + sB.ToString());
        }
    }

    public void ValidationEventHandler(object sender, ValidationEventArgs args)
    {
        sB.Append("Error: " + args.Message);
    }  
}

Hope now you can validate XML file easily.

Creating XSD file from an XML file in Asp.Net within few seconds




Please visit my new Web Site https://coderstechzone.com



There are a lot of tools in the internet you will get to create XSD file from an XML file but you need to download then install or may be convert on-line. But there is good news that Asp.Net has built in menu to create XSD file from an XML file.













To do that first write the below XML file in VisualStudio:
<?xml version="1.0" encoding="utf-8" ?>
<Home>
  <Menu text="Books" url="MenuFromXml.aspx">
    <SubMenu text="Asp.Net" url="MenuFromXml.aspx"></SubMenu>
    <SubMenu text="Ajax" url="MenuFromXml.aspx"></SubMenu>
    <SubMenu text="MS SQL Server 2005" url="MenuFromXml.aspx"></SubMenu>
    <SubMenu text="JavaScript" url="MenuFromXml.aspx"></SubMenu>
  </Menu>
  <Menu text="Electronics"  url="MenuFromXml.aspx">
    <SubMenu text="Camera" url="MenuFromXml.aspx">
      <SubMenu text="Digital" url="MenuFromXml.aspx">
        <SubMenu text="Canon" url="MenuFromXml.aspx"></SubMenu>
        <SubMenu text="Kodak" url="MenuFromXml.aspx"></SubMenu>
        <SubMenu text="Sony" url="MenuFromXml.aspx"></SubMenu>
        <SubMenu text="Casio" url="MenuFromXml.aspx"></SubMenu>
        <SubMenu text="Fuji" url="MenuFromXml.aspx"></SubMenu>
      </SubMenu>
      <SubMenu text="Film Camera" url="MenuFromXml.aspx"></SubMenu>
    </SubMenu>
    <SubMenu text="DVDs" url="MenuFromXml.aspx">
      <SubMenu text="Comedy" url="MenuFromXml.aspx">
        <SubMenu text="English" url="MenuFromXml.aspx"></SubMenu>
        <SubMenu text="French" url="MenuFromXml.aspx"></SubMenu>
        <SubMenu text="German" url="MenuFromXml.aspx"></SubMenu>
        <SubMenu text="Spanish" url="MenuFromXml.aspx"></SubMenu>
      </SubMenu>
      <SubMenu text="Kids Movies" url="MenuFromXml.aspx"></SubMenu>
      <SubMenu text="Romance Movies" url="MenuFromXml.aspx"></SubMenu>
      <SubMenu text="Action Movies" url="MenuFromXml.aspx"></SubMenu>
    </SubMenu>
  </Menu>
  <Menu text="Contact Us" url="MenuFromXml.aspx"></Menu>
</Home>

Now you found a menu named "XML" in VS Main menu. View:

Now click on Create schema will create the below XSD file:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Home">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" name="Menu">
          <xs:complexType>
            <xs:sequence minOccurs="0">
              <xs:element maxOccurs="unbounded" name="SubMenu">
                <xs:complexType>
                  <xs:sequence minOccurs="0">
                    <xs:element maxOccurs="unbounded" name="SubMenu">
                      <xs:complexType>
                        <xs:sequence minOccurs="0">
                          <xs:element maxOccurs="unbounded" name="SubMenu">
                            <xs:complexType>
                              <xs:attribute name="text" type="xs:string" use="required" />
                              <xs:attribute name="url" type="xs:string" use="required" />
                            </xs:complexType>
                          </xs:element>
                        </xs:sequence>
                        <xs:attribute name="text" type="xs:string" use="required" />
                        <xs:attribute name="url" type="xs:string" use="required" />
                      </xs:complexType>
                    </xs:element>
                  </xs:sequence>
                  <xs:attribute name="text" type="xs:string" use="required" />
                  <xs:attribute name="url" type="xs:string" use="required" />
                </xs:complexType>
              </xs:element>
            </xs:sequence>
            <xs:attribute name="text" type="xs:string" use="required" />
            <xs:attribute name="url" type="xs:string" use="required" />
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

Wow done wthin few seconds.

Bind DataSource into DataList example in Asp.Net




Please visit my new Web Site https://coderstechzone.com



The DataList control is a standard control of Asp.Net like others. It is used to display repeated list of data or items. You can bind any datasource in this DataList control like DataTable, SqlDataReader and XML etc. In most e-commerce site use DataList control to display products insted of repeater control. Here in this example i will show you how one can bind data to DataList control in runtime.

Table snapshot that we bound to the control:
DataList table structure


Now add an Aspx page in your project and write the below HTML markup code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataList.aspx.cs" Inherits="DataList" %>

<!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>DataList DataBinding Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DataList id="DataList1" runat="server">
            <ItemTemplate>
                Title: 
                <asp:Label id="Label6" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Title") %>'></asp:Label>
                <br />
                Published: 
                <asp:Label id="Label7" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Published") %>'></asp:Label>
                <br />
                Modified: 
                <asp:Label id="Label2" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "ModifedDate") %>'></asp:Label>
            </ItemTemplate>
            <HeaderTemplate>
                <asp:Label id="Label1" runat="server" Font-Names="Tahoma" Font-Italic="True">List of Articles:</asp:Label>
                <hr />
            </HeaderTemplate>
            <FooterTemplate>
                <hr />
            </FooterTemplate>
            <SeparatorTemplate>
                <hr />
            </SeparatorTemplate>
        </asp:DataList>    
    </div>
    </form>
</body>
</html>

Now under Page_Load event write the below server side code:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataList1.DataSource = PopulateData();
            DataList1.DataBind();
        }
    }

    public SqlDataReader PopulateData()
    {
        string conStr=@"Data Source=.\SQLExpress;Initial Catalog=TESTDB;User Id=sa;Password=Comm!pass@1;";
        SqlConnection Conn = new SqlConnection(conStr);
        string sQuery="SELECT * FROM Article";
        SqlCommand sqlCommand = new SqlCommand(sQuery, Conn);
        Conn.Open();
        SqlDataReader dataReader=sqlCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
        return dataReader;
    }

Dont forget to add the "using System.Data.SqlClient;" namespace.

Now run the project & hope you will get below output:
DataList output
Hope now you bound the DataList control to display repeated data.

Wednesday, March 23, 2011

Center middle the content of a DIV based web page




Please visit my new Web Site https://coderstechzone.com



When browsing we found a lot of website midle centered. The question is how developer doing this. In forums i found many times this question. Its simple and easy to middle the content for div based design. To do that wrap up all div in one div and then apply some CSS to middle or center the web page.
I want to make the below example:











To do that add an aspx page in your project. Then add the below stylesheet/CSS under head HTML tag:
<style type="text/css">
        #main_container {width: 760px;margin:auto}
        #content
            {
                background-color:gray;
                font-weight:bold;
                color:White;
            }
    </style>

Now write the below code under BODY tag:
<form id="form1" runat="server">
        <div id="main_container">
            <div id="content">
                Main Body Here
            </div>
        </div>    
    </form>

Now run the page. Hope you found your content in middle or center of the browser.

Tricks for URL Rewriting using Request.PathInfo in Asp.Net




Please visit my new Web Site https://coderstechzone.com



To publish cleaner URL in your Asp.Net application you can use URL Rewriting. The most popular reason for URL Rewriting is let you have implemented pages based on query string like http://yourdomain/product.aspx?Brand=Lux. But now you want to change the URL to http://yourdomain/product.aspx/Lux for SEO purpose. There is a lot of way to implement this. One of the easy trick is you can achieve URL Rewriting by using Request.PathInfo of Asp.Net. Mind it this is not the best way for a huge site because this technique requires some of coding which is error prone. One another thing that if you have 10 brands & you use query string to populate Brand related product then google will index only one url but if you use URL like http://yourdomain/product.aspx/Lux then google will treat all ten individual pages. Nice thing am i right? Another reason for URL Rewriting is to server the pages those users have bookmarked old query string URL's. Let’s move for implementation. To do that first add a page in your project and named it BrandList.aspx.



Add a button in this page and write the below code under button click event:
Response.Redirect("Product.aspx/Lux");

Now add another page and name the page product.aspx. Now write the following server side code:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Response.Write("Brand=" + GetBrand());
            // Now you can do anything sinch you have got the BrandName
        }
    }

    public string GetBrand()
    {
        if (Request.PathInfo.Length == 0)
            return Request["Brand"];
        else
            return Request.PathInfo.Substring(1);
    }

Now run the BrandList page and click on the button. Check your browser address you will find a SEO friendly URL. The previous bookmark users also get your product list.

Monday, March 21, 2011

Check user name login name email address availability using jquery ajax in Asp.Net page




Please visit my new Web Site https://coderstechzone.com



In most registration page we need to check the availability of user name or email address using Jquery/Ajax. Because it will be hectic job for user to rewrite the data after getting post back error that user name already taken or email address already taken. So it would be very helpful for user if he can check his name or login name or email address availability in time without losing any data. To do that in this article i will show you GMAIL like feature by using Jquery & Asp.Net Ajax. The test output screen look like this:

Check login Name Availability

Now add a handler by right clicking on solution name. Then click on Add New Item and then select Generic Handler. Name the handler to "user_Login.ashx".
Write the below code within the handler:
using System;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;

public class user_Login : IHttpHandler 
{
    
    public void ProcessRequest (HttpContext context) 
    {
        string user_name = context.Request["user_name"];     
        string output = "";
        output = CheckAvailability(user_name);
        context.Response.Write(output);
        context.Response.End();
    }

    public string CheckAvailability(string user_name)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString);
        con.Open();
        SqlCommand com = new SqlCommand("Select User_Name from tblUsers where User_Name=@Name", con);
        com.Parameters.AddWithValue("@Name", user_name);
        string uName = (string)com.ExecuteScalar();
        con.Close();
        if (uName != null)
            return "1";
        else
            return "0";
    }
    
    public bool IsReusable 
    {
        get {return false;}
    }
}

Now add an aspx page & write the below HTML code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Check_USER_EMAIL.aspx.cs" Inherits="Check_USER_EMAIL" %>

<!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>Check user or email address availability</title>
    <script src="Script/jquery.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(function() {
        $("#cmdCheck").click(function() {
        $.post("user_Login.ashx", { user_name: $("#<% =txtName.ClientID %>").val() }, function(output) {
        if (output == "1") 
        {                    
            $("#dv_Ajax_Response").html("Name already exist!");
        }
        else{                    
            $("#dv_Ajax_Response").html("Still available");
            }

        });
        });
    });

</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
    <input type="button" id="cmdCheck" value="Available?" />
    <div id="dv_Ajax_Response" style="color:Red;font-weight:bold"></div>
    </div>
    </form>
</body>
</html>

Now run the page. Hope you can now check the availability of user name or user login or email address before submit the full registration page.
Want To Search More?
Google Search on Internet
Subscribe RSS Subscribe RSS
Article Categories
  • Asp.net
  • Gridview
  • Javascript
  • AJAX
  • Sql server
  • XML
  • CSS
  • Free Web Site Templates
  • Free Desktop Wallpapers
  • TopOfBlogs
     
    Free ASP.NET articles,C#.NET,VB.NET tutorials and Examples,Ajax,SQL Server,Javascript,Jquery,XML,GridView Articles and code examples -- by Shawpnendu Bikash