Advertisement
Guest User

Untitled

a guest
Feb 26th, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.78 KB | None | 0 0
  1. MembershipUser user = Membership.GetUser();
  2. string id = user.ProviderUserKey.ToString();
  3. SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
  4. try
  5. {
  6. using (connection)
  7. {
  8. using (SqlCommand con_get = new SqlCommand("SELECT firstname FROM x WHERE userId='" + id + "'", connection)) //Executes SQL command
  9. {
  10. try
  11. {
  12. connection.Open(); //Opens the database connection
  13. using (SqlDataReader reader = con_get.ExecuteReader())
  14. {
  15. if (reader != null)
  16. {
  17. while (reader.Read())
  18. {
  19. Label label1 = (Label)sender;
  20. label1.Text = reader["x"].ToString();
  21. }
  22. }
  23. }
  24. }
  25. catch
  26. {
  27.  
  28. }
  29.  
  30. finally
  31. {
  32. connection.Close(); //Closes the database connection
  33. }
  34. }
  35. }
  36. }
  37. catch
  38. {
  39.  
  40. }
  41.  
  42. protected void Page_Load(object sender, EventArgs e)
  43. {
  44. if(!Page.IsPostBack)
  45. {
  46. var welcomeLabel = Page.Master.FindControl("lblWelcome") as Label;
  47. SetName(welcomeLabel);
  48. }
  49. }
  50.  
  51. protected void SetName(Label welcomeLabel)
  52. {
  53. //this is the type of thing you'd probably wanna do in the Global.asax on session start
  54. if (Session["userName"] == null || !Login()) return; //session variable is empty and the login attempt failed, give up
  55. var usersName = Session["userName"].ToString();
  56. welcomeLabel.Text = usersName;
  57. }
  58. protected bool Login()
  59. {
  60. const string query = "SELECT Name FROM Users WHERE Password = @Password AND UserName = @UserName";
  61. using (var conn = new SqlConnection(connectionString))
  62. {
  63. using (var comm = new SqlCommand(query, conn))
  64. {
  65. comm.CommandType = CommandType.Text;
  66. comm.Parameters.Add(new SqlParameter("@Password", password)); //or get this from a control or wherever
  67. comm.Parameters.Add(new SqlParameter("@UserName", userName)); //or get this from a control or wherever
  68. conn.Open();
  69. var name = (string)comm.ExecuteScalar();
  70. if (!string.IsNullOrEmpty(name))
  71. {
  72. Session["userName"] = name;
  73. return true;
  74. }
  75. //"Login information is wrong or user doesn't exist.
  76. return false;
  77. }
  78. }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement