Table adapter with visual studio Final Code - asp.net

I enter values in User Name and Password in two text boxes. When I click submit, I want the table adapter to check the database to see if those are really the values and allow the user to log in.
This is my code:
protected void Submit_Click(object sender, EventArgs e)
{
//assign text from the textboxes to variables
string userName = TextBox1.Text;
string passWord = TextBox2.Text;
lblError.Visible = true;
try
{
string passwordValue = Encrypt(passWord);
DataSet1.tblUserDataTable dataTable = proccessedProcess.Login(userName, passwordValue);
if (dataTable != null & dataTable.Count!=0)
{
DataSet1.tblUserRow dataRow = dataTable[0];
if (dataRow.nUserID.ToString() == "00000000-0000-0000-0000-000000000000")
{
lblError.Text = "";
}
else if(dataRow.nUserID.ToString() != "00000000-0000-0000-0000-000000000000")
{
Session["CurrentUserID"] = dataRow.nUserID.ToString();
Session["LoggedIn"] = "YES";
Session["LastLogin"] = DateTime.Now.ToString();
Session["UserName"] = dataRow.txtUserName;
HttpContext.Current.Response.Redirect("MainCustomer.aspx");
}
} else {
lblError.Text = "Incorrect UserID or Password";
}
}
catch (Exception E)
{
E.Message.ToString();
lblError.Text = E.Message;
}
}

in the catch section you have E.Message.ToString(); which has no effect. Either you have to set it to a label inorder to see if there is an exception happening or throw E
catch (Exception E)
{
// E.Message.ToString();
Throw;
}

Related

How to get pathname of image from FileUpload in grid view

Hello i have my FileUpload in gridview.I upload image for every row and then click button called UPLOAD. So that it should get image path from every row and upload. Onclick listener for UPLOAD is UploadBtn_onClick.
Code for UploadBtn_onClick is
protected void UploadBtn_onClick(object sender, EventArgs e)
{
foreach (GridViewRow row in StudentGrid.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
try
{
UpdateEmailProperties objUpdateEmailId = new UpdateEmailProperties();
GridViewRow grdrow = (GridViewRow)((FileUpload)sender).NamingContainer;
FileUpload filename = (FileUpload)grdrow.Cells[5].FindControl("fileuploadimages");
objUpdateEmailId.StudId = int.Parse(row.Cells[6].Text);
objUpdateEmailId.Email = row.Cells[3].Text;
objUpdateEmailId.profilepath = "profilepics/" + filename;
int intStatus;
intStatus = Stud.UpdateStudentEmailId(objUpdateEmailId);
if (intStatus != 0)
{
lblWarning.Text = "Updated successfully";
}
else
{
lblWarning.Text = "Failed to Update";
}
}
catch (Exception ex)
{
//LogFile.CreateLog("User", "AddPlacement", ex.Message);
lblWarning.Text = "Error: " + ex.Message.ToString();
}
}
}
}
But i am getting error as
Unable to cast object of type 'System.Web.UI.WebControls.Button' to type 'System.Web.UI.WebControls.FileUpload'
.
I need to fetch name of file returned from loadfile

using Session for creating login for mutiple users has error and further which can evaluate the rights of users

I have tried many things but its just showing error "Object reference not set to an instance of an object."
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
else if (Session["StudId"] != null)
{
Label1.Text = Session["StudId"].ToString();
}
I have written this code in my login page dragging all the required databases strings i.e. typeid,students,faculty,admin and accemployee in the page.
public partial class Login : System.Web.UI.Page
{private string strcon = WebConfigurationManager.ConnectionStrings["StudentConnectionString1"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.Cookies["UName"] != null)
TextBox1.Text = Request.Cookies["UName"].Value;
if (Request.Cookies["PWD"] != null)
TextBox2.Attributes["value"] = Request.Cookies["PWD"].Value;
if (Request.Cookies["UName"] != null && Request.Cookies["PWD"] != null)
CheckBox1.Checked = true;
}
}
protected void Button1_Click1(object sender, EventArgs e)
{
if (DropDownList1.SelectedItem.Value == "1")
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("Select StudFirstName from Student where StudId=#sid and Password=#pw", con);
cmd.Parameters.AddWithValue("#sid", TextBox1.Text);
cmd.Parameters.AddWithValue("#pw", TextBox2.Text);
con.Open();
string name = Convert.ToString(cmd.ExecuteScalar());
con.Close();
if (String.IsNullOrEmpty(name))
Label1.Text = "Sorry! Invalid User ID or Password!";
else
{
if (CheckBox1.Checked)
{
Response.Cookies["UName"].Value = TextBox1.Text;
Response.Cookies["PWD"].Value = TextBox2.Text;
Response.Cookies["UName"].Expires = DateTime.Now.AddMonths(2);
Response.Cookies["PWD"].Expires = DateTime.Now.AddMonths(2);
}
Session.Add("StudId", TextBox1.Text);
Session.Add("StudFirstName", name);
Session.Add("Password", TextBox2.Text);
FormsAuthentication.RedirectFromLoginPage(name, false);
}
}
else if (DropDownList1.SelectedItem.Value == "2")
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("Select FacultyFirstName from Faculty where FacultyId=#fid and Password=#pw", con);
cmd.Parameters.AddWithValue("#fid", TextBox1.Text);
cmd.Parameters.AddWithValue("#pw", TextBox2.Text);
con.Open();
string name = Convert.ToString(cmd.ExecuteScalar());
con.Close();
if (String.IsNullOrEmpty(name))
Label1.Text = "Sorry! Invalid User ID or Password!";
else
{
if (CheckBox1.Checked)
{
Response.Cookies["UName"].Value = TextBox1.Text;
Response.Cookies["PWD"].Value = TextBox2.Text;
Response.Cookies["UName"].Expires = DateTime.Now.AddMonths(2);
Response.Cookies["PWD"].Expires = DateTime.Now.AddMonths(2);
}
Session["FacultyId"] = TextBox1.Text;
Session.Add("FacultyFisrtName", name);
Session["Password"] = TextBox2.Text;
FormsAuthentication.RedirectFromLoginPage(name, false);
}
}
else if (DropDownList1.SelectedItem.Value == "3")
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("Select AccEmployeeName from AccEmployee where AccEmployeeId=#aid and Password=#pw", con);
cmd.Parameters.AddWithValue("#aid", TextBox1.Text);
cmd.Parameters.AddWithValue("#pw", TextBox2.Text);
con.Open();
string name = Convert.ToString(cmd.ExecuteScalar());
con.Close();
if (String.IsNullOrEmpty(name))
Label1.Text = "Sorry! Invalid User ID or Password!";
else
{
if (CheckBox1.Checked)
{
Response.Cookies["UName"].Value = TextBox1.Text;
Response.Cookies["PWD"].Value = TextBox2.Text;
Response.Cookies["UName"].Expires = DateTime.Now.AddMonths(2);
Response.Cookies["PWD"].Expires = DateTime.Now.AddMonths(2);
}
Session["AccEmployeeFacultyId"] = TextBox1.Text;
Session.Add("AccEmployeeName", name);
Session["Password"] = TextBox2.Text;
FormsAuthentication.RedirectFromLoginPage(name, false);
}
}
else if (DropDownList1.SelectedItem.Value == "4")
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("Select from Admin where AdminId=#pid and Password=#pw", con);
cmd.Parameters.AddWithValue("#pid", TextBox1.Text);
cmd.Parameters.AddWithValue("#pw", TextBox2.Text);
con.Open();
string name = Convert.ToString(cmd.ExecuteScalar());
con.Close();
if (String.IsNullOrEmpty(name))
Label1.Text = "Sorry! Invalid User ID or Password!";
else
{
if (CheckBox1.Checked)
{
Response.Cookies["UName"].Value = TextBox1.Text;
Response.Cookies["PWD"].Value = TextBox2.Text;
Response.Cookies["UName"].Expires = DateTime.Now.AddMonths(2);
Response.Cookies["PWD"].Expires = DateTime.Now.AddMonths(2);
}
string adminName = "Pujan";
Session["AdminId"]=TextBox1.Text;
Session["AdminName"] = adminName;
Session["Password"]=TextBox2.Text;
FormsAuthentication.RedirectFromLoginPage(name, false);
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Label2.Text = DropDownList1.SelectedItem.Text;
}
`
}
.....................................................................................
Now the error occurs in the masterpage.master.cs which is shown below....
public partial class MasterPage : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["StudId"] == null)
Response.Redirect("Login.aspx");
else if (Session["StudId"] != null)
{
Label1.Text = Session["StudId"].ToString();
}
else if (Session["FacultyFirstName"] == null)
{
Response.Redirect("Login.aspx");
}
else if (Session["FacultyFirstName"] != null)
{
Label1.Text = Session["FacultyFirstName"].ToString();
}
else if (Session["AccEmployeeName"] == null)
{
Response.Redirect("Login.aspx");
}
else if (Session["AccEmployeeName"] != null)
{
Label1.Text = Session["AccEmployeeName"].ToString();
}
else if (Session["AdminName"] == null)
{
Response.Redirect("Login.aspx");
}
else if (Session["AdminName"] != null)
{
Label1.Text = Session["AdminName"].ToString();
}
}
protected void LinkButton1_Click1(object sender, EventArgs e)
{
FormsAuthentication.SignOut();
Response.Redirect("Login.aspx");
}
}
Please suggest me how to get rid of the error in session or wateva it is......Thank you in advance :)
System.NullReferenceException: Object reference not set to an instance of an object.
This error means that the value that is being provided is a null and the Server cannot use it for a process, that requires a parameter to work on.
Sometimes this happens when you're trying to use a variable in a method, and the variable gets a null value. Null value means that there is no value or no data for this thing.
In your code I guess that this error would generate when the site is first loading. At that time, there is no Session for the Server to load or work on. Thus the values are all null throwing this Null exception.
You can try to cover up the code inside an if else block to check whether there is a cookie present for the Session, or try out a try catch block to minimize this exception and do the work depending on the condition.
An example would be:
try {
/* your code here */
} catch (System.NullReferenceException) {
/* create a session or fill up the variable */
}
This block would run the code of yours, and if the exception provided inside the Catch method gets thrown it would execute the code inside the catch block.
Second thing was to use if else:
if(variable != null) {
/* your code here */
} else {
/* set the value */
}
You just check for the value of that particular variable, and check it. If its a null valued variable, then you can skip the execution of the code block and fill the variable with a value and then come back to the current space and re-execute it.
For exception details: http://msdn.microsoft.com/en-us/library/system.nullreferenceexception(v=vs.110).aspx

ASP.NET Mysql Data Reader not working

I try to autentificate to a database, to create a Login function. Every time I press the button I receive this error: System.InvalidOperationException: The connection is not open. at MySql.Data.MySqlClient.MySqlConnection.Throw(Exception ex) at MySql.Data.MySqlClient.MySqlCommand.Throw(Exception ex) at MySql.Data.MySqlClient.MySqlCommand.Prepare() at start.CheckUserLogin(String username, String password) in c:\Users\RARES\Documents\Visual Studio 2010\WebSites\tem1\start.aspx.cs:line 46
Please tell me how can I read the data and check if the user and pass are the same as the ThextBox texts.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
String sCon = "SERVER=localhost;DATABASE=sd_tema1;UID=root;";
MySqlConnection con = new MySqlConnection(sCon);
if (CheckUserLogin(Label2.Text, Label3.Text))
{
Response.Redirect("login.aspx");
}
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
}
}
public Boolean CheckUserLogin(string username, string password)
{
try
{
String sCon = "SERVER=localhost;DATABASE=sd_tema1;UID=root;";
MySqlConnection con = new MySqlConnection(sCon);
String query = "Select * from users where username= ?userName and password= ?passWord";
MySqlCommand cmd = new MySqlCommand(query,con);
cmd.Parameters.Add("?userName", TextBox1.Text);
cmd.Parameters.Add("?passWord", TextBox2.Text);
cmd.Prepare();
MySqlDataReader print = cmd.ExecuteReader();
bool read = print.Read();
if(username.Equals(print.GetString("1")) && password.Equals(print.GetString("2"))) return true;
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
}
return false;
}
You didn't open the connection before calling ExecuteReader method. Call con.Open. Your issue will be resolved.

update cancel on gridview asp.net

I am trying to update a gridview on asp.net using a stored procedure but it always resets to the original values. What am I doing wrong?
edit: all page code added now
protected void page_PreInit(object sender, EventArgs e)
{
MembershipUser UserName;
try
{
if (User.Identity.IsAuthenticated)
{
// Set theme in preInit event
UserName = Membership.GetUser(User.Identity.Name);
Session["UserName"] = UserName;
}
}
catch (Exception ex)
{
string msg = ex.Message;
}
}
protected void Page_Load(object sender, EventArgs e)
{
userLabel.Text = Session["UserName"].ToString();
SqlDataReader myDataReader = default(SqlDataReader);
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RescueAnimalsIrelandConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("sp_EditRescueDetails", MyConnection);
if (!User.Identity.IsAuthenticated)
{
}
else
{
command.Parameters.AddWithValue("#UserName", userLabel.Text.Trim());
}
try
{
command.CommandType = CommandType.StoredProcedure;
MyConnection.Open();
myDataReader = command.ExecuteReader(CommandBehavior.CloseConnection);
// myDataReader.Read();
GridViewED.DataSource = myDataReader;
GridViewED.DataBind();
if (GridViewED.Rows.Count >= 1)
{
GridViewED.Visible = true;
lblMsg.Visible = false;
}
else if (GridViewED.Rows.Count < 1)
{
GridViewED.Visible = false;
lblMsg.Text = "Your search criteria returned no results.";
lblMsg.Visible = true;
}
MyConnection.Close();
}
catch (SqlException SQLexc)
{
Response.Write("Read Failed : " + SQLexc.ToString());
}
}
//to edit grid view
protected void GridViewED_RowEditing(object sender, GridViewEditEventArgs e)
{
GridViewED.EditIndex = e.NewEditIndex;
}
protected void GridViewED_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RescueAnimalsIrelandConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("sp_UpdateRescueDetails", MyConnection);
if (!User.Identity.IsAuthenticated)
{
}
else
{
command.Parameters.AddWithValue("#UserName", userLabel.Text.Trim());
command.Parameters.Add("#PostalAddress", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[0].Controls[0]).Text;
command.Parameters.Add("#TelephoneNo", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
command.Parameters.Add("#Website", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
command.Parameters.Add("#Email", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
}
command.CommandType = CommandType.StoredProcedure;
MyConnection.Open();
command.ExecuteNonQuery();
MyConnection.Close();
GridViewED.EditIndex = -1;
}
I suspect the code loading the grid is being invoked upon postback, which is causing the data to be pulled from the database when you don't want it to.
Yes - I think you want the code to only load if it is not a postback. You can use the Page.IsPostBack property for this.
Something like this:
protected void Page_Load(object sender, EventArgs e)
{
userLabel.Text = Session["UserName"].ToString();
if (!IsPostBack) {
SqlDataReader myDataReader = default(SqlDataReader);
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RescueAnimalsIrelandConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("sp_EditRescueDetails", MyConnection);
if (!User.Identity.IsAuthenticated)
{
}
else
{
command.Parameters.AddWithValue("#UserName", userLabel.Text.Trim());
}
try
{
command.CommandType = CommandType.StoredProcedure;
MyConnection.Open();
myDataReader = command.ExecuteReader(CommandBehavior.CloseConnection);
// myDataReader.Read();
GridViewED.DataSource = myDataReader;
GridViewED.DataBind();
if (GridViewED.Rows.Count >= 1)
{
GridViewED.Visible = true;
lblMsg.Visible = false;
}
else if (GridViewED.Rows.Count < 1)
{
GridViewED.Visible = false;
lblMsg.Text = "Your search criteria returned no results.";
lblMsg.Visible = true;
}
MyConnection.Close();
}
catch (SqlException SQLexc)
{
Response.Write("Read Failed : " + SQLexc.ToString());
}
}
}
Don't bind your data in the Page_Load event. Create a separate method that does it, then in the Page Load, if !IsPostback, call it.
The reason to perform the databinding is it's own method is because you'll need to call it if you're paging through the dataset, deleting, updating, etc, after you perform the task. A call to a method is better than many instances of the same, repetitive, databinding code.

Object reference not set to an instance of an object

I keep getting the following error and I don't know how to fix it. Any help would be great please
Exception Details:NullReferenceException was unhandled by users code: Object reference not set to an instance of an object.
protected void LbUpload_Click(object sender, EventArgs e)
{
ERROR: if(FileUpload.PostedFile.FileName == string.Empty)
{
LabelMsg.Visible = true;
return;
}
else
{
string[] FileExt = FileUpload.FileName.Split('.');
string FileEx = FileExt[FileExt.Length - 1];
if (FileEx.ToLower() == "csv")
{
FileUpload.SaveAs(Server.MapPath("CSVLoad//" + FileUpload.FileName));
}
else
{
LabelMsg.Visible = true;
return;
}
}
CSVReader reader = new CSVReader(FileUpload.PostedFile.InputStream);
string[] headers = reader.GetCSVLine();
DataTable dt = new DataTable();
foreach (string strHeader in headers)
dt.Columns.Add(strHeader);
string[] data;
while ((data = reader.GetCSVLine()) != null)
dt.Rows.Add(data);
GridView1.DataSource = dt;
GridView1.DataBind();
if (FileUpload.HasFile)
try
{
FileUpload.SaveAs(Server.MapPath("confirm//") +
FileUpload.FileName);
LabelGrid.Text = "File name: " +
FileUpload.PostedFile.FileName + "<br>" +
FileUpload.PostedFile.ContentLength + " kb<br>" +
"Content type: " +
FileUpload.PostedFile.ContentType + "<br><b>Uploaded Successfully";
}
catch (Exception ex)
{
LabelGrid.Text = "ERROR: " + ex.Message.ToString();
}
else
{
LabelGrid.Text = "You have not specified a file.";
}
File.Delete(Server.MapPath("confirm//" + FileUpload.FileName));
}
You are checking if the FileName is string.Empty, it sounds like you want to detect when the user clicked the button without selecting a file.
If that happens, the actual PostedFile property will be null (remember, the user didn't posted a file), you should use the FileUpload.HasFile property for that purpose:
protected void LbUpload_Click(object sender, EventArgs e)
{
if(FileUpload.HasFile)
{
LabelMsg.Visible = true;
return;
}
// ...
}
But I would recommend you also to add a RequiredFieldValidator.
More on validation:
Validating ASP.NET Server Controls
ASP.NET Validation in Depth
Are you sure that FileUpload and FileUpload.PostedFile is not null?
Either FileUpload or its PostedFile property must be null.

Resources