Tracking User login Attempts Using ViewState

There was a question asked on www.asp.net forums that how can we give only 3 tries to user login. A good way is to use Database so that we can log user attempts. But if you want just a quick solution you can always use ViewState. Here is a simple code that checks for the username and if all three attempts fails than print a friendly message.
 
string userName = txtUserName.Text; 
			
			// check the viewstate 
			if(ViewState["Attempts"] != null) 
			{
				if( ( (int) (ViewState["Attempts"])   ) != 3 )
				{
					// You should get the name from the DataSource.
					if(userName.Equals("AzamSharp")) 
					{
						Response.Write("Welcome AzamSharp"); 
					}
					
					PrintAttempts();
				}
				else 
				{
					Response.Write("Sorry no more attempts. Please contact Administrator.");
				}
			}
			else 
			{
				PrintAttempts();
			}

private void PrintAttempts() 
		{
			ViewState["Attempts"] = Convert.ToInt32(ViewState["Attempts"] ) +  1;  
			Response.Write("Attempts:"+  ViewState["Attempts"].ToString() ); 
 
		}

Print | posted @ Friday, September 09, 2005 6:37 PM

Twitter