using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Data.SqlClient; using System.Web.Configuration; public partial class Lec12_Sessions_and_Cookies_UsingSessions : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Session["LoggedIn"] != null) { LoggedIn(); } else { LoggedOut(); } } protected void loginButton_Click(object sender, EventArgs e) { SqlConnection connection; SqlCommand command; SqlDataReader reader; try { // Connect to the database using the connection string in the web.config file connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString); // Create an SELECT Sql statement command = new SqlCommand("SELECT * FROM Users WHERE Username=@Username AND Password=@Password", connection); command.Parameters.AddWithValue("@Username", userTextBox.Text); command.Parameters.AddWithValue("@Password", passwordTextBox.Text); using (connection) { // Open the connection connection.Open(); // Execute the command, the records are returned in an SqlDataReader object reader = command.ExecuteReader(); // Have a row been returned? if (reader.HasRows) { // Logged in OK reader.Read(); Session["LoggedIn"] = reader["FullName"]; Session.Timeout = 40; // 40 minutes LoggedIn(); } else { // No match found } // Close the connection connection.Close(); } } catch { // Some error occurred } } protected void logoutButton_Click(object sender, EventArgs e) { Session.Clear(); Session.Abandon(); LoggedOut(); } private void LoggedIn() { welcomeLabel.Text = "Hi " + Session["LoggedIn"]; loginPanel.Visible = false; logoutPanel.Visible = true; } private void LoggedOut() { loginPanel.Visible = true; logoutPanel.Visible = false; } }