Asp.net Session Url Asp.net Page.IsPostBack getuserinfo error - asp.net

Okay,The Other errors are fixed now im at this point where my other pages need their code to be updated:
Error : Object reference not set to an instance of an object.
public partial class Controls_GetUserScraps : System.Web.UI.UserControl
{
DataBaseClass dbClass = new DataBaseClass();
public DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GetUserScraps(int.Parse(Session["UserId"].ToString()));
}
}
public void GetUserScraps(int Id)
{
string getUserScraps = "SELECT u.Id as UserId,u.FirstName,,u.LastName,u.ImageName,s.FromId,s.ToId,s.Message,s.SendDate,s.ID as ScrapId FROM [User] as u, Scrap as s WHERE u.Id=s.FromId AND s.ToId='" + Request.QueryString["Id"].ToString() + "'";
dt = dbClass.ConnectDataBaseReturnDT(getUserScraps);
if (dt.Rows.Count > 0)
{
GridViewUserScraps.DataSource = dt;
GridViewUserScraps.DataBind();
}
}
I replaced Session ID to UserId and it removed the error now it has displayed another error under.
Error : Object reference not set to an instance of an object.
string getUserScraps = "SELECT u.Id as UserId,u.FirstName,,u.LastName,u.ImageName,s.FromId,s.ToId,s.Message,s.SendDate,s.ID as ScrapId FROM [User] as u, Scrap as s WHERE u.Id=s.FromId AND s.ToId='" + Request.QueryString["Id"].ToString() + "'";
Adding your fix created this new error:

I think the easiest way to do this would be to have the private bool UserAuthenticate method take an out parameter which you can use to return the actual user name from the database.
private bool UserAuthenticate(string UserName, string Password, out string actualUserName)
{
actualUserName = string.Empty;
bool boolReturnValue = false;
//--------------------------------
//Check UserID From Config File
if (UserName == "User" && Password == "Pass")
{
boolReturnValue = true;
return boolReturnValue;
}
else
{
//--------------------------------
dt = new DataTable();
string chkUser = "Select * FROM [User] where Email='" + UserName + "' AND Password='" + Password + "'";
dt = dbClass.ConnectDataBaseReturnDT(chkUser);
if (dt.Rows.Count > 0)
{
//TODO: grab the actual user name from the row and assign it to actualUserName. For example:
actualUserName = dt.Rows[0]["FullName"];
boolReturnValue = true;
Session["UserId"] = dt.Rows[0]["Id"].ToString();
string updateLastLogin = "Update [User] SET LastLogin='" + System.DateTime.Now.ToString() + "' where Id='" + Session["UserId"].ToString() + "'";
dbClass.ConnectDataBaseToInsert(updateLastLogin);
}
return boolReturnValue;
}
}
After that you would then need to do something like this in the OnAuthenticate method:
string actualUserName;
Authenticated = UserAuthenticate(ctlLogin.UserName, ctlLogin.Password, out actualUserName);
And the redirect would now be:
Response.Redirect("Home.aspx/" + actualUserName);

Related

Getting error "Database is locked" when I trye to save data i SQLITE DB

I have following class that connects to database but when I trye to call the method that saves data I get error "Database is locked". Could some one please help me to find the problem?
class Data
{
private SQLiteConnection con;
private void ConnectoDB()
{
String PathDB = Directory.GetCurrentDirectory();
PathDB += "\\SQLiteDB_MEDFit.db";
string cs = #"URI=file:" + PathDB;
string stm = "SELECT SQLITE_VERSION()";
con = new SQLiteConnection(cs);
con.Open();
var cmd = new SQLiteCommand(stm, con);
string version = cmd.ExecuteScalar().ToString();
}
public Boolean SaveToDatabase(string name, string number)
{
bool result = false;
try
{
ConnectoDB();
con.Execute("insert into People(name, number) values ('" + name+ "', '" + number+ "')");
con.Close();
result = true;
MessageBox.Show("Saved!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return result;
}
}
The code that calls the "SaveToDatabase()"
string name = textBox1.Text();
string number = textBox2.Text();
Data connect = new Data();
connect.SavetoDB(name, number);

Why isn't my database logic throwing an exception when I enter data that already exists?

I have a small ASP.NET registration page linked to a database. If the user enters the username that already exists in the database, then it should display "user already exists", but it is not doing that:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
SqlConnection conn =new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string check = "Select Count(*) from Registration where UserName = '"+TextBoxUN.Text+"';";
SqlCommand comm = new SqlCommand(check, conn);
int temp = Convert.ToInt32(comm.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("User already exists!!");
}
conn.Close();
}
}
protected void Button3_Click(object sender, EventArgs e)
{
if (this.DropDownListCountry.SelectedValue == "-Select-" && this.DropDownListAge.SelectedValue == "-Select-")
{
Response.Write("Select Country and age!");
}
else if(this.DropDownListCountry.SelectedValue == "-Select-" && this.DropDownListAge.SelectedValue != "-Select-")
{
Response.Write("Select Country!");
}
else if (this.DropDownListCountry.SelectedValue != "-Select-" && this.DropDownListAge.SelectedValue == "-Select-")
{
Response.Write("Select Age!");
}
else
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string insertQ = "insert into Registration(UserName,Email,Password,Country,Age) values ('" + TextBoxUN.Text + "','" + TextBoxEmail.Text + "','" + TextBoxPass.Text + "','" + DropDownListCountry.SelectedItem.ToString() + "','" + DropDownListAge.SelectedItem.ToString() + "');";
SqlCommand comm = new SqlCommand(insertQ, conn);
comm.ExecuteNonQuery();
Response.Redirect("Display.aspx");
conn.Close();
}
catch(Exception ex)
{
Response.Write("Error : " + ex.ToString());
}
}
}
}
I think you should try first
If ( temp > 0)
{
}
also debug to see what is returned by the sql query
Few Things.
You need to check this before inserting the data.
You are not preventing entering the same data if the username still exists
You can check top 1 instead of count.
private bool IsUserExists()
{
bool UserExists = false;
SqlConnection conn =new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string check = "Select Count(*) from Registration where UserName = '"+TextBoxUN.Text+"';";
SqlCommand comm = new SqlCommand(check, conn);
int temp = Convert.ToInt32(comm.ExecuteScalar().ToString());
if (temp >= 1)
{
UserExists = true;
Response.Write("User already exists!!");
}
conn.Close();
}
return UserExists ;
}
Check this before inserting the data.
try
{
if(UserExists())
return; //Skips further code when user exists.
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string insertQ = "insert into Registration(UserName,Email,Password,Country,Age) values ('" + TextBoxUN.Text + "','" + TextBoxEmail.Text + "','" + TextBoxPass.Text + "','" + DropDownListCountry.SelectedItem.ToString() + "','" + DropDownListAge.SelectedItem.ToString() + "');";
SqlCommand comm = new SqlCommand(insertQ, conn);
comm.ExecuteNonQuery();
Response.Redirect("Display.aspx");
conn.Close();
}
catch(Exception ex)
{
Response.Write("Error : " + ex.ToString());
}

Session disappears on return to home page

I have a web site running on Azure where a user can login then navigate to other pages (naturally). My problem is that when I return to the Index/Homepage the session just disappears. I thought it my have something to do with the login control and its authentication method in the code behind but I tried putting another login on another page with the same authenticate event but that is completely fine.
I haven't found anyone with a similar problem.
here is the code behind for index.aspx
string Connection = ConfigurationManager.ConnectionStrings["****"].ConnectionString;
protected void Page_Load(object sender, EventArgs e) {}
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e) {
string Username = Login1.UserName;
string pwd = Login1.Password;
SqlConnection connection = new SqlConnection(Connection);
connection.Open();
//SqlCommand comm = new SqlCommand("SELECT COUNT([*****], [*****]) FROM ***** WHERE [****] = '***' AND [****] = '****'", connection);
string sqlUserName = "SELECT [****] ,[****] FROM ***** WHERE [*****] ='" + * * * * * +"' AND [*****] ='" + * * * +"'";
SqlCommand cmd = new SqlCommand(sqlUserName, connection);
string CurrentName;
CurrentName = (string) cmd.ExecuteScalar();
if(CurrentName != null) {
Login1.FailureText = "Welcome";
Session["User"] = Username;
Session["LoggedIn"] = true;
Label1.Text = Session["User"].ToString();
if((bool) Session["LoggedIn"] == true && Session["User"].ToString() == "admin1") {
HyperLink3.Visible = true;
} else if((bool) Session["LoggedIn"] == true) {
HyperLink1.Visible = true;
}
} else {
Session["User"] = "";
}
}
}
Your if statement must be bugging out somewhere, or CurrentName is null.
if (CurrentName != null)
{
Login1.FailureText = "Welcome";
Session["User"] = Username;
Session["LoggedIn"] = true ;
Label1.Text = Session["User"].ToString();
if ((bool)Session["LoggedIn"] == true && Session["User"].ToString() == "admin1")
{
HyperLink3.Visible = true;
}
else if ((bool)Session["LoggedIn"] == true)
{
HyperLink1.Visible = true;
}
}
else
{
Session["User"] = "";
}
The most likely culprit is the preceding SQL query. Double check your syntax with the SQL query. I'm not sure what the asterisk variables are you have combined in there, but they could be causing an issue. You should proceed with line-by-line debugging of that script. Catch it mid-way through and check the value of CurrentName.

Session variable accessibility

I have a class which creates a session the following way:
Session["UserId"] = UserId; // UserId = 1
In one of the pages on Page_Load, I retrieve the session variable value this way which works fine:
if (Session["UserId"] != null){
var userid = Session["UserId"];
Welcome.Text = "Hello, " + userid;
}
Now I need to use the value of the session variable in my classes as well. I used the following method to get the session value int useridsession = Convert.ToInt32(HttpContext.Current.Session["UserId"]); but it always returns null whereas the session is correctly read using Session["UserId"]; in my code behind file.
The mentioned class:
public static DataTable ManageBookingsDataTable()
{
int useridsession = Convert.ToInt32(HttpContext.Current.Session["UserId"]);
SqlConnection con = new SqlConnection(Database.ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select bookings.id,user_id, start_date, end_date, pets.name AS 'Pet name' from bookings AS bookings left join users AS usr ON bookings.user_id=usr.id AND bookings.user_id=1 left join pets AS pets ON pets.id=bookings.pet_id WHERE bookings.user_id=#userid_session", con);
cmd.Parameters.AddWithValue("#userid_session", useridsession);
SqlDataAdapter sqlDa = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
string id = string.Empty;
string name = string.Empty;
string startdate = string.Empty;
string enddate = string.Empty;
string full_string = string.Empty;
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
id = dt.Rows[i]["id"].ToString();
var sdate = dt.Rows[i]["start_date"];
name = dt.Rows[i]["Pet name"].ToString();
startdate = dt.Rows[i]["start_date"].ToString();
enddate = dt.Rows[i]["end_date"].ToString();
full_string = startdate + " to " + enddate + " (" + name + ")";
//CurrentBookings.Items.Add(new ListItem(full_string, id));
}
}
return dt;
}
I diagnosed the problem by adding HttpContext.Current.Session["UserId"] = 1; which proves that when I set the session in the same class, the method works.
My question is how do I access the previously created session from any class?
Session should be available for the session regardless of the class. Why don't you set and get
your session values using the same class? All your session stuff in a one place so it is more neat and tidy as well.
Local.MySession.UserId = UserId; //Set here
int myUserId = Local.MySession.UserId; //Get here
//Something like this??
namespace Local
{
//You can add all session variables to this class
public class MySession
{
public static int UserId
{
get
{
return Convert.ToInt32(HttpContext.Current.Session["userId"] ?? "0");
}
set { HttpContext.Current.Session["userId"] = value.ToString(); }
}
public static string UserEmail //For Example another session variable
{
get { return HttpContext.Current.Session["email"] ?? ""; }
set { HttpContext.Current.Session["email"] = value; }
}
}
}

Login validation and redirection

I am trying to implement a Login validation using C# 2005 in ASP.net 2.0 web application. The SQL Server database contains a table named "UserList" with columns LoginId, Password and Role. The Login webform should authenticate the LoginId and password and depending upon the Role assigned to that user/visitor should redirect to a specific webform with a pre-defined menu options. The role might be Admin, DEO, Accounts or Member. How should I implement it? I have tried the following:
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
try
{
string uname = Login1.UserName.Trim();
string password = Login1.Password.Trim();
int flag = AuthenticateUser(uname, password);
if (flag == 1)
{
e.Authenticated = true;
Login1.DestinationPageUrl = "~/MenuAdmin.aspx";
}
else if (flag == 2)
{
e.Authenticated = true;
Login1.DestinationPageUrl = "~/MenuDEO.aspx";
}
else if (flag == 3)
{
e.Authenticated = true;
Login1.DestinationPageUrl = "~/MenuAccts.aspx";
}
else if (flag == 4)
{
e.Authenticated = true;
Login1.DestinationPageUrl = "~/MenuMember.aspx";
}
else
{
e.Authenticated = false;
}
}
catch (Exception)
{
e.Authenticated = false;
}
}
private int AuthenticateUser(string uname, string password)
{
int bflag = 0;
string connString = ConfigurationManager.ConnectionStrings["LoginDemoConnString"].ConnectionString;
string strSQL = "Select * FROM UserList where ULoginId ='" + uname + "' AND UPassword ='" + password + "'";
DataTable dt = new DataTable();
SqlConnection m_conn;
SqlDataAdapter m_dataAdapter;
try
{
m_conn = new SqlConnection(connString);
m_conn.Open();
m_dataAdapter = new SqlDataAdapter(strSQL, m_conn);
m_dataAdapter.Fill(dt);
m_conn.Close();
}
catch (Exception ex)
{
dt = null;
}
finally
{
//m_conn.Close();
}
if (dt.Rows.Count > 0)
{
if (dt.Rows[0][3].ToString() == "Administrator")
bflag = 1;
else if (dt.Rows[0][3].ToString() == "DEO")
bflag = 2;
else if (dt.Rows[0][3].ToString() == "Accts")
bflag = 3;
else
bflag = 4;
}
return bflag;
}
Well first of all I guess each role in the sql table has id so you can get rid of the ifs in the AuthenticateUser and just return the id. Or you can also return the actual role and just do something with this data in the Login1_Authenticate function.
Now you can also get rid of the ifs in the Login1_Authenticate function if you will use dictionary where the key is role and value is pageURL so you can just write something like that:
int flag = AuthenticateUser();
Login1.DestinationPageUrl = roles.ElementAt(flag).Value;

Resources