LoginView Not Updating After User Login - asp.net

I'm using ASP.NET Membership in order to manage a website users. But without using the specific 'Login Controls'. Actually, just applying Membership class methods in order to Create a user account and also to User login.
On the other hand, there is a LoginView control in Site.Master which is responsible to 'Welcome Username' task.
The problem is that, the LoginView control isn't updated after creating new account or any login.
Do I have to Definitely use the specific login controls?
----Also, I have set the Login Button CommandName to 'Login'!
----Should I set something like that for Create User Button?
I would appreciate any help...
The following is my code for login:
if (!Membership.ValidateUser(HttpUtility.HtmlEncode(txtUserName.Text), HttpUtility.HtmlEncode(txtPass.Text)))
{
lblResult.Text = "Invalid user name and password.";
lblResult.Visible = true;
}
else
{
Response.Redirect("~/Default.aspx");
}
And here the registration code:
MembershipCreateStatus statusUser;
try
{
Membership.CreateUser(HttpUtility.HtmlEncode(txtUserName.Text), HttpUtility.HtmlEncode(txtPass.Text), HttpUtility.HtmlEncode(txtEmail.Text), ddlSexQues.SelectedValue != "-1" ? ddlSexQues.Text : string.Empty, txtSecAnsw.Text == string.Empty ? string.Empty : txtSecAnsw.Text, true, out statusUser);
txtEmail.Text = string.Empty;
txtPass.Text = string.Empty;
txtRepass.Text = string.Empty;
txtSecAnsw.Text = string.Empty;
txtUserName.Text = string.Empty;
ddlSexQues.SelectedValue = "-1";
lblRsl.ForeColor = Color.Green;
lblRsl.Text = "حساب کاربری شما با موفقیت ایجاد شد.";
lblRsl.Visible = true;
}
catch (MembershipCreateUserException error)
{
lblRsl.Text = GetErrorMessage(error.StatusCode);
lblRsl.Visible = true;
}

If you're using your own login code, you'll need to persist the user's authentication information, for instance by adding a cookie to the response. The built-in controls do this automatically.
I'm assuming you're using Forms-based authentication. There's a reference to the .NET security class for Forms auth here, which details what options are available to you:
http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication%28v=vs.100%29.aspx
Look at the SetAuthCookie and RedirectFromLoginPage methods in particular.
As far as I'm aware, the CommandName property is for distinguishing between Button controls in code. As you're using your own methods to handle user creation, I don't think you need to add it to your own control. More here:
http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication%28v=vs.100%29.aspx

Related

Set and Get the Cookies in ASP.NET web forms

The cookies in Asp.net are killing me! This is my Code:
set the cookie:(Upload is an asp:FileUpload control for uploading image)
HttpCookie cookie = new HttpCookie("WorkingImage", Upload.FileName.ToString());
cookie.Expires = DateTime.Now.AddDays(3);
HttpContext.Current.Response.Cookies.Add(cookie);
and this is the way I get it:
if (HttpContext.Current.Request.Cookies["WorkingImage"] != null && HttpContext.Current.Request.Cookies["WorkingImage"].Value.ToString() != "")
{ //....}
cookie value is "" when I run the project .
Is there any help?(please note that in other pages cookies can set and will got correctly)
Here is an example where we save a WorkingImage name in cookie
HttpCookie cookie = new HttpCookie("WorkingImage");
cookie.Value = Upload.FileName.ToString(); // Upload is an asp:FileUpload control name for uploading image
cookie.Expires = DateTime.Now.AddHours(3);
Response.SetCookie(cookie);
Here is example for accessing our cookie and check for the cookie :
if(Request.Cookies["WorkingImage"] != null)
{
var cookieValue=Request.Cookies["WorkingImage"].Value;
}
If you are using within handler inherit:
System.Web.SessionState.IRequiresSessionState
Like this:
public class Handler : IHttpAsyncHandler, System.Web.SessionState.IRequiresSessionState
For more cookies tutorials in asp .net visit this.

session variable for username

Hey I am creating a forum where users can login and post ocmments in a forum, I want the username as a session variable so I can get it when they post a comment and insert the username in the db and also to display a hello user message.
Below is my login code:
protected void Button1_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
localhost.Service1 myws = new localhost.Service1();
ds = myws.GetUsers();
foreach (DataRow row in ds.Tables[0].Rows)
if (txtusername.Text == System.Convert.ToString(row["username"]) &&
txtpassword.Text == System.Convert.ToString(row["password"]))
{
System.Web.Security.FormsAuthentication.RedirectFromLoginPage(txtusername.Text, false);
}
else
Label3.Text = "Invalid Username/Password";
}
Do I declare the session variable here?
Like:
Session["username"] = "username";
Also not sure what to type to get the value username from the db
Thanks
You don't need to use a session. Once you call the FormsAuthentication.RedirectFromLoginPage method, inside the target page you could access the currently connected user from the authentication cookie that was emitted by this method using User.Identity.Name.
protected void Page_Load(object sender, EventArgs e)
{
if (User.Identity.IsAuthenticated)
{
string username = User.Identity.Name;
// ...
}
}
To learn more about how Forms Authentication works in ASP.NET I invite you to read the following article.
You are already using forms authentication (FormsAuthentication.RedirectFromLoginPage(txtusername.Text, false)) which is great. Consequently, you don't need to store the username is session as it's already available via User.Identity.Name, as Darin noted.
I have written two tutorials on forms authentication you might find useful:
An Overview of Forms Authentication
Forms Authentication Configuration and Advanced Topics
Additionally, consider using Membership. Membership is a subsystem built into ASP.NET that handles user accounts and provides an API for creating accounts, deleting accounts, etc. In short, you don't have to write all that code yourself. And with the login Web controls, creating new accounts, signing users in, resetting passwords, and so on, are all quite simple and involve zero to little code. For more information see my Membership tutorials.
Happy Programming!

How to provide different pages on login for different users?

I'm working on web application which has a database
UserName|Password|UserType
Anil|Anil|Manager
ghouse|Ghouse|Admin
raghu|raghu|User
Now my task is to provide each user their own page on login...They all have a same login page.
I tried this code it's working fine for two users. What to do if I have more than two users?
SqlConnection con = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DebitCareBankApp;Data Source=SSDEV7-HP\\SQLEXPRESS");
string cmdStr = "select LoginType from Login where UserName='" + TxtUsername.Text + "' AND Password = '" + TxtPassword.Text + "'";
SqlCommand cmd = new SqlCommand(cmdStr, con);
con.Open();
Object TypeUser = cmd.ExecuteScalar();
con.Close();
if (TypeUser != null)
{
LblError.Visible = false;
LblError.Text = "";
if (TypeUser.ToString() == "Manager")
Response.Redirect("~/CallingAgents/CallingAgents_Login.aspx");
else
Response.Redirect("~/UserRegistrationForm.aspx");
}
else
{
LblError.Visible = true;
LblError.Text = "Invalid Credentials Entered, Try again";
}
I think you should create a common class where insert your user type on successful login.
In that common class redirect it to respective page.
On successful login:
Response.Redirect(clsCommon.GetDefaultPage(userType));
your commaon class code:
public static string GetDefaultPage(string userType){
//Default Redirects
Dictionary<string, string> userInfo = new Dictionary<string, string>(){
{"Manager","~/ManagerLogin.aspx"}, {"Admin","~/AdminLogin.aspx"},
{"User","~/UserLogin.aspx"}
};
return userInfo[roleName];
}
If you are using struts then you can redirect to different pages depending upon some Id. In actionforward you can achieve so. Or you can get some values from the url and try to redirect it
A simple way would be to use the Login-control and provide event handlers for the Authenticate event and the LoggedIn event. But i think it would be worth while for you to check out the capabilities of the asp.net membership system.
I assume you are not using Membership provider and make your login functionality by hand.
I do not fully understand the purpose of this customization. It make no sense for me. But there are multiple solutions for you:
convert the login page (aspx) into a user/custom control (ascx) and put in into different pages - simple, quick but not fully transparent, more info ScottGu
use IIS URL-Rewrite engine to provide multiple entry-points (urls)
to the same login page - clear, recomended, more info ScottGu
With first scenario you need to check UserType for credentials given by the user and confront it with page Url (aspx). In the second scenario, you need to obtain Request.RawUrl which contain base Url and make simple case.
Make use of sessions.
For a workaround, you can follow this:
+provide the same login page.
+Ask for username and password.
+use a drop down for selecting the usertype (ie Admin or Manager or User).
So based on the selection from drop down list you process the request.
I hope this helps.

to display username on all aspx pages

How to Dispaly the username on all aspx pages....?
Can any one help me in this context.....
am thinking that by using "session object" we can able to do this...bt am not sure
Can any send the code or links
Assuming that you have a mechanism you can use to obtain the current user's username, you could fetch that and add code to your master page(s) to display the name. There's not really much more that can be said from your question. (Ask a vague question, get a vague answer.)
And also, if you aren't using master pages, you should be using master pages.
You can use a master page if you want to display the username on all pages.
Username can be stored in a cookie, session, etc.
Code sample:
lblUsername.Text = Session["Username"]
System.Security.Principal.IPrincipal user;
user = System.Web.HttpContext.Current.User;
System.Security.Principal.IIdentity identity;
identity = user.Identity;
lblUserName.Text = identity.Name.Substring(identity.Name.IndexOf(#"\") + 1); ToString();
In First Page (Login page), store the value in Session
Session["Username"] = txtusername.text;
And rest of the pages, where you want to display the UserName
lblUser.Text = Session["Username"].Tostring();
For Logout
Session["Username"] = null;

Login Control - Response.Redirect

I have a usercontrol on a page that has a login control in it. This controls the display of another user control (if the user is not logged in they get the login control user control). I have some authentication code (see below) that runs when the user clicks the "Login" button. Basically I want it to post back to the same page so they will be logged in and able to now see the other protected user control. This code is not working. Perhaps there is something going on in another page that is making this not work, but does this code itself seem like it should work?
string userName = Membership.GetUserNameByEmail(Login1.UserName);
if (userName != null)
{
e.Authenticated = Membership.ValidateUser(userName, Login1.Password);
}
else
{
e.Authenticated = false;
}
if (e.Authenticated)
{
Login1.UserName = userName;
ImageButton loginButton = (ImageButton)Login1.FindControl("LoginButton");
if (loginButton != null)
{
//loginButton.PostBackUrl = Request.Url.ToString();
Response.Redirect(Request.Url.ToString());
}
}
The issue is the login control will itself do a redirect setting a cookie or an encrypted authentication ticket in the url (cookieless).
I think the login control has some properties where you can tell it where it will be redirecting to (which overrides the one in the web.config).
DestinationPageUrl is the property... soo Login1.DestinationPageUrl = "~/whatever.aspx";

Resources