Check UserName Email Availability In Asp.Net Ajax


For this create a table Users in sql server database with ID,Uname,emlAddress columns 
and add some records in it.

Add ScriptManager,Ajax UpdatePanel on the page, and inside ContentTemplate place two textbox, two image control to display images and two label controls for related messages.

Set AutoPostBack property of textbox to true.
HTML SOURCE OF PAGE


<asp:ScriptManager ID="ScriptManager1" runat="server"/>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
UserName:
<asp:TextBox ID="txtUName" runat="server"
ontextchanged="txtUName_TextChanged"
AutoPostBack="True"/>
<asp:Image ID="imgUsr" runat="server" Visible="false"/>
<asp:Label ID="lblUsr" runat="server"/>
Email ID:
<asp:TextBox ID="txtId" runat="server"
AutoPostBack="True"
ontextchanged="txtId_TextChanged"/>
<asp:Image ID="imgId" runat="server" Visible="false"/>
<asp:Label ID="lblId" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
 
Write below mentioned code in TextChanged Event of textbox
 

C# CODE

protected void txtUName_TextChanged(object sender, EventArgs e)
    {
        if (txtUName.Text != string.Empty)
        {
            string strConnection = ConfigurationManager.ConnectionStrings
["ConnectionString"].ConnectionString;
            string strSelect = "SELECT COUNT(*) FROM Users WHERE 
Uname = @Username";
            SqlConnection con = new SqlConnection(strConnection);
            SqlCommand cmd = new SqlCommand(strSelect,con);
            SqlParameter user = new SqlParameter("@Username", SqlDbType.VarChar);
            user.Value = txtUName.Text.Trim().ToString();
            cmd.Parameters.Add(user);
            con.Open();
            int result = (Int32)cmd.ExecuteScalar();
            con.Close();
            if (result >= 1)
            {
                imgUsr.ImageUrl = "unavailable.png";
                imgUsr.Visible = true;
                lblUsr.Text = "Username not available";
                lblUsr.ForeColor = System.Drawing.Color.Red;
            }
            else
            {
                imgUsr.ImageUrl = "tick.png";
                imgUsr.Visible = true;
                lblUsr.Text = "Available";
                lblUsr.ForeColor = System.Drawing.Color.Green;
            }
        }
    }
Similarly we can check email availability by writing following code
protected void txtId_TextChanged(object sender, EventArgs e)
   {
        if (txtId.Text != string.Empty)
       {
           string strConnection = ConfigurationManager.ConnectionStrings
["ConnectionString"].ConnectionString;
            string strSelect = "SELECT COUNT(*) FROM Users WHERE emlAddress = @Email";
           SqlConnection con = new SqlConnection(strConnection);
            SqlCommand cmd = new SqlCommand(strSelect, con);
           cmd.Parameters.AddWithValue("@Email", txtId.Text.Trim().ToString());
            con.Open();
            int result = (Int32)cmd.ExecuteScalar();
           con.Close();
            if (result >= 1)
            {
               imgId.ImageUrl = "unavailable.png";
               imgId.Visible = true;
                lblId.Text = "Email already registered";
              lblId.ForeColor = System.Drawing.Color.Red;
            }
            else
           {
               imgId.ImageUrl = "tick.png";
               imgId.Visible = true;
                lblId.Text = "Available";
               lblId.ForeColor = System.Drawing.Color.Green;
            }
       }
    }

 More Details :  Live Training in jaipur


  

ExecuteScalar Example In Asp.Net C#

string strConnection = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;  string strSelect = "SELECT COUNT(*) FROM Users WHERE Username =   @Username AND Password = @Password";

SqlConnection con = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = strSelect;

SqlParameter username = new SqlParameter("@Username",SqlDbType.VarChar   ,50);
username.Value = txtUserName.Text.Trim().ToString();
cmd.Parameters.Add(username);

SqlParameter password = new SqlParameter("@Password", SqlDbType.VarChar, 50);
password.Value = txtPassword.Text.Trim().ToString();
cmd.Parameters.Add(password);

con.Open();
int result = (Int32)cmd.ExecuteScalar();
con.Close();

if (result >= 1)
Response.Redirect("Default.aspx");
else
lblMsg.Text = "Incorrect Username or Password";

 More Details :  Live Training in jaipur

How to find duplicate values in a table or sql?

With the SQL statement below you can find duplicate values in any table, just change the tablefield into the column you want to search and change the table into the name of the table you need to search.
In your recordset you will see the tablefield and how many times it is found as a duplicate.


SELECT     tablefield, COUNT(tablefield) AS dup_count

FROM         table
GROUP BY tablefield
HAVING     (COUNT(tablefield) > 1)


Some further tempering with the statement gets the complete records that are double. (yeah yeah.. no * should be used in the SELECT) It's just for demonstrating folks!!


SELECT *

FROM table
WHERE tablefield IN (
 SELECT tablefield
 FROM table
 GROUP BY tablefield 
 HAVING (COUNT(tablefield ) > 1)
)


To go even further in the process and DELETE every double record we could do something like make a temporary table, insert the double records, delete it from the original table and insert the saved single records from the temporary table. 



More Details  :  Live Training in jaipur

Only Number validation in Textbox of ASP.NET Using Regular Expression validator

Only numbers can enter into that Textbox
We can use Regular expression validator for this:

In the validation expression property keep ^\d+$.
<asp:TextBox ID="TextBox1" runat="server" Style="z-index: 100; left: 259px; position: absolute;top: 283px" ValidationGroup="check"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="Please Enter Only Numbers" Style="z-index: 101; left: 424px; position: absolute;top: 285px" ValidationExpression="^\d+$"  ValidationGroup="check"></asp:RegularExpressionValidator>

 More Details : Live Training in jaipur

What is the difference between Finalize() and Dispose()?

Dispose() is called by as an indication for an object to release any unmanaged resources it has held.
Finalize() is used for the same purpose as dispose however finalize doesn’t assure the garbage collection of an object.
Dispose() operates determinalistically due to which it is generally preferred.

More Details  : Live Training in jaipur

What is a base class and derived class?

A class is a template for creating an object. The class from which other classes derive fundamental functionality is called a base class. For e.g. If Class Y derives from Class X, then Class X is a base class.
The class which derives functionality from a base class is called a derived class. If Class Y derives from Class X, then Class Y is a derived class.

 More Details :  Live Training in jaipur

What is inheritance?

Inheritance represents the relationship between two classes where one type derives functionality from a second type and then extends it by adding new methods, properties, events, fields and constants.
C# support two types of inheritance:
·         Implementation inheritance
·         Interface inheritance
 
More Details :  Live Training in jaipur

MultiPle Inheritance

Can you use multiple inheritance in .NET?
.NET supports only single inheritance. However the purpose is accomplished using multiple interfaces.
Why don’t we have multiple inheritance in .NET?
There are several reasons for this. In simple words, the efforts are more, benefits are less. Different languages have different implementation requirements of multiple inheritance. So in order to implement multiple inheritance, we need to study the implementation aspects of all the languages that are CLR compliant and then implement a common methodology of implementing it. This is too much of efforts. Moreover multiple interface inheritance very much covers the benefits that multiple inheritance has.

 More Details :  Live Training in jaipur

What is an Interface?

An interface is a standard or contract that contains only the signatures of methods or events. The implementation is done in the class that inherits from this interface. Interfaces are primarily used to set a common standard or contract.

 More Details :  Live Training in jaipur

What are events and delegates?

An event is a message sent by a control to notify the occurrence of an action. However it is not known which object receives the event. For this reason, .NET provides a special type called Delegate which acts as an intermediary between the sender object and receiver object.

What is business logic?

It is the functionality which handles the exchange of information between database and a user interface.

What are functional and non-functional requirements?


 More Details :  Live Training in jaipur

Functional requirements defines the behavior of a system whereas non-functional requirements specify how the system should behave; in other words they specify the quality requirements and judge the behavior of a system.
E.g.
Functional - Display a chart which shows the maximum number of products sold in a region.
Non-functional – The data presented in the chart must be updated every 5 minutes.

What is Boxing/Unboxing?


 More Details :  Live Training in jaipur

Boxing is used to convert value types to object.
E.g. int x = 1;
object obj = x ;
Unboxing is used to convert the object back to the value type.
E.g. int y = (int)obj;
Boxing/unboxing is quiet an expensive operation.

What is the difference between user and custom controls?

User controls are easier to create whereas custom controls require extra effort.
User controls are used when the layout is static whereas custom controls are used in dynamic layouts.
A user control cannot be added to the toolbox whereas a custom control can be.
A separate copy of a user control is required in every application that uses it whereas since custom controls are stored in the GAC, only a single copy can be used by all applications.

 More Details :  Live Training in jaipur

what is abstract class ?


 More Details :  Live Training in jaipur

Abstract class is a class that can not be instantiated, it exists extensively for inheritance and it must be inherited. There are scenarios in which it is useful to define classes that is not intended to instantiate; because such classes normally are used as base-classes in inheritance hierarchies, we call such classes abstract classes.

Abstract classes cannot be used to instantiate objects; because abstract classes are incomplete, it may contain only definition of the properties or methods and derived classes that inherit this implements it's properties or methods.

Static, Value Types & interface doesn't support abstract modifiers. Static members cannot be abstract. Classes with abstract member must also be abstract.

how to seach data in sqlDatabase

 More Details :  Live Training in jaipur

 
CREATE PROC SearchAllTables (
@SearchStr nvarchar(100)
)
AS
BEGIN

CREATE TABLE #Results (ColumnName nvarchar(370), 
 ColumnValue nvarchar(3630))
SET NOCOUNT ON
DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), 
 @SearchStr2 
nvarchar(110)
SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
WHILE @TableName IS NOT NULL
BEGIN
        SET @ColumnName = ''
        SET @TableName = 
        (
                SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + 
 QUOTENAME(TABLE_NAME))
                FROM    INFORMATION_SCHEMA.TABLES
                WHERE           TABLE_TYPE = 'BASE TABLE'
                        AND     QUOTENAME(TABLE_SCHEMA) + '.' + 
QUOTENAME(TABLE_NAME) > @TableName
                        AND     OBJECTPROPERTY(
                                        OBJECT_ID(
                                                QUOTENAME(TABLE_SCHEMA) 
 + '.'  
+ QUOTENAME(TABLE_NAME)
                                                 ), 'IsMSShipped'
                                               ) = 0
        )

        WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
        BEGIN
                SET @ColumnName =
                (
                        SELECT MIN(QUOTENAME(COLUMN_NAME))
                        FROM    INFORMATION_SCHEMA.COLUMNS
                 WHERE      TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                    AND     TABLE_NAME      = PARSENAME(@TableName, 1)                                      
                    AND     QUOTENAME(COLUMN_NAME) > @ColumnName
                )

                IF @ColumnName IS NOT NULL
                BEGIN
                        INSERT INTO #Results
                        EXEC
                        (
                                'SELECT ''' + @TableName + '.' + 
 @ColumnName + 
 ''', LEFT(' + @ColumnName + ', 3630) 
                                FROM ' + @TableName + ' (NOLOCK) ' +
                                ' WHERE CONVERT(varchar, ' + 
 @ColumnName + ')
 LIKE ' + @SearchStr2
                        )
                END
        END     END
SELECT ColumnName, ColumnValue FROM #ResultsEND

state management


 More Details :  Live Training in jaipur

State management is the process by which you maintain state and page information over multiple requests for the same or different pages.


Types of State Management


There are 2 types State Management:

1. Client – Side State Management
This stores information on the client's computer by embedding the information into a Web page, a uniform resource locator(url), or a cookie. The techniques available to store the state information at the client end are listed down below:

a. View State – Asp.Net uses View State to track the values in the Controls. You can add custom values to the view state. It is used by the Asp.net page framework to automatically save the values of the page and of each control just prior to rendering to the page. When the page is posted, one of the first tasks performed by page processing is to restore view state.

b. Control State – If you create a custom control that requires view state to work properly, you should use control state to ensure other developers don’t break your control by disabling view state.

c. Hidden fields – Like view state, hidden fields store data in an HTML form without displaying it in the user's browser. The data is available only when the form is processed.

d. Cookies – Cookies store a value in the user's browser that the browser sends with every page request to the same server. Cookies are the best way to store state data that must be available for multiple Web pages on a web site.

e. Query Strings - Query strings store values in the URL that are visible to the user. Use query strings when you want a user to be able to e-mail or instant message state data with a URL.

2. Server – Side State Management

a. Application State - Application State information is available to all pages, regardless of which user requests a page.

b. Session State – Session State information is available to all pages opened by a user during a single visit.

Both application state and session state information is lost when the application restarts. To persist user data between application restarts, you can store it using profile properties.

Implementation Procedure



Advantages of Client – Side State Management:

1. Better Scalability: With server-side state management, each client that connects to the Web server consumes memory on the Web server. If a Web site has hundreds or thousands of simultaneous users, the memory consumed by storing state management information can become a limiting factor. Pushing this burden to the clients removes that potential bottleneck.

2. Supports multiple Web servers: With client-side state management, you can distribute incoming requests across multiple Web servers with no changes to your application because the client provides all the information the Web server needs to process the request. With server-side state management, if a client switches servers in the middle of the session, the new server does not necessarily have access to the client’s state information. You can use multiple servers with server-side state management, but you need either intelligent load-balancing (to always forward requests from a client to the same server) or centralized state management (where state is stored in a central database that all Web servers access).

Advantages of Server – Side State Management:

1. Better security: Client-side state management information can be captured (either in transit or while it is stored on the client) or maliciously modified. Therefore, you should never use client-side state management to store confidential information, such as a password, authorization level, or authentication status.

2. Reduced bandwidth: If you store large amounts of state management information, sending that information back and forth to the client can increase bandwidth utilization and page load times, potentially increasing your costs and reducing scalability. The increased bandwidth usage affects mobile clients most of all, because they often have very slow connections. Instead, you should store large amounts of state management data (say, more than 1 KB) on the server.

difference between varchar and nvarchar datatype ?

VARCHAR is an abbreviation for variable-length character string. It's a string of text characters that can be as large as the page size for the database table holding the column in question. The size for a table page is 8,196 bytes, and no one row in a table can be more than 8,060 characters. This in turn limits the maximum size of a VARCHAR to 8,000 bytes.

varchar :


Non-Unicode Variable Length character data type.
It takes 1 byte per character.
optional Parameter n value can be from 1 to 8000.Can store maximum 8000 Non-Unicode characters.
If Optional parameter value nis not specified in the variable declaration or column definition then it is considered.
If we know that data to be stored in the column or variable doesn’t have any Unicode characters.
When this optional parameter n is not specified while using the CAST/CONVERT functions, then it is considered as 30.

 

nvarchar :

UNicode Variable Length character data type. It can store both non-Unicode and Unicode (i.e. Japanese, Korean etc) characters.
It takes 2 bytes per Unicode/Non-Unicode character.
 optional Parameter n value can be from 1 to 4000.Can store maximum 4000 Unicode/Non-Unicode characters.
If Optional parameter value n is not specified in the variable declaration or column definition then it is considered as 1.
When this optional parameter n is not specified while using the CAST CONVERT functions, then it is considered as 30.

 More Details :  Live Training in jaipur

Difference between SqlDataAdapter or sqlDataReader ?


 More Details :  Live Training in jaipur

Ques.1 :  Difference between SqlDataAdapter or sqlDataReader ?
Ans  :      1.A DataReader works in a connected environment,
               whereas DataSet works in a disconnected environment.
               2.A DataSet represents an in-memory cache of data consisting of any number of inter related            DataTable objects. A DataTable object represents a tabular block of in-memory data.

DataReader – The datareader is a forward-only, readonly stream of data from the database. This makes the datareader a very efficient means for retrieving data, as only one record is brought into memory at a time. The disadvantage: A connection object can only contain one datareader at a time, so we must explicitly close the datareader when we are done with it. This will free the connection for other uses. The data adapter objects will manage opening and closing a connection for the
command to execute 

DataAdapter – Represents a set of SQL commands and a database connection that are used to fill the DataSet and update the data source. It serves as a bridge between a DataSet and a data source for retrieving and saving data. The DataAdapter provides this bridge by mapping Fill, which changes the data in the DataSet to match the data in the data source, and Update, which changes the data in the data source to match the data in the DataSet. By using it, DataAdapter also automatically opens and closes the connection as and when required.
go to more help : Web Solution In jaipur