to display username on all aspx pages - asp.net

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;

Related

Can I save data/value in browser session storage using asp.net

However, i can save and retrieve data to browser from clientside. I'm not sure, but is there any way I could do it from serverside. Thanks in advance for any solution and advices.
I think I have the solution. Below is the code I found, which helped me to expose data from server-side to the client side.
Page.ClientScript.RegisterStartupScript(this.GetType(), "", "sessionStorage.setItem('Username','Something')", true);
For Creating Session
Session["Username"] = " Mairaj";
To Get Value from Session
string userName = string.Empty;
if(Session["Username"] != null)
userName= Session["Username"].ToString();
To get value from Session in aspx page.
var userName = '<% =Session["userName"]%>';
You can get value from Session in aspx page not in external JS file.

autofill textbox based on user input

I'm extremely new to ASP.NET and came across a problem I have yet to figure out. On my Default.aspx page, I have a place where users can signup. This just takes to fields - Email and Password. When the submit button is clicked, they are taking to Signup.aspx, which shows a bigger signup form with fields for username, email, password, confirm password, etc. I would like to auto fill my email and password textboxes with those of the Default.aspx page that the user has entered. Is this possible? I'm using Microsoft Visual Web Developer 2010 Express.
There are multiple ways to do that.
One way is to use querystring to navigate to like :
http://example.com/Signup.aspx?email=value1&password=value2
and get value on Signup.aspx Page_Load event like :
String email = Request.QueryString["email"];
String password = Request.QueryString["password"];
and assign to your text box controls like:
txtEmail.text =email;
txtPassword=password;
But posting password as clear text in query string is not good practice.
Other way is to get HTTP POST information from the source page:
In the source page, include a form element that contains HTML elements (such as input or textarea) or ASP.NET server controls (such as TextBox or DropDownList controls) that post values when the form is submitted.
In the target page, read the Form collection, which returns a dictionary of name/value pairs, one pair for each posted value. e.g.
//
void Page_Load(object sender, EventArgs e)
{
System.Text.StringBuilder displayValues =
new System.Text.StringBuilder();
System.Collections.Specialized.NameValueCollection
postedValues = Request.Form;
String nextKey;
for(int i = 0; i < postedValues.AllKeys.Length; i++)
{
nextKey = postedValues.AllKeys[i];
if(nextKey.Substring(0, 2) != "__")
{
displayValues.Append("<br>");
displayValues.Append(nextKey);
displayValues.Append(" = ");
displayValues.Append(postedValues[i]);
}
}
Label1.Text = displayValues.ToString();
}
Best & easiest I think is to use Session:
on Submitbutton_click event of Default.aspx, save values to Session like:
Session["Email"] = txtEmail.text;
Session["Password"]=txtPassword.text;
and retrieve values on Signup.aspx Page_load event like:
string email = (string)(Session["Email"]);
string password = (string)(Session["Password"]);
& assign to your control/textbox like:
txtEmail.text =email;
txtPassword=password;
There are more ways too to retrieve value from previous page like PreviousPage.FindControl("txtEmail") but I never like them.

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.

FormsAuthentication Rememberme

I am using forms authentication and the I wanted the remember me functionality.
How can I just retain the username alone.
I wanted the username to be stored on cookies and when the user is logged out. I want to user name to be displayed on the username text box.
Is there an example that can be provided?
In the login method (Probably your "Login" button click):
Response.Cookies["userName"].Value = txtUserName.Text;
Then on the Page_Load check for that cookie and assign the textbox a value.
if (!String.IsNullOrEmpty(Request.Cookies["userName"])) {
txtUserName.Text = Request.Cookies["userName"];
}

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