I want to do some action if button clicked for 3 times. Just like if users enters a wrong password for 3 times the page the page must be redirected to another page or something.
How to do action in ASP.NET C# if button clicked for 3rd time?
To check if a user has taken an action fox "x" times you need to store it somehwere. If you're using a relation database you could for example call a table LoginAttempts and there you store all unsuccesfull logins. When you have that table you can build your logic against it.
I'd use a session variable.
Another solution could be having a column in the users table named LoginAttempt(int)(default 0), how I would use that column is
Let's say you have a table in your databese called TblUsers with these columns
Id,
UserName,
Password,
LoginAttempt.
And let's say you have two TextBoxes on your Login.aspx page
TextBoxUserName,
TextBoxPassword.
Let's say you have one record in your TblUsers like this
Id : 1
UserName : rammstein
Password : ohnedich
LoginAttempt : 0
Now, you are in your Login.aspx.cs code
you have a method and in it you have
TblUsers user = new TblUsers();
And you have a bool login = false;.
You've got the username from TextBoxUserName.Text, you check if a user with this username exists then if it exist you do the below code.
Let's follow this scenerio
The given user tried to login with
UserName:rammstein
Password:duhast
Checked your database with username rammstein and found it, and took that record in your TblpUsers user then you checked whether user.Password and TextBoxPassword.Text matches.Well it won't match for the above example because
user.Password is ohnedich however TextBox.Password is duhast.This means the login is not successfull so you set false to your bool login.
Everything else belongs to the below code with if-else condition
if(user.LoginAttempt < 3){
if(!login)
{
user.LoginAttempt = user.LoginAttempt + 1;
}
else
{
user.LoginAttempt = 0;
}
}
else
{
//do something
}
Multiple solutions:
1) Session variable (Okay solution)
2) Static class variable (Not a good solution)
3) DB record field (Best solution)
4) Pass flag variable back and forth between view and controller (not a very good idea).
5) Browser cookie (can be cleared)
Related
I have a users table in my sql server 2008 which has
username, password, email,first name, last name and user group.
I want to display my website controls specific to that user groups once the user logs in.
Could you please help in this issue.
You can assign user's user group is a session variable at the time of log in. Now you can set (may be on page_load) your pages's controls visibility upon that value.
Something like this,
If(Session["UserGroup"] == "1")
{
ControlID.Visible = true;
}
else
{
ControlID.Visible = false;
}
I have a table named users two of it's fields are login and name.
These fields can not be duplicate.
When the user are going to create a new registration, I already made a method to check if that name/login already exists or not.
But the user can also edit his login/name.
When the user enters on the page to edit his registration data, it already fills the fields with the current data.
I have 3 fields [NAME] [EMAIL] [LOGIN].
The user can edit only 1 of this or all of them at once ...
How may I create a method to check if that name/loginalready exists or not when he try to edit it ? Maybe a Query ? A select count on the login then on the name field ?
--UPDATE--
here's my solution
You should leave this up to the database system you are using and handle any errors it may throw. All database systems (Access, Oracle, MS SQL, etc) allow you to mark a table field as being Unique. This means that the table can only hold one records with a field(s) with that value. If you try to add more than one record with a same field, you will be thrown an error. Your application should catch that error and alert the user. If you post what kind of database system you are using I can show you how to do this.
Edit:
Heres is an example. This uses the SqlClient.SqlException exception class. I'm not sure what the error code is for unique constraints but I added a variable in the catch that you can place a break point on to get. Just change the if statement to match that error code:
Try
'your database insert attempt here
Catch ex As SqlClient.SqlException
Dim sqlErrorNumber = ex.ErrorCode
If (sqlErrorNumber = 1) Then
Me.lblWarning.Text = "Please select a unique ID"
Me.lblWarning.Visible = True
Me.lblWarning.ForeColor = Drawing.Color.Red
Me.lblWarning.Font.Bold = True
End If
End Try
In the aspx page:
<asp:Label ID="lblWarning" runat="server" Visible="false"></asp:Label>
What is your primary key here?
I suggest, Adding new identity column to your table will solve the issue.
You can edit the row based on the identity column.
For Ex: Add [UserID] field and made it unique identity column. then perform update operations based on userid in where clause.
You should use unique fields in your database, try catch in php or asp and ajax technique to get sure that the fields are filled or not with the informations that are you typing now.
if you don't have a column ID or if username column is not set like UNIQUE you can use this function :
function user_exists($username){
$username = sanitize($username); // sanitize
return(mysql_result(mysql_query("SELECT COUNT(user_name) FROM user_table WHERE username = '$username'"), 0) == 1) ? true : false;
}
For New Members / Or if current User wants to edit his username
this function return false if username is not registered and true if it is
I've written a simple code to keep a USerID with the help of session. However I can't get Session value although it's not null. I've done exactly the way microsoft official tutorial says. Here's the code:
The code on the Default.aspx
string regCode = loginBase.getRegCodePerUser(txtLogin.Text);
Session["regCode"] = regCode;
//lblInfo.text=(string)Session["regCode"];When I check it shows the right string.It's OK
Response.Redirect("Selection.aspx");
I do not directly go to that page.I first go to Selection.aspx, then UpdateStages.
And this is the code on the other page(UpdateStages.apsx):
if ((string)Session["connSTR"] == null && (string)Session["user"] == null)
{
Response.Redirect("Default.aspx");
}
else if ((string)Session["regCode"]!=null)
{
regCode=(string)Session["regCode"];
lblInfo.Text = regCode;//Show nothing. Empty.
}
It might very well be that when you set the session variable:
Session["regCode"] = loginBase.getRegCodePerUser(txtLogin.Text);
That the username is not available yet and that is why it's returning an empty string, and I would assume that you are executing this code: lblStatus.Text =loginBase.getRegCodePerUser(txtLogin.Text); on a different page/after the user has logged in and that is why you get the value in the label when you assign it directly.
Put a breakpoint on where you set the Session variable and see if the value is being set.
Otherwise your session settings could be incorrect in your web.config which causes the session values to be cleared before you get to your second page where you are accessing it.
i'm new to ASP.NET,so plz b patient :D
i want to redirect one of my pages to the other one,and i keep the username!
i tried to use session.add and session[],but when i want to insert the username inside the brackets,it says use must int!!!but i thought i should use session["username"]
i used another way(request.querystring[]),but both have problems
here is my code
//first solution
string username="asal";
session.Add(username,username);
Response.Redirect("~/Doctor/DoctorsMainPage.aspx");
//in the other page
Label1.Text= Session["username"].ToString();//this one says use int?!
//i used this one instead of it
Label1.Text= Session[0].ToString();//with this one i get the username in other page,but one i want to pass another string like "id" with session,I can not!
//the second solution
string username="asal";
Response.Redirect("~/Doctor/DoctorsMainPage.aspx?username");
Label1.Text = Request.QueryString["username"];//this one redirect to doctors main page but set the value of username to "" !
session.Add(string, string) where the first string is the name of the variable and the second is the value.
You are adding the value twice.
//first solution
string username="asal";
session.Add("username",username); <-- this is your problem
Response.Redirect("~/Doctor/DoctorsMainPage.aspx");
//in the other page
Label1.Text= Session["username"].ToString();
Now, as for
//the second solution
string username="asal";
Response.Redirect("~/Doctor/DoctorsMainPage.aspx?username");
Label1.Text = Request.QueryString["username"];//this one redirect to doctors main page but set the value of username to "" !
In this case you're creating a url "~/Doctor/DoctorsMainPage.aspx?username"
Ok - so what is username? The code is looking for a param in the query string named username but it's not finding a value.
You need:
Response.Redirect("~/Doctor/DoctorsMainPage.aspx?username="+username);
That will give you "~/Doctor/DoctorsMainPage.aspx?username=asal"
string username = "asal";
Session["username"] = username;
Response.Redirect("~/Doctor/DoctorsMainPage.aspx");
//Other page
Label1.Text = Session["username"].ToString().Trim();
You have to add the session like..
session.Add("username",username); instead session.Add(username,username);
And then you can access the value like..Label1.Text= (String)Session["username"];
Check out this article related to the session State ASP.NET Session State Overview that will help you to understand Session State management.
Seconly querystring should be like, as you have not passing your string parameter and it should be like...
Response.Redirect("~/Doctor/DoctorsMainPage.aspx?username=" + username);
How to Create a Login, Signup and after user Login then loggedin username will be dispalyed in every page using Label with out using login control and create userwizard
I have following Field in My Table1
ID Username Email id Password
1 dobriyal dd#d.com ssssss
2 manish tt#d.com ttreter
i want to create login in sumit.aspx page using Textbox1 and textbox2 and button ...when user eneter emailid in textbox1 and password in textbox2 then if userfind in database according to the emailid and password entered in textbox1 and textbox2 .... then loggedin username will be displayed in label1 of each page ...where i have label 1 on page ///
means .... if i have label1 on Default.aspx, myname.aspx, defaul2.aspx then in each page the label1 text would be loggedin username .....till they loggedit its session ...
How to do it using Vb.NET
Remember I dont wanna use default login & createuserwizard, login status and login name control of ASp.NET ...
Answer of your question is very broad. So instead of code i am giving you the algorithm.
1. Create a method that will check the supplied user name and password in your data layer file.
E.g. bool IsAuthenticatedUser(). Inside this method run Command.ExecuteScalar. Here is query "
Declare #Count =(Select Count(*) From Login
Where UserName = #UserNAme and Password = #Password)
Select #Count;
-- Assuming u r using Sql Server 2008
2. Now in your IsAuthenticated Method check if the returned value is one then return true else false. Something like this
int count = (int)command.ExecuteScalar();
If (count ==1)
{
return true;
}
return false;
3. On the UI check the value returned by the method. If its true redirect the user to its page. And set session. For displaying name email id on page,
After the success of IsAuthenticated method, Create another method that will select your desired entities from database and fill it in datatable.
Something like this
If(IsAuthenticatedUser(username, password))
{
Datatable dt = GetUserDetails(username,password);
If(dt!=null)
{
if(dt.rows.count >0)
{
// here there is only one row so you can use index [0] also
foreach(DataRow dr in dt.rows)
{
Session["UserName"] = dr["UserName"].tostring();
Session["Email"] = dr["Email"].tostring();
}
}
}
Now on the desired page check if the both sessions are not null , then set the value at desired label.
If (Session["UserName"]!=null && Session["Email"]!=null)
{
lblUserName.Text = "Welcome " + Session["UserName"].ToString();
lblEmail.Text = Session["Email"].tostring();
}
**Here userName and password parameter will be the value passed from the textbox.
string username = txtUserName.text.trim();
string password = txtPassword.text.trim();
Also you to put validations before accepting input from users, as this may result in sql injection and exposing of your entire database. but for home purpose you can do this.**
See Update:
For displaying name on every page Create a master page and add the two labels on that. For adding master page , from context menu Add New Item -> MasterPage. Now in source view add table as per your need. Also there is ContentPlaceholder , do not add inside that tag. That is the space to display the other child pages. in the master page load event use the label = session code to set the name. Also there add a link button , in its click event use
Session.Abandon();
Response.Redirect("~/Login.aspx?Logout=1");
-> i have added a new thing ?Logout called query string , used for passing values from one page to another. Here i am using Login =1 that means I can know ia m on login page because i logged out myself.