Database is not uploading after adding Session in ASP.NET - c#

In my website project, I made a register and login form, then I connected it to a database. The insertion was working. Now I added session to store the data of registration, but no data is getting inserted. In addition to this, I am not getting any change in codes too, where I made change if there is a session. Once it said that localhost refused to connect, but now the browser is not giving any error like that. Can anyone please help me figure out where the problem in my code is?
My C# code is:
protected void userRegister(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["Khulna_website"].ConnectionString;
string encoded_pass = encrypt_pass(Regi_Password.Text);
using(SqlConnection connection = new SqlConnection(constr))
{
string insertQuery = "insert into dbo.users(user_f_name,user_l_name,user_password,user_email,user_age, user_gender) values (#First_Name, #Last_Name, #Regi_Password, #Regi_Email, #Age, #Gender);";
SqlCommand com = new SqlCommand(insertQuery, connection);
connection.Open();
com.Parameters.AddWithValue("#First_Name", First_Name.Text);
com.Parameters.AddWithValue("#Last_Name", Last_Name.Text);
com.Parameters.AddWithValue("#Regi_Password", encoded_pass);
com.Parameters.AddWithValue("#Regi_Email", Regi_Email.Text);
com.Parameters.AddWithValue("#Age", Age.Text);
com.Parameters.AddWithValue("#Gender", Gender.SelectedValue);
try
{
com.ExecuteNonQuery();
com.CommandText = "Select * from dbo.users where email = " + Regi_Email.Text;
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
da.Fill(dt);
Session["User"]=dt.Rows[0]["user_f_name"];
Response.Redirect("default.aspx");
loginlabel.Text="Welcome, "+Session["User"];
connection.Close();
}
catch
{
Label1.Text = "Registration Error!";
}
}
The HTML is:
<form runat="server" method="post">
<div class="header">
<img id="icon" src="Images/logo.png">
<form>
<input type="text" id="search" placeholder="Search for people, place, locations">
<input type="submit" id="search_button" value="">
</form>
<span id= "login" runat="server" onclick="login();"><asp:Label ID="loginlabel" Text="" runat="server"></asp:Label></span>
</div>
<div>
<asp:ContentPlaceHolder id="Body" runat="server">
</asp:ContentPlaceHolder>
</div>
<div id="Sign_Up_Form" style="display: none">
<form class="modal-content animate">
<div class="input">
<div>
<div>Name</div>
<asp:TextBox CssClass="signUp_input" ID="First_Name" runat="server" placeholder="First Name" style="height: 20px; padding-left: 1px;"></asp:TextBox>
<asp:TextBox CssClass="signUp_input" ID="Last_Name" runat="server" placeholder="Last Name" style="height: 20px; padding-left: 1px;"></asp:TextBox>
</div>
<div>
<div>Email</div>
<asp:TextBox CssClass="signUp_input" ID="Regi_Email" runat="server" placeholder="Your email here" style="height: 20px; width:90%; padding-left: 1px;"></asp:TextBox>
</div>
<div>
<div>Password</div>
<asp:TextBox CssClass="signUp_input" ID="Regi_Password" type="password" runat="server" placeholder="**********" style="height: 20px; width: 90%; padding-left: 1px;"></asp:TextBox>
</div>
<div>
<div>Confirm Password</div>
<asp:TextBox CssClass="signUp_input" ID="Confirm_Regi_Password" type="password" runat="server" placeholder="**********" style="height: 20px; width: 90%; padding-left: 1px;"></asp:TextBox>
</div>
<div>
<div>Birth Date</div>
<asp:TextBox CssClass="signUp_input" ID="Age" type="number" runat="server" placeholder="dd/mm/yyyy" style="height: 20px; width: 90%; padding-left: 1px;"></asp:TextBox>
</div>
<div>
<div>Gender</div>
<asp:RadioButtonList CssClass="radio" ID="Gender" runat="server">
<asp:ListItem CssClass="radio" Value="1">Male</asp:ListItem>
<asp:ListItem CssClass="radio" Value="2">Female</asp:ListItem>
<asp:ListItem CssClass="radio" Value="3">Other</asp:ListItem>
</asp:RadioButtonList>
</br>
</div>
</div>
<asp:Button ID="Register_Button" runat="server" value="Join" OnClick="userRegister" CssClass="button_join" Text="Join" />
<asp:Label ID="Label1" CssClass="label" runat="server" Text=""></asp:Label>
</form>

I think the problem here is you are using the same SqlCommand that you have with the "insert" command to fill the data adapter (you don't change the command).
You can solve this three ways:
First one: Change the SqlCommand to a SELECT clause with the information you need to fill your session just before creating the DataAdapter.
Second one: Just fill your session with the form data like:
Session["user"] = Regi_Email.Text;
Session["user_name"] = First_Name.Text;
Of course you should handle the errors if the insert fails.
Third One: Use stored procedure so you can insert and fill the data adapter with a select in the same query.
IMHO i would prefer option 2 or 3.
Also i think you have to consider to have a better exception handling (Not all the errors that can actually happen are because the email is already in use) and you should consider using the "using" statement (https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement) for disposing/closing the objects (SqlCommand and SqlDataAdapter).
Hope this helps.

Related

ASP.Net white page of death after submit

We have two ASP.NET (4.0) web applications running on IIS 8.5. Periodically, the users will try to log in and after submitting their credentials, the page will reload into a white screen.
The response size is 0 bytes and has a 200 status. The login page will reload and the HTML will be displayed, but when you submit the form the white page will be displayed. This is solved when the application pool is recycled.
I have checked the IIS logs and event viewer and there are no errors or warning related to this issue.
The code for the login.aspx page is below:
<%# Page Title="" Language="C#" MasterPageFile="~/login.Master" AutoEventWireup="true" CodeBehind="login.aspx.cs" Inherits="Driver.login1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<style type="text/css">
.has-error {
color: red;
}
</style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div class="form-group">
<span id="spnInvalidAccount" runat="server" visible="false" class="has-error">Invalid Credentials</span>
</div>
<div class="form-group has-feedback">
<asp:TextBox TextMode="SingleLine" ID="txtEmail" CssClass="form-control" placeholder="Box Number" runat="server"></asp:TextBox>
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" CssClass="has-error" ControlToValidate="txtEmail" ErrorMessage="Careem Id Required" Display="Dynamic"></asp:RequiredFieldValidator>
</div>
<div class="form-group has-feedback">
<asp:TextBox ID="txtPassword" runat="server" CssClass="form-control" TextMode="Password" placeholder="Password"></asp:TextBox>
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" CssClass="has-error" ControlToValidate="txtPassword" ErrorMessage="Password Required" Display="Dynamic"></asp:RequiredFieldValidator>
</div>
<div class="row">
<!-- /.col -->
<div class="col-xs-8">
<span class="checkbox">
<div class="icheckbox_flat-red col-xs-1" aria-checked="false" aria-disabled="false" style="position: relative;">
<%--<asp:CheckBox ID="cbxRememberMe" runat="server" style="position: absolute; top: -20%; left: -20%; display: block; width: 140%; height: 140%; margin: 0px; padding: 0px; background: rgb(255, 255, 255); border: 0px; opacity: 0;" />--%>
<input id="Login1_RememberMe" runat="server" type="checkbox" name="Login1$RememberMe" style="position: absolute; top: -20%; left: -20%; display: block; width: 140%; height: 140%; margin: 0px; padding: 0px; background: rgb(255, 255, 255); border: 0px; opacity: 0;">
</div>
<label for="Login1_RememberMe" class="col-xs-9">Remember me</label>
</span>
</div>
<div class="col-xs-4">
<asp:Button ID="btnSubmit" Text="Sign In" runat="server" CssClass="btn btn-primary btn-block btn-flat" OnClick="btnSubmit_Click" />
</div>
<!-- /.col -->
</div>
</asp:Content>
And the code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Driver
{
public partial class login1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.QueryString["action"] != null && Request.QueryString["action"] == "logout")
{
HttpCookie loggedInCookie = new HttpCookie("LoggedIn");
loggedInCookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(loggedInCookie);
}
else if (Request.Cookies["LoggedIn"] != null && Request.Cookies["LoggedIn"].Value != null)
{
Response.Redirect("default.aspx");
}
}
if (Request.Cookies["LoggedIn"] != null && Request.Cookies["LoggedIn"].Value != null)
{
Response.Redirect("default.aspx");
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
using (DriverEntities cnx = new DriverEntities())
{
string password = Global.EncryptPassword(txtPassword.Text);
if (cnx.Drivers.Where(x => x.BoxNumber == txtEmail.Text && x.Password == password).Any())
{
Driver driver = cnx.Drivers.FirstOrDefault(x => x.BoxNumber == txtEmail.Text && x.Password == password);
Car car = cnx.Cars.FirstOrDefault(x => x.Id == driver.CarId);
HttpCookie loggedInCookie = new HttpCookie("LoggedIn");
loggedInCookie.Value = driver.Id.ToString();
if (!Login1_RememberMe.Checked)
loggedInCookie.Expires = DateTime.Now.AddHours(8);
else
loggedInCookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(loggedInCookie);
HttpCookie carCookie = new HttpCookie("MV_car");
carCookie.Value = car.Id.ToString();
Response.Cookies.Add(carCookie);
DateTime currentDate = DateTime.Now.AddDays(-1);
Response.Redirect("default.aspx");
}
else
{
spnInvalidAccount.Visible = true;
}
}
}
}
}
Some Remarks:
- I haven't been able to recreate this issue locally. This is only happening in the production environment.
- We use the same login page for a dozen other applications and we haven't had the same issue with them.
- The page is not redirecting to the default.aspx page.
- Customerrors is turned off so if there was an application error we would be able to see the exception screen

Asp.Net SQL Delete Statement

I have an Asp.net application and I am trying to delete a row from my 'Users' db if the user submits the requests via the web but I can't seem to get it to work.
HTML
<div class="panel panel-danger">
<div class="panel-heading">
<h3 class="panel-title">Remove User</h3>
</div>
<div class="panel-body">
<asp:Label ID="lbRemoveUser" runat="server" Text="Remove User">
<b>Enter Full Name</b>
</asp:Label>
<asp:TextBox runat="server" ID="txtRemoveUser" CssClass="form-control" AutoPostBack="true" OnTextChanged="txtRemoveUser_TextChanged" />
<asp:Label ID="removeUserNotExist" runat="server" Text="The user entered does not exist." Visible="false" style="color: red"></asp:Label>
</div>
<div class="panel-footer">
<div class="text-center">
<asp:Button CssClass="btn btn-danger" ID="btnSubmitRemoveUser" runat="server" Text="Remove User" ToolTip="Click to remove the user from the list." OnClick="removeUserSubmitButton_Click" />
</div>
</div>
</div>
<!-- Confirm Removal Modal-->
<div class="modal fade" id="confirmRemoveUserModal">
<div class="modal-dialog" style="margin-top: 55px">
<div class="modal-content">
<div class="modal-header ConfirmHeader">
<h4 class="modal-title" id="myModalLabel">Confirm Removal</h4>
</div>
<div class="modal-body">
<p>Are you sure you want to remove <b><%=Session["txtRemoveUser"] %></b> from the payday lunch list?</p>
<p>If you don't, click 'No' and the user will not be removed.</p>
</div>
<div class="modal-footer ConfirmFooter">
<asp:Button id="btnRemoveConfirmYes" runat="server" CssClass="btn btn-success" Text="Yes" OnClick="btnRemoveConfirmYes_Click" ToolTip="Click to remove the user from the payday lunch list." />
<asp:Button id="btnRemoveConfirmNo" runat="server" CssClass="btn btn-warning" Text="No" OnClick="btnAllCloses_Click" ToolTip="Click to close this screen. The user will not be removed." />
</div>
</div>
</div>
</div>
Code I tried
public void btnRemoveConfirmYes_Click(object sender, EventArgs e)
{
string connection = ConfigurationManager.ConnectionStrings["PaydayLunchConnectionString1"].ConnectionString;
SqlConnection conn = new SqlConnection(connection);
conn.Open();
SqlCommand cmd1 = new SqlCommand("DELETE FROM Users WHERE Name = " + txtRemoveUser.Text, conn);
conn.Close();
txtRemoveUser.Text = "";
Response.Redirect("/AdminSide/TaskList.aspx");
}
Like I said all I want is to delete the entry if it exists in my db. I already have a check to make sure that the entry exists in the 'Users' table
Do I need the SqlDataReader rd1 = cmd1.ExecuteReader(); as when I tried it, I got a server error "System.Data.SqlClient.SqlException: Invalid column name 'Test2'."
You are not using ExecuteNonQuery. You also have to wrap the user-name in apostrophes:
SqlCommand cmd1 = new SqlCommand("DELETE FROM Users WHERE Name = '" + txtRemoveUser.Text + "'", conn);
But you should always use sql parameters to prevent sql injection and other issues:
using(var cmd1 = new SqlCommand("DELETE FROM Users WHERE Name = #Name", conn))
{
cmd1.Parameters.Add("#Name", SqlDbType.VarChar).Value = txtRemoveUser.Text;
conn.Open();
cmd1.ExecuteNonQuery();
}
also use the using-statement on types that implement IDisposable like SqlCommand or -more important- SqlConnection to ensure that unmanaged resources are disposed.

Show product details in page

I need to show products details in a page.
My aspx is like below...
<div class="col-xs-12 col-sm-4 no-margin product-item-holder hover"> <!-- this div will be repeated for each product -->
<div class="product-item">
<div class="image">
<img runat="server" id="img" alt="" src="" />
</div>
<div class="body">
<div class="label-discount clear"></div>
<div class="title">
<a runat="server" id="name" href="single-product.html"></a>
</div>
</div>
<div class="prices">
<div class="price-prev"></div>
<div runat="server" id="price" class="price-current pull-right"></div>
</div>
<div class="hover-area">
<div class="add-cart-button">
Enquiry
</div>
</div>
</div>
and my codebehind is like below...
dbConnection cn = new dbConnection();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
getLoopData();
}
}
public void getLoopData()
{
cn.con.Open();
cn.cmd.Connection = cn.con;
cn.cmd.CommandText = "select * FROM products";
MySqlDataReader reader = cn.cmd.ExecuteReader();
while (reader.Read())
{
//int id = reader.GetInt32(0);
name.InnerText = reader["InventionName"].ToString();
price.InnerText = reader["Price"].ToString();
img.Src = reader["Picture"].ToString();
}
reader.Close();
cn.con.Close();
}
But it is showing only last product details.
How should I repeat the div for each product and how to show every products in page ??
You can use Asp Repeater to do that.
Check this link out : http://www.w3schools.com/aspnet/aspnet_repeater.asp
You need a datagrid control, repeater or similar to show tabular data.
Right now you only have one control per attribute to show all records, that's why last one wins.
Your view/page could be like this:
<asp:Repeater ID="ProductRepeater" runat="server" EnableViewState="False">
<ItemTemplate>
<div class="product-item">
<div class="image">
<img id="img" alt="" src='<%# Eval("Picture") %>' />
///...
</ItemTemplate>
</asp:Repeater>
In your code you could do this:
cn.con.Open();
cn.cmd.Connection = cn.con;
cn.cmd.CommandText = "SELECT InventionName, Price, Picture FROM products";
MySqlDataReader reader = cn.cmd.ExecuteReader();
ProductRepeater.DataSource = reader;
ProductRepeater.DataBind();
You are iterating a list, and assigning data to name, price and img.Src, but you overwrite the values on each iteration, therefore you only have the values from the last element.
You should bind you data source (reader) to an <asp:Repeater>'s DataSource property. In your markup you specify a header (HeaderTemplate), a footer (FooterTemplate) and content (ItemTemplate). You can omit the header and footer template if you don't need them. You can also use an AlternatingItemTemplate if you need to do different things with odd/even rows (e.g. alternating row color in a table).
You can access properties of the databound datatype using the <%# Eval("SomeProperty") %> which is a databinding expression.
HTML markup would be something like this:
<asp:Repeater id="Products" runat="server">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<div class="col-xs-12 col-sm-4 no-margin product-item-holder hover"> <!-- this div will be repeated for each product -->
<div class="product-item">
<div class="image">
<img class="img" alt="" src="<%# Eval("Picture") %>" />
</div>
<div class="body">
<div class="label-discount clear"></div>
<div class="title">
<a class="name" href="single-product.html"><%# Eval("InventionName") %></a>
</div>
</div>
<div class="prices">
<div class="price-prev"></div>
<div class="price" class="price-current pull-right"><%# Eval("Price") %></div>
</div>
<div class="hover-area">
<div class="add-cart-button">
Enquiry
</div>
</div>
</div>
</div>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>
and wire up the datasource in codebehind like this:
cn.con.Open();
cn.cmd.Connection = cn.con;
cn.cmd.CommandText = "select * FROM products";
MySqlDataReader reader = cn.cmd.ExecuteReader();
Products.DataSource = reader; // rather than iterating manually, you assign the datasource to the repeater.
Products.DataBind();
reader.Close();
cn.con.Close();
Side note: I changed the attribute from id to class on the name, price and img element. Because when this markup is rendered it would have been with multiple elements with the same id, which it shouldn't since id is supposed to be unique according to specification.

show asp.net progress bar for multiple operations

I need to show asp.net progress bar for three operations on webpage. First,when file upload the progress bar should show 33 % and message 'file upload started'. Once uploaded it should show message 'validating file data' and progress 66%. At third round, it should show 'automatching data' with 99%.
I have three methods that will be called one by one. I googled a lot but couldn't find a solution for this type of problem. Can someone please help?
If you want to show progress bar you need to introduce some java script or jquery code. I am sharing a sample code you can take idea from here
<form id="form1" runat="server">
<div style="text-align: left">
<asp:FileUpload ID="FileUpload1" runat="server" /> <br />
<br />
<asp:Button ID="Button1" runat="server" Text="Upload" OnClientClick="return ProgressBar()" OnClick="Button1_Click" /><br />
<br />
<div id="divUpload" style="display: none">
<div style="width: 300pt; text-align: center;">Uploading...</div>
<div style="width: 300pt; height: 20px; border: solid 1pt gray">
<div id="divProgress" runat="server" style="width: 1pt; height: 20px; background-color: Gray; display: none">
</div>
</div>
<div style="width: 300pt; text-align: center;">
<asp:Label ID="lblPercentage" runat="server" Text="Label"></asp:Label>
</div>
</div>
</div>
<br />
<asp:Label ID="Label1" runat="server" ForeColor="Red" Text=""></asp:Label>
</form>
<script language="javascript" type="text/javascript">
var size = 2;
var id = 0;
function ProgressBar() {
if (document.getElementById('<%=FileUpload1.ClientID %>').value != "") {
document.getElementById("divProgress").style.display = "block";
document.getElementById("divUpload").style.display = "block";
id = setInterval("progress()", 20);
return true;
}
else {
alert("Select a file to upload");
return false;
}
}
function progress() {
size = size + 1;
if (size > 299) {
clearTimeout(id);
}
document.getElementById("divProgress").style.width = size + "pt";
document.getElementById("<%=lblPercentage.ClientID %>").
firstChild.data = parseInt(size / 3) + "%";
}
</script>
protected void Button1_Click(object sender, EventArgs e)
{
// Do code here to saving a file from fileupload control
//FileUpload1.PostedFile.SaveAs("path");
System.Threading.Thread.Sleep(8000);
Label1.Text = "Upload successfull!";
}
Here is the source url - http://www.codeproject.com/Articles/26668/Showing-progress-bar-while-uploading-a-file-in-an

Not able to use javascript variable in code behind in C#

Guys I am using a jquery price range slider for getting Price range from user.But the problem is that the Price range selected by user on slider I have to use that in code behind.My code is like this:
My java script:
<script type="text/javascript">
//adding load class to body and hide page
document.documentElement.className += 'loadstate';
</script>
<script type ="text/javascript" >
var str1= document.getElementById("amt3").value;
var str2= document.getElementById("amt4").value;
document.getElementById("hf1").value = str1;
document.getElementById("hf2").value = str2;
</script>
</head>
My Html code is like this:
<asp:HiddenField ID="hf1" runat="server" />
<asp:HiddenField ID="hf2" runat="server" />
<div class="form-row row-fluid">
<div class="span12">
<div class="row-fluid">
<label class="form-label span4" for="slider">
Range slider</label>
<div class="span8">
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate >
<asp:HiddenField ID="HiddenField1" runat="server" />
<div id="slider-range" class="slider" >
</div>
<input type="text" id="amount1" style="border: 0; color: #ED7A53; font-weight: bold;
box-shadow: none;" />
<input type="text" id="amt3" style="border: 0; color: #ED7A53; font-weight: bold;
box-shadow: none;" />
<input type="text" id="amt4" name="amt4" style="border: 0; color: #ED7A53;
font-weight: bold; box-shadow: none;" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
</div>
and My code Behind is like this:
protected void lnkFilter_Click1(object sender, EventArgs e)
{
string str= hf1.Value;
if (WebHelper.Cast(amt2.Value, 0) != 0)
{
Fill();
}
}
But the Problem is hf1 (hidden field) is getting empty string value.Please help me in this and suggest me a solution how to use selected range on jquery slider in code behind file.
You should move your hidden values inside your Update panel as they will not get posted back to the server on a partial update.

Categories