I am new to web development and .NET too. I have a website written in ASP.NET using C#. How should I display full name of the current user instead of username using sessions? Please help me. Here is the code.
Code behind login page:-
Session["username"] = txt_un.Text.Trim().ToString();
Code behind userprofile page:-
string str = "select fullname from userprofile where username=#username";
Label4.Text = Session["username"].ToString();
The problem is that fullname is not present on the login page. It is present in userprofile page. How to display fullname on the userprofile page after user click on login button?User is using his registration_id as username. But I don't want to display registration_id,I want to display fullname of the user.Pls give me answer in detail. Thank you in advance.
You need to get first name, Whenever you login in your app with this select query and ExecuteScalar.
string str = "select fullname from userprofile where username=#username";
Then You need to store the first name into a session
Session[firstName]=Query return value
And finally you can give
if(Session[firstName]!=null)
{
Label4.Text=Session[firstName].ToString()
}
I really don't understand clearly what you need but somehow you need user's full name to show some where using username,
Here one simple function that will return you the full name.
I assume you know how to connect your webpage to the SQL Server and all the functions
public string GetFullName(string username)
{
string query = "select fullname from userprofile where username ='" + staffID + "'";
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
try
{
while (reader.Read())
{
return reader["fullname"].ToString();
}
}
catch (Exception ex)
{
HttpContext.Current.Session["Error_Message_Session"] = ex;
HttpContext.Current.Response.Redirect("Error.aspx", false);
}
finally
{
conn.Close();
}
return "-";
}
The function that i used here is from my own project, this is how i get the full name by his username, similarly i had the same problem so i did this, just a simple static function
Related
I am trying to redirect my login.htm to index.htm in c#. both files are inside the folder named 'default'. after logging in, if the credential is correct, I want to redirect the login page to index. using the code below, but there is an exception message Attempted to cancel thread.. Is there a way to fix this?? How you can help me. Thanks in advance.
[WebMethod]
public void LogMeIn(string user, string pass) {
try {
using (MySqlConnection dbConn = new MySqlConnection(connectionString())) {
if (dbConn.State == System.Data.ConnectionState.Open) dbConn.Close();
dbConn.Open();
MySqlCommand sqlCmd = new MySqlCommand("SELECT * FROM tbllogin WHERE userName = '" + user + "' AND passWord ='" + pass + "'", dbConn);
int rowCount = (int)sqlCmd.ExecuteScalar();
if (rowCount > 0) {
HttpContext.Current.Response.Redirect("../default/index.htm"); //redirect to new htm page
}
}
}
catch (Exception ex) {
Console.WriteLine("Error Message : " + ex.Message);
}
}
HttpContext.Current.Response.Redirect(HttpContext.Current.Request.ApplicationPath+"default/index.htm");
Or you can use this way.
HttpContext.Current.Response.Redirect is trying to send users to the wrong place
HttpContext.Current.Response.Redirect("~/default/index.htm");
There are some errors and unnecesary code in your code example:
There is no need to check if dbConn is already opened, because it was just created
The SELECT * caused an Exception when doing later an ExecuteScalar because the table has more than one column. You should change it to SELECT COUNT(*)
Because how Microsoft handles how the flow of the page is done, if you don't end the response when doing the Response.Redirect you may need to catch an ThreadAbortException. To end the response you could check Redirect(string url, bool endResponse) overload
That being said, you should do use parametrized queries, because unexpected or malicious input could cause you problems.
Hello I am working on a log in form. I am able to sign up for an account on my website, but It doesn't allow me to log in when I type in the user name and password. I have some code that is suppose the compare the two but for some reason is just not working. Here is my code. It wont for some reason even execute the while loop at the bottom of the code. Any help would be appreciated
private bool CompareStrings(string string1, string string2)
{
return String.Compare(string1, string2, true, System.Globalization.CultureInfo.InvariantCulture) == 0 ? true : false;
}
public void LogInAccount(string UserName, string UserPassword, Label InvalidLogIn)
{
connection.ConnectionString = #"Connection String";
connection.Open();
string compare = "select ISNULL(UserName, '') As UserName, ISNULL(UserPassword, '') As UserPassword from SignUp where UserName= #UserName";
SqlCommand CompareUser = new SqlCommand(compare, connection);
//SqlCommand Command2 = new SqlCommand("select * from SignUp where FirstName= #FirstName", connection);
//Command2.Parameters.AddWithValue("#FirsName", FirstName.Text);
CompareUser.Parameters.AddWithValue("#UserPassword", UserPassword);
CompareUser.Parameters.AddWithValue("#UserName", UserName);
SqlDataReader dr = CompareUser.ExecuteReader();
//string User = UserName;
//string UserPassword = Password;
//HtmlAnchor LogIn = (HtmlAnchor)Master.FindControl("LogIn");
//HtmlAnchor SignUp = (HtmlAnchor)Master.FindControl("SignUp");
while (dr.Read())
{
if (this.CompareStrings(dr["UserName"].ToString(), UserName) &&
this.CompareStrings(dr["UserPassword"].ToString(), UserPassword))
{
InvalidLogIn.Visible = false;
FormsAuthentication.RedirectFromLoginPage(UserName, true);
}
else
{
InvalidLogIn.Visible = true;
}
}
connection.Close();
}
Just something I'd throw out there: you really shouldn't be comparing usernames/passwords like this.
The basic idea behind login authentication is this:
When the password gets created, the hashed value is stored in a
table
When a user tries to log in, they submit their password
The attempted password is then hashed
Hash(Attempt) is compared to the entry in the database.
... if I'm reading your code right, it looks like the password is stored in plain-text in SQL? And your query retrieves the value, and then compares it in c#?
Don't get me wrong - if this is just a little personal site that only you use, and the password table only has your entry? Then it's no problem. But if you've got anyone else putting usernames/passwords in your site - you really need to protect their data.
Hie, I'm having a bit of a crisis trying to run an sql query from a C# class. It was working fine in the Login page it was in before and I changed very little of it when I moved it over.
SQL query in class:
namespace Masca
{
public class loginc
{
// Telling the class that the page 'Login' exists.
public Login login;
....
public void Login ()
{
// connection parameters
string sqlcon = "datasource=localhost;port=3306;username = root; password = root";
//Command to carry out -This is what the exception highlights when it's thrown.
string query = "SELECT * FROM logon.login where username = '" + login.username.Text + "' and password = '" + login.password.Password + "';";
MySqlConnection con = new MySqlConnection(sqlcon);
MySqlCommand cmd = new MySqlCommand (query,con);
MySqlDataReader rdr;
con.Open();
rdr = cmd.ExecuteReader();
int count = 0;
while (rdr.Read())
{
count = count + 1;
}
if (count == 1)
{
//If the username and password match those in the database table, run the method 'login' in the login page cs.
login.login();
}
else
{
// if they don't match, run the method 'failLogin' in the login page cs.
login.failLogin();
}
}
In login.cs I have two textboxes and a button. One for the username and one for the password. The button is supposed to trigger the above code:
public void Logon_Click(object sender, RoutedEventArgs e)
{
loginc.Login();
}
Which it does fine. However I get the classic "Object reference not set to an instance of an object" exception thrown on the query. When I enter the actual credentials instead of '+ login.username.Text +' and '+ login.password.Password +' then the exception gets thrown on 'login.Login()'.
I don't understand why the loginc.cs class refuses to relate to the login.cs but the login.cs clearly has no problem triggering the method in class the same way. Anyone know where I'm going wrong?
I see no code where you instantiate Login login. You should really do that.
Login login = new Login();
or something alike.
I need to create login page in asp.net where i have to create 3 user access levels such as
users who can view there email and updates
superusers who can view there email, updates and also delete some users
admin who can view all and delete superusers as well.
my login page has
username
password and login button
when the user/admin/superuser clicks on the button it should automatically redirect him depending on the user levels.
i have a database of username, password, userid, useraccesstype, email.
my problem here is i am not getting how to write the if commands basing on the useraccesstype in a disconnected architecture of database and also without using stored procedures.
String Uid = TextBox1.Text;
String Pwd = TextBox2.Text;
SqlConnection con = new SqlConnection(#"Data Source=Sun-PC\SQLEXPRESS;Initial Catalog=dts;Persist Security Info=True;User ID=sa;Password=********;");
SqlDataAdapter da;
da = new SqlDataAdapter("Select userid,password,useraccesstype from Table2 WHERE userid = " + Uid + " and password ='" + Pwd + "'", con);
DataSet ds = new DataSet("Table2");
da.Fill(ds, "Table2");
if (Uid == "userid" && Pwd == "password")
{
if (uzrtype3 = "componentadmin")
{
Response.Redirect("userpage.aspx");
}
if (uzrtype = "user")
{
Response.Redirect("register.aspx");
}
}
else
{
Label123.Text = "Sorry, user not recognized - please try again";
}
Reading between the lines, I think you are asking "how t get the useraccesstype"? If so with the current code, maybe:
if(ds.Tables[0].Rows.Count == 1) {
// match
var accessType = ({appropriate cast here})ds.Tables[0].Rows[0]["useraccesstype"];
} else {
// no match
}
However! I would do it a different way, solving the various parameter issues and making it much safer - using "dapper-dot-net" for convenience (google it):
string userid = ....
string password = ...
var row = con.Query(
"Select useraccesstype from Table2 WHERE userid = #userid and password = #password",
new { userid, password }).FirstOrDefault();
if(row == null) {
// no match
} else {
var accessType = ({some cast here})row.useraccesstype;
}
The salted hashing of passwords is also something you should look into.
No point returning the userid/password : you already know those. You could also use ExecuteScalar, but then you need to handle the parameters yourself.
i am using ODBC to pull data from active directory to get the email for a particular username using the code below.
how can i use AD to pull all the usernames of peolel who report into a prticular manager?
i can transverse the org chart in outlook so im thinking i can do the same using AD...
ideas?
System.Data.OleDb.OleDbConnection con;
System.Data.OleDb.OleDbCommand cmd;
con = new System.Data.OleDb.OleDbConnection("Provider=ADsDSOObject;dsn=Active Directory Provider");
con.Open();
//Create a command object on this connection
string strSQL = "SELECT mail FROM 'LDAP://DC=amrs,DC=win,DC=ml,dc=COM' WHERE samaccountname = '" + UserName.Replace(#"AMRS\", "") + "'";
cmd = new System.Data.OleDb.OleDbCommand(strSQL, con);
try
{
return Convert.ToString ( cmd.ExecuteScalar() );
}
catch (System.Data.OleDb.OleDbException exc)
{
return "ERROR: " + exc.ToString();
}
finally
{
con.Close();
}
See if the manager attribute in AD is set? It should return you the distinguished name of the manager. You can then parse the string to figure out the samAccountName of the manager.
Then just repeat your search using the manager's distinguished name.
Now if the manager attribute isn't set....
Maybe search by department code, and then check the title of everyone in the department?
Might want to look into the Directory Services class.
This link gives you a basic tutorial on how to query AD