Registration inserting into MS Access database multiple times - c#

My registration used to be working completely fine, but I have since done multiple modifications to it, so I can't find out what has caused this problem...
When I enter details and click Register, the page takes a long time to process, using the asp.net local server. It then finally says I've registered, but has entered 10-30 entries into the database (some aren't even identical, with different fields missing etc)
I can clear all the created entries in the database, then re-open it, and it has added 10-30 more... it will keep doing this until I kill the asp.net development server it creates when I "start without debugging".
Here is the c# file for the page:
using System;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.Mail;
public partial class Register : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
//Display welcome message
lblMessage.Text = "Welcome " + txtFirstName.Text + "!";
//Save the registration data into database, 17/8/2014
SaveRegistration();
sendEmail();
}
}
private void SaveRegistration()
{
OleDbConnectionStringBuilder sb = new OleDbConnectionStringBuilder();
sb.Provider = "Microsoft.ACE.OLEDB.12.0";
//sb.DataSource = Server.MapPath("/carpec02/asp_assignment/App_Data/shoeDB.accdb");
sb.DataSource = Server.MapPath("~/App_Data/shoeDB.accdb");
OleDbConnection myConnection = new OleDbConnection(sb.ConnectionString);
string queryString = "";
OleDbCommand myCmd = new OleDbCommand(queryString, myConnection);
//Open connection
myConnection.Open();
//Build the query string
StringBuilder queryStringBuilder = new StringBuilder("Insert into customer([customerFirstName], [customerLastName], [customerPassword], [customerPhHome], [customerPhWork], [customerPhMobile], [customerEmail], [customerPrivilege], [customerUsername])");
queryStringBuilder.Append("values ('");
queryStringBuilder.Append(txtFirstName.Text);
queryStringBuilder.Append("','");
queryStringBuilder.Append(txtLastName.Text);
queryStringBuilder.Append("','");
queryStringBuilder.Append(txtPassword.Text);
queryStringBuilder.Append("','");
queryStringBuilder.Append(txtPhHome.Text);
queryStringBuilder.Append("','");
queryStringBuilder.Append(txtPhWork.Text);
queryStringBuilder.Append("','");
queryStringBuilder.Append(txtPhMobile.Text);
queryStringBuilder.Append("','");
queryStringBuilder.Append(txtEmail.Text);
queryStringBuilder.Append("','");
queryStringBuilder.Append("User");
queryStringBuilder.Append("','");
queryStringBuilder.Append(txtUsername.Text);
queryStringBuilder.Append("')");
queryString = queryStringBuilder.ToString();
//Assign the QueryString to the command object
myCmd.CommandText = queryString;
//Execute the query
myCmd.ExecuteNonQuery();
//Create another command object to display the inserted record ID
OleDbCommand anotherCmd = new OleDbCommand("SELECT ##IDENTITY", myConnection);
int numId = Convert.ToInt32(anotherCmd.ExecuteScalar());
lblDataId.Text = "<h3>Your registration number is <big>" + numId.ToString() + "</big></h3>";
//Close the connection
myConnection.Close();
}
//Modified from http://www.aspsnippets.com/Articles/How-to-create-Contact-Us-Page-in-ASPNet.aspx
protected void sendEmail()
{
try
{
string strReceiver = txtEmail.Text;
MailMessage mm = new MailMessage("fakeemail#gmail.com", strReceiver); //Sender / receiver
mm.Subject = "Welcome to Awesome Shoes!";
mm.Body = "Thank you, " + txtFirstName.Text + " " + txtLastName.Text + ", for registering at Awesome Shoes. Your username is: " + txtUsername + " and your password is " + txtPassword;
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = "fakeemail#gmail.com";
NetworkCred.Password = "fake123";
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
lblMessage2.Text = "Email Sent Sucessfully.";
}
catch
{
}
}
}
and here is the asp.net code for the page:
<%# Page Title="" Language="C#" MasterPageFile="~/AwesomeShoes.master" AutoEventWireup="true" CodeFile="Register.aspx.cs" Inherits="Register" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TabTitle" Runat="Server">
Register - Awesome Shoes
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="Head" Runat="Server">
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="CurrentTabRegister" Runat="Server">
class="currentTab"
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainTitle" Runat="Server">
Register
</asp:Content>
<asp:Content ID="Content5" ContentPlaceHolderID="MainBody" Runat="Server">
<script type="text/javascript">
function IsInteger(input) {
var regEx = /^\+{0,1}\d+\d*$/;
return regEx.test(input);
}
function btnRegister_OnClick()
{
var txtFirstName = document.getElementById('MainBody_txtFirstName');
if (txtFirstName.value.length == 0)
{
alert("You must enter all the required information before submitting");
return;
}
var txtEmail = document.getElementById('MainBody_txtEmail');
if (txtEmail.value.indexOf('#') == -1)
{
alert("You must enter an # for your email address.");
return;
}
var txtPassword = document.getElementById('MainBody_txtPassword');
if (txtPassword.value.length < 6) {
alert("Your password must be at least 6 characters long");
return;
}
var txtRepeatPassword = document.getElementById('MainBody_txtRepeatPassword');
if (txtRepeatPassword.value != txtPassword.value) {
alert("Your password does not match");
return;
}
var txtPhHome = document.getElementById('MainBody_txtPhHome');
var txtPhWork = document.getElementById('MainBody_txtPhWork');
var txtPhMobile = document.getElementById('MainBody_txtPhMobile');
if ((!IsInteger(txtPhHome.value)) && (!IsInteger(txtPhWork.value)) && (!IsInteger(txtPhMobile.value)))
{
alert('You must enter at least one phone number.');
return;
}
if (IsInteger(txtPhHome.value))
{
if (txtPhHome.value < 1000000 || txtPhHome.value > 9999999) {
alert('The home phone number you entered is invalid. It must be between 100-0000 and 999-9999');
return;
}
}
if (IsInteger(txtPhWork.value)) {
if (txtPhWork.value < 1000000 || txtPhWork.value > 9999999) {
alert('The work phone number you entered is invalid. It must be between 100-0000 and 999-9999');
return;
}
}
if (IsInteger(txtPhMobile.value)) {
if (txtPhMobile.value < 0210000000 || txtPhMobile.value > 0299999999) {
alert('The mobile phone number you entered is invalid. It must be between 021-000-0000 and 029-999-9999');
return;
}
}
document.getElementById('form1').submit();
}
</script>
<div>
<table>
<tr><td>First Name:</td><td><asp:TextBox ID="txtFirstName" Width="150" runat="server"></asp:TextBox></td></tr>
<tr><td>last Name:</td><td><asp:TextBox ID="txtLastName" Width="150" runat="server"></asp:TextBox></td></tr>
<tr><td>Username:</td><td><asp:TextBox ID="txtUsername" Width="150" runat="server"></asp:TextBox></td></tr>
<tr><td>Password:</td><td><asp:TextBox ID="txtPassword" Width="150" runat="server"></asp:TextBox></td></tr>
<tr><td>Repeat Password:</td><td><asp:TextBox ID="txtRepeatPassword" Width="150" runat="server"></asp:TextBox></td></tr>
<tr><td>Email:</td><td><asp:TextBox ID="txtEmail" Width="150" runat="server"></asp:TextBox></td></tr>
<tr><td>Home Phone:</td><td><asp:TextBox ID="txtPhHome" Width="150" runat="server"></asp:TextBox></td></tr>
<tr><td>Work Phone:</td><td><asp:TextBox ID="txtPhWork" Width="150" runat="server"></asp:TextBox></td></tr>
<tr><td>Mobile Phone:</td><td><asp:TextBox ID="txtPhMobile" Width="150" runat="server"></asp:TextBox></td></tr>
</table>
<input type="button" class="caption" value="Register" id="btnRegister" name="btnRegister" onclick="btnRegister_OnClick()"/>
<br/>
<asp:Label ID="lblMessage" runat="server" class="message"></asp:Label>
<br/>
<asp:Label ID="lblMessage2" runat="server" class="message"></asp:Label>
<br/>
<asp:Label ID="lblDataId" runat="server"></asp:Label>
</div>
</asp:Content>
Appreciate any help as to why this may be happening, as the assignment is due later today.

Instead of passing these methods in Page Load, write them into the button click event as.
protected void btnRegister_Click(object sender, EventArgs e)
{
//Save the registration data into database, 17/8/2014
SaveRegistration();
sendEmail();
}
Change the html markup of Register button as,
<asp:Button type="button" CssClass="caption" Text="Register" ID="btnRegister" onclick="btnRegister_Click" onClientClick="javascript:btnRegister_OnClick();"/>

Related

ASP.NET Textbox text does not change while trying to update

I have a form where there is a ListBox, a textbox and four buttons called Save, Edit, Delete and Clear. I'm retrieving data from database and populating the ListBox. When I select one of the items in the ListBox, it is populated into the textbox. Now when I delete that item, there is nothing wrong, it works fine. But when I try to update that item, i.e. change the text in the textbox and then click the Edit button, there is problem. In the textbox, I can see the text is being changed, no problem with that, but when I debugged, I found in the backend, the textbox is still containing the old text and not the modified one.
What am I doing wrong?
Here's my UI code:
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
<h1>Employee Category</h1>
<table>
<td>
<asp:ListBox ID="listEmployeeCategory" runat="server" Height="164px" Width="210px" AutoPostBack="true" />
</td>
<td>
<table>
<tr>
<td>
<asp:Label ID="lblMessage" runat="server" Text="" Visible="false" />
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblEmpCategoryName" runat="server" Text="Name: " Font-Bold="true" />
</td>
<td>
<asp:TextBox ID="txtEmpCategoryName" runat="server" />
</td>
<td>
<asp:RequiredFieldValidator ID="rqdEmpCategoryName" ControlToValidate="txtEmpCategoryName" ErrorMessage="Employee Category Name can't be empty!" Style="color:Red" runat="server" />
</td>
</tr>
</table>
<asp:Button ID="btnSave" Text="Save" runat="server" OnClick="btnSave_Click" />
<asp:Button ID="btnEdit" Text="Edit" runat="server" OnClick="btnEdit_Click" />
<asp:Button ID="btnDelete" Text="Delete" runat="server" OnClick="btnDelete_Click" />
<asp:Button ID="btnCancel" Text="Cancel" runat="server" />
</td>
</table>
</asp:Content>
And here's my backend code, for the sake of everyone's understanding, I'm posting my entire backend code (except the BL, DAL and DAO codes):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Shelter.DAO.MasterEntry;
using Shelter.BLL.MasterEntry;
namespace Shelter.UI.MasterEntry
{
public partial class EmployeeCategoryUI : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadDataIntoListBox();
}
else
{
if (listEmployeeCategory.SelectedIndex != -1)
{
LoadDataIntoTextBox(Convert.ToInt32(listEmployeeCategory.SelectedValue));
}
}
}
private void LoadDataIntoTextBox(int val)
{
EmployeeCategory objEmployeeCategory = new EmployeeCategory();
EmployeeCategoryBLL empCategoryBLL = new EmployeeCategoryBLL();
objEmployeeCategory.ID = Convert.ToInt32(val);
DataTable EmpCategoryDt = new DataTable();
EmpCategoryDt = empCategoryBLL.RetrieveById(objEmployeeCategory);
txtEmpCategoryName.Text = EmpCategoryDt.Rows[0]["EmpCategoryName"].ToString();
}
private void LoadDataIntoListBox()
{
EmployeeCategory objEmployeeCategory = new EmployeeCategory();
EmployeeCategoryBLL empCategoryBLL = new EmployeeCategoryBLL();
DataSet EmployeeCategoryDs = new DataSet();
EmployeeCategoryDs = empCategoryBLL.RetreiveFromTable();
DataTable EmployeeCategoryDt = EmployeeCategoryDs.Tables[0];
DataRow tempRow = null;
foreach (DataRow tempRow_Variable in EmployeeCategoryDt.Rows)
{
tempRow = tempRow_Variable;
string rowText = tempRow["EmpCategoryName"] + "(" + tempRow["ID"] + ")";
string rowValue = tempRow["ID"].ToString();
listEmployeeCategory.Items.Add(new ListItem(rowText, rowValue));
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
EmployeeCategory objEmployeeCategory = new EmployeeCategory();
EmployeeCategoryBLL empCategoryBLL = new EmployeeCategoryBLL();
objEmployeeCategory.EmpCategoryName = txtEmpCategoryName.Text;
bool isSave = empCategoryBLL.SaveToTable(objEmployeeCategory);
if (isSave)
{
int id = empCategoryBLL.ReturnLastInsertedId();
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Green");
lblMessage.Text = "Data saved successfully!";
string rowText = txtEmpCategoryName.Text + "(" +id.ToString()+ ")" ;
string rowValue = id.ToString();
listEmployeeCategory.Items.Add(new ListItem(rowText, rowValue));
txtEmpCategoryName.Text = "";
}
else
{
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Red");
lblMessage.Text = "Data saving failed!";
}
}
protected void btnEdit_Click(object sender, EventArgs e)
{
if (IsPostBack)
{
EmployeeCategory objEmployeeCategory = new EmployeeCategory();
EmployeeCategoryBLL empCategoryBLL = new EmployeeCategoryBLL();
objEmployeeCategory.EmpCategoryName = txtEmpCategoryName.Text;
objEmployeeCategory.ID = Convert.ToInt32(listEmployeeCategory.SelectedValue);
bool isEdit = empCategoryBLL.EditInTable(objEmployeeCategory);
if (isEdit)
{
int id = objEmployeeCategory.ID;
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Green");
lblMessage.Text = "Data edited successfully!";
}
else
{
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Red");
lblMessage.Text = "Data editing failed!";
}
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
if (IsPostBack)
{
EmployeeCategory objEmployeeCategory = new EmployeeCategory();
EmployeeCategoryBLL empCategoryBLL = new EmployeeCategoryBLL();
objEmployeeCategory.ID = Convert.ToInt32(listEmployeeCategory.SelectedValue);
bool isDelete = empCategoryBLL.DeleteFromTable(objEmployeeCategory);
if (isDelete)
{
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Green");
lblMessage.Text = "Data deleted successfully!";
listEmployeeCategory.Items.Remove(new ListItem(listEmployeeCategory.SelectedItem.Text, listEmployeeCategory.SelectedValue));
txtEmpCategoryName.Text = "";
}
else
{
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Red");
lblMessage.Text = "Data deleting failed!";
}
}
}
}
}
The txtEmpCategoryName.Text is still containing the old value, so whenever I try to update, it only takes the old value and not the modified value in the textbox. It seems that the TextChanged event is not working. What is the fix to this problem?
You can use Entity frame in Visual studio;
right click on your solution - select new Add - then New Project - C# -Class Library give it a project name and Click Ok to add a new project to your existing project.
rename your class to a meaning name such as BusinessLogic and make it public.
right click on the newly added project and select add new item, on your popup windows select data on the right panel then select ADO.NET Entity Data Model rename your edmx to a meaningful name and click on add. default option and click on next, point to your SQL database by clicking on the new Connection.
select your store procedure for populating your listbox and updating the description and click on Finish.
CREATE PROCEDURE Proc_name AS BEGIN SET NOCOUNT ON;
SELECT ID,Description FROM Table_Name END
CREATE PROCEDURE [dbo].[UpdateEmpCategoryBLL]
#ID int, #Description varchar(50) AS BEGIN
SET NOCOUNT ON;
UPDATE Question1 SET Description = #Description WHERE ID = #ID
END
In your class Implement your methods for populating listbox and updating the description
public class Wrapper
{
public static List EmployeeCategory()
{
try
{
return new LOOKUPEntities().empCategoryBLL().ToList();
}
catch (Exception)
{
throw;
}
}
public static void UpdateEmpCategory(int id, string description)
{
try
{
using (LOOKUPEntities client = new LOOKUPEntities())
{
client.UpdateEmpCategoryBLL(id, description);
}
}
catch (Exception)
{
throw;
}
}
}
copy the connection string from you app.config to your web.config. Then add your class library to your references by right clicking on your references and select add reference, select solution and click on add. Add also System.Data,Entity and click ok.
now;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindListBox();
}
}
protected void BindListBox()
{
try
{
ListItem lstBox;
listEmployeeCategory.Items.Clear();
var query = Wrapper.EmployeeCategory();
foreach (var items in query)
{
lstBox = new ListItem(items.Description, items.ID.ToString());
listEmployeeCategory.Items.Add(lstBox);
}
}
catch(Exception ex)
{
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Red");
lblMessage.Text = "Data loading failed "+ ex +" !";
}
}
protected void listEmployeeCategory_SelectedIndexChanged(object sender, EventArgs e)
{
lblMessage.Visible = false;
try
{
Session["ID"] = listEmployeeCategory.SelectedValue.ToString();
txtEmpCategoryName.Text = listEmployeeCategory.SelectedItem.ToString();
}
catch (Exception ex)
{
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Red");
lblMessage.Text = "Loading session data failed " + ex + " !";
}
}
protected void btnEdit_Click(object sender, EventArgs e)
{
try
{
int id = int.Parse(Session["ID"].ToString());
Wrapper.UpdateEmpCategory(id, txtEmpCategoryName.Text.Trim());
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Green");
lblMessage.Text = "Data edited successfully!";
BindListBox();
txtEmpCategoryName.Text = string.Empty;
}
catch
{
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Red");
lblMessage.Text = "Data editing failed!";
}
}
done!

ASP.NET Repeater not binding

I have issues.
One of them is this one.
I'm trying to bind a list of Hyperlinks to a repeater and I think my code looks all good, but my repeater is sadly lacking in anything. It's totally blank (Apart from the header, which is not databound).
I can't see where the problem is, so I'm hoping you guys can point it out to me.
Code:
Markup
<asp:Panel ID="pnlNavMenu" class="navigation" runat="server" Visible="true">
<div class="search-textbox"><div>
<asp:ImageButton ID="btnSearch" class="Search-Icon"
BackColor="White" runat="server" OnClick="btnSearch_Click"
ImageUrl="~/images/Mobile/mobile-search-icon.png" />
<asp:TextBox ID="txtSearch" runat="server" CssClass="Search" onblur="if(this.value == '') { this.value='Enter keyword or product code'; isSet=true; }"
onmouseover="if(this.value == 'Enter keyword or product code') { this.value='';isSet = true; }"
onmouseout="if(this.value == '' && !isSet) { this.value='Enter keyword or product code'; isSet=>false; }"
MaxLength="255" Text="Enter keyword or product code" ontextchanged="btnSearch_Click"/>
<asp:ImageButton ID="btnClear" class="Search-Cancel" BackColor="White" runat="server" OnClick="btnClear_Click" ImageUrl="~/images/Mobile/mobile-search-cancel.png" />
</div>
</div>
<asp:Panel ID="pnlComputers" runat="server" CssClass="nav-item" Visible="true">
<asp:Label id="lblComp" Text="Computers" runat="server" cssclass="Menu-Panel-Header"></asp:Label>
<asp:Repeater ID="rptComputers" runat="server">
<ItemTemplate><asp:HyperLink ID="hlCompCategories" runat="server" CssClass="nav-sub-item"><%#Eval("XW_WEBCATNAME") %></asp:HyperLink></ItemTemplate>
</asp:Repeater>
</asp:Panel
<asp:CollapsiblePanelExtender ID="cpe1" runat="Server" TargetControlID="pnlComputers" CollapsedSize="64" ExpandedSize="192" Collapsed="True" ExpandControlID="lblComp" CollapseControlID="lblComp" AutoCollapse="false" AutoExpand="False" ScrollContents="True" ExpandDirection="Vertical" />
</asp:Panel>
C#
protected void Page_Init(object sender, EventArgs e)
{
if (Session["Customer"] is GPCUser)
{
hlLogInOut.Text = "Log Out";
hlLogInOut.NavigateUrl = "log-in.aspx?logout=1";
hlRegDetails.Text = "My Details";
hlRegDetails.NavigateUrl = "/update-details.aspx";
}
else
{
hlLogInOut.Text = "Log in";
hlLogInOut.NavigateUrl = "/log-in.aspx";
hlRegDetails.Text = "Register";
hlRegDetails.NavigateUrl = "/create-account.aspx";
}
BindCategories();
}
private void BindCategories()
{
if (!IsPostBack)
{
try
{
SqlConnection connect = new SqlConnection();
DataTable Data = new DataTable();
connect.ConnectionString = "SERVER = SERVER-SQL01; Trusted_Connection=yes; DATABASE=PCSQL";
connect.Open();
string query = null;
query = "SELECT * from dbo.STOCK_GROUPS WHERE XW_MAINGROUP = '1' ORDER BY XW_WEBCATNAME ASC";
SqlDataAdapter command = new SqlDataAdapter(query, connect);
command.Fill(Data);
connect.Close();
rptComputers.DataSource = Data;
}
catch (SqlException sqlEX)
{
sqlEX.ToString();
}
}
}
protected void rptComputers_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem)
{
HyperLink hlCompCategories = (HyperLink)e.Item.FindControl("hlCompCategories");
DataRowView dr = (DataRowView)e.Item.DataItem;
hlCompCategories.NavigateUrl = Page.ResolveUrl("~/" + "Computers" + "/" + dr["XW_URL"] + "/index.aspx");
if ((!object.ReferenceEquals(dr["xw_webcatname"], System.DBNull.Value)))
{
hlCompCategories.Text = (dr["xw_webcatname"]).ToString();
hlCompCategories.ToolTip = (dr["xw_webcatname"]).ToString();
}
else
{
hlCompCategories.Text = dr["groupname"].ToString();
hlCompCategories.ToolTip = dr["xw_webcatname"].ToString();
}
}
}
I'm pretty sure that the issue is in the ItemDataBound method because the rest of the panel loads fine (search bar and header, etc.) but none of my links are there.
After
rptComputers.DataSource = Data;
add
rptComputers.DataBind();
Otherwise it won't bind.
You might be missing AutoEventWireup=true in Page header in aspx file.
If not than please try to bind the repeater in the Page_Load event instead binding in Page_Init event.

Buttons work only on the second click

I`m trying to make an ASP.NET basic site that connects to a database. It's supposed to allow a user to register and log in.
I check the input with javascript and in the code behind in case it's disabled.
The problem is that whenever i click the register, login, or logout buttons for the first time they won't work; The page remains the same.
The second time, however, they work perfectly.
Debugger says it's called both times.
any ideas?
ASP:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Main.aspx.cs"
Inherits="Register_and_Login.Main" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<script type="text/javascript">
function isUserValid() {
var UserLength = document.getElementById("UserTB").value.length;
var ValidatorLabel = document.getElementById("ValidateUser");
if (UserLength < 6 || UserLength > 15) {
ValidatorLabel.style.display = 'inline';
return false;
}
else {
ValidatorLabel.style.display = 'none';
return true;
}
}
function isPassValid() {
var PassLength = document.getElementById("PasswordTB").value.length;
var ValidatorLabel = document.getElementById("ValidatePassword");
if (PassLength < 6 || PassLength > 15) {
ValidatorLabel.style.display = 'inline';
return false;
}
else {
ValidatorLabel.style.display = 'none';
return true;
}
}
function isConfirmValid() {
var Password = document.getElementById("PasswordTB").value;
var Me = document.getElementById("ConfirmTB").value;
var ValidatorLabel = document.getElementById("ValidateConfirm");
if (Password == Me) {
ValidatorLabel.style.display = 'none';
return true;
}
else {
ValidatorLabel.style.display = 'inline';
return false;
}
}
function isEmailValid() {
var str = document.getElementById("EmailTB").value;
var lastAtPos = str.lastIndexOf('#');
var lastDotPos = str.lastIndexOf('.');
var isFine = (lastAtPos < lastDotPos && lastAtPos > 0 && str.indexOf('##') == -1 && lastDotPos > 2 && (str.length - lastDotPos) > 2);
var ValidationLabel=document.getElementById("ValidateEmail");
if(isFine)
{
ValidationLabel.style.display='none';
return true;
}
else
{
ValidationLabel.style.display='inline';
return false;
}
}
</script>
<title></title>
<style type="text/css">
.Validators
{
display:none;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Panel id="RegisterRelated" runat="server">
Username:<br />
<asp:TextBox ID="UserTB" runat="server" OnChange="isUserValid()" AutoPostBack="false"></asp:TextBox>
<asp:Label ID="ValidateUser" runat="server" ForeColor="Red"
Text="Username must be 6-15 characters in length, and contain no special characters." CssClass="Validators"></asp:Label>
<br />
Password:<br />
<asp:TextBox ID="PasswordTB" runat="server" OnChange="isPassValid()" AutoPostBack="false"></asp:TextBox>
<asp:Label ID="ValidatePassword" runat="server" ForeColor="Red"
Text="Password must be 6-15 characters in length, and contain no special characters." CssClass="Validators"></asp:Label>
<br />
Confirm password:<br />
<asp:TextBox ID="ConfirmTB" runat="server" OnChange="isConfirmValid()" AutoPostBack="false"></asp:TextBox>
<asp:Label ID="ValidateConfirm" runat="server" ForeColor="Red"
Text="This field must match the password field." CssClass="Validators"></asp:Label>
<br />
Email:<br />
<asp:TextBox ID="EmailTB" runat="server" OnChange="isEmailValid()" AutoPostBack="false"></asp:TextBox>
<asp:Label ID="ValidateEmail" runat="server" ForeColor="Red" Text="Invalid Email." CssClass="Validators"></asp:Label>
<br />
<br />
<asp:Button ID="Register" runat="server" Text="Register" onclick="Register_Click" EnableViewState="false"/>
<br />
<asp:Panel ID="Answer" runat="server" >
</asp:Panel>
</asp:Panel>
<br />
<br />
<asp:Panel id="LoginRelated" runat="server">
User:
<asp:TextBox ID="LoginUserTB" runat="server" AutoPostBack="false"></asp:TextBox>
<br />
Password:
<asp:TextBox ID="LoginPassTB" runat="server" AutoPostBack="false"></asp:TextBox>
<br />
<asp:Button ID="Login" runat="server" Text="Login" onclick="Login_Click" EnableViewState="false" />
<br />
</asp:Panel>
<asp:Panel ID="InPage" runat="server">
<asp:Panel ID="LogAnswer" runat="server">
</asp:Panel>
<br />
<asp:Label ID="WelcomeTag" runat="server"></asp:Label>
<br />
<br />
<asp:Button ID="logout" runat="server" onclick="logout_Click" Text="Logout" EnableViewState="false"/>
</asp:Panel>
</div>
</form>
</body>
</html>
C# Login, Logout & Register buttons:
protected void Register_Click(object sender, EventArgs e)
{
Label Reply = new Label();
if (Session["User"] == null)
{
Result myRegResult = Result.IN_PROG;
User myAddedUser = new User(UserTB.Text, PasswordTB.Text, EmailTB.Text);
DbManager.OpenDbConnection();
myRegResult = DbManager.Register(myAddedUser); //Connection with the database.
Reply.Text = resultToString(myRegResult);
Reply.ForeColor = resultColor(myRegResult);
}
else
{
Reply.Text = "You must log out before you register.";
Reply.ForeColor = resultColor(Result.EXEC_ERROR);
}
Answer.Controls.Add((Control)Reply);
//Reset_Fields();
}
protected void Login_Click(object sender, EventArgs e)
{
Label Reply = new Label();
LoginProc Status = LoginProc.IN_PROG;
DbManager.OpenDbConnection();
Status = DbManager.Login(LoginUserTB.Text, LoginPassTB.Text); //Connection with the database
Reply.Text = ProcToString(Status);
Reply.ForeColor = ProcToColor(Status);
LogAnswer.Controls.Add(Reply);
if (Status == LoginProc.FINE)
Session["User"] = new User(LoginUserTB.Text, LoginPassTB.Text, null);
//Reset_Fields();
}
protected void logout_Click(object sender, EventArgs e)
{
Session["User"] = null;
}
Page load:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["User"] != null)
{
RegisterRelated.Visible = false;
LoginRelated.Visible = false;
InPage.Visible = true;
WelcomeTag.Text = "Welcome, " + ((User)Session["User"]).Username + ".";
}
else
{
RegisterRelated.Visible = true;
LoginRelated.Visible = true;
WelcomeTag.Text = String.Empty;
InPage.Visible = false;
}
}
EDIT: A friend of mine adviced me to take a look in the ASP.NET page lifecycle, and it might have something to do with the database interactions being done after the page is presented, if it helps anyone.
Your friend is correct, you need to understand the page the Page Life cycle better. Basically in this instance you need to understand that the OnLoad event happens before any click events. You can see this for yourself by adding a break point to the OnLoad event and the click handler. You will see that the order of events as they happen.
In this instance I would writ a method to set up the page, and then call this in each of the on click events
private void setUpPage()
{
if (Session["User"] != null)
{
RegisterRelated.Visible = false;
LoginRelated.Visible = false;
InPage.Visible = true;
WelcomeTag.Text = "Welcome, " + ((User)Session["User"]).Username + ".";
}
else
{
RegisterRelated.Visible = true;
LoginRelated.Visible = true;
WelcomeTag.Text = String.Empty;
InPage.Visible = false;
}
}
protected void Page_Load(object sender, EventArgs e)
{
//Call if not in response to button click
if(!IsPostBack)
{
setUpPage();
}
}
protected void Register_Click(object sender, EventArgs e)
{
Label Reply = new Label();
if (Session["User"] == null)
{
Result myRegResult = Result.IN_PROG;
User myAddedUser = new User(UserTB.Text, PasswordTB.Text, EmailTB.Text);
DbManager.OpenDbConnection();
myRegResult = DbManager.Register(myAddedUser); //Connection with the database.
Reply.Text = resultToString(myRegResult);
Reply.ForeColor = resultColor(myRegResult);
}
else
{
Reply.Text = "You must log out before you register.";
Reply.ForeColor = resultColor(Result.EXEC_ERROR);
}
Answer.Controls.Add((Control)Reply);
//Reset_Fields();
//Reset the fields as required AFTER you have done what you need with the database
setUpPage();
}
protected void Login_Click(object sender, EventArgs e)
{
Label Reply = new Label();
LoginProc Status = LoginProc.IN_PROG;
DbManager.OpenDbConnection();
Status = DbManager.Login(LoginUserTB.Text, LoginPassTB.Text); //Connection with the database
Reply.Text = ProcToString(Status);
Reply.ForeColor = ProcToColor(Status);
LogAnswer.Controls.Add(Reply);
if (Status == LoginProc.FINE)
Session["User"] = new User(LoginUserTB.Text, LoginPassTB.Text, null);
//Reset_Fields();
//Reset the fields as required AFTER you have done what you need with the database
setUpPage();
}
protected void logout_Click(object sender, EventArgs e)
{
Session["User"] = null;
//Reset the fields as required AFTER you have done what you need with the database
setUpPage();
}
When you click the login or register button, page load event works firstly, and after button click event works.
I can see that, you set to page display in page load event and set to Session value in button click event. So at first click, page load event triggered first, but there is no Session value yet. Page load event finishes and resume with button click event, so Session value is not null now (if entered user info is valid).
It is the reason why page work at second click.
Solution:
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack) //just write this
return;
if (Session["User"] != null)
{
RegisterRelated.Visible = false;
LoginRelated.Visible = false;
InPage.Visible = true;
WelcomeTag.Text = "Welcome, " + ((User)Session["User"]).Username + ".";
}
else
{
RegisterRelated.Visible = true;
LoginRelated.Visible = true;
WelcomeTag.Text = String.Empty;
InPage.Visible = false;
}
}
Note: I got your code and tried.
Also see this: http://msdn.microsoft.com/en-us/library/ms178472%28v=vs.85%29.aspx
I think there is issue with validators. Please set causes validation property of buttons according to your requirements.
Try Page_BlockSubmit = false; before every return false;

refresh page after 3 seconds using c#

I want my code to refresh the page once its shown the success label for 3 seconds.
How can i do this in c# code?
i have this following:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.IO;
public partial class CAPTCHA_Contact : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//ImageVerification
if (!IsPostBack)
{
SetVerificationText();
}
imCaptcha.ImageUrl = "captcha.ashx?d=" + DateTime.Now.Ticks;
}
public void SetVerificationText()
{
Random ran = new Random();
int no = ran.Next();
Session["Captcha"] = no.ToString();
}
protected void CAPTCHAValidate(object source, ServerValidateEventArgs args)
{
if (Session["Captcha"] != null)
{
if (txtVerify.Text != Session["Captcha"].ToString())
{
SetVerificationText();
args.IsValid = false;
return;
}
}
else
{
SetVerificationText();
args.IsValid = false;
return;
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
{
return;
}
SetVerificationText();
//Save the content
MailMessage mail = new MailMessage();
mail.From = new MailAddress(EmailTB.Text);
mail.To.Add("name#company.co.uk");
mail.Bcc.Add("test#test.co.uk");
mail.Subject = "Web Quote";
mail.IsBodyHtml = true;
mail.Body = "First Name: " + FNameTB.Text + "<br />";
mail.Body += "Email: " + EmailTB.Text + "<br />";
mail.Body += "Telephone: " + TelephoneTB.Text + "<br />";
mail.Body += "Query: " + QueryDD.Text + "<br />";
mail.Body += "Comments: " + CommentsTB.Text + "<br />";
SmtpClient smtp = new SmtpClient();
smtp.Host = "localhost";
smtp.Send(mail);
sucessPH.Visible = true;
}
protected void Reset(object s, EventArgs e)
{
FNameTB.Text = "";
QueryDD.Text = "";
EmailTB.Text = "";
TelephoneTB.Text = "";
CommentsTB.Text = "";
txtVerify.Text = "";
}
}
So after sucessPH.Visible = true; i need to count 3 seconds and then refresh the page. This will then clear the form data and the user will also get 3 seconds to see the message to say the message was successfull.
Any ideas?
Since this is a client-side concern and not a server-side concern, you'll want to do this with JavaScript. Keep in mind that by the time the page is sent to the client all of the server-side code has completed and disposed. Trying to do this with server-side code will result in a lot of unnecessary complexity in this case.
In JavaScript you can reload the page with a delay with something like this:
setTimeout("window.location.reload()", 3000);
Well, if you're using webforms, you could use an update panel, and then use the timer component, just like this guy've done
Tutorial: How to refresh an UpdatePanel control at a timed interval
Right after sucessPH.Visible = true; add following line: ClientScript.RegisterClientScriptBlock(this.GetType(), "refresh", "setTimeout('window.location.href=window.location.href', 3000);", true);
Well.. you are in a web..
So your server can count 3, but you need the client to count 3 and then postback it to the server...
If your server only counts, then the user will not view anything..
Just make your application ajax enable, and use a timer ;)
This is the code for the page
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Timer ID="Timer1" runat="server" Interval="3000" ontick="Timer1_Tick">
</asp:Timer>
</div>
</form>
</body>
</html>
and in the code behind you have this:
protected void Timer1_Tick(object sender, EventArgs e)
{
//do your thing when reach this tick
}
This page will refresh exactly every 3 seconds.
This is .net 4.

This asp.net password recovery code has an error. Can anyone spot it?

We use email address instead of user id. But when the user enters his email address into the password recovery form and submits it, the site returns "We were unable to access your information. Please try again." and replaces the email value in the text box with a long string of characters and numbers (e.g. e61686cb-93a5-4737-8c40-52g8eb01bb67).
Here's the relevant aspx page code...
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1"
runat="server">
<div class="login_page">
<div class="login_header">Password Reset</div>
<div class="login_body">
<asp:PasswordRecovery ID="PasswordRecovery1" runat="server"
onverifyinguser="PasswordRecovery1_VerifyingUser"
onsendingmail="PasswordRecovery1_SendingMail">
</asp:PasswordRecovery>
</div>
</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;
using System.Web.Security;
using System.Text.RegularExpressions;
using System.Net.Mail;
using System.Configuration;
using System.Web.Profile;
using System.Text;
namespace Sample.Web
{
public partial class PasswordReset : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
bool IsValidEmail(string strIn)
{
// Return true if strIn is in valid e-mail format.
return Regex.IsMatch(strIn, #"^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
}
protected void PasswordRecovery1_VerifyingUser(object sender, LoginCancelEventArgs e)
{
if (IsValidEmail(PasswordRecovery1.UserName))
{
string username = Membership.GetUserNameByEmail(PasswordRecovery1.UserName);
if (username != null)
{
PasswordRecovery1.UserName = username;
}
else
{
PasswordRecovery1.UserNameInstructionText = "We were unable to access your information. Check your user name and try again.";
e.Cancel = true;
}
}
else
{
PasswordRecovery1.UserNameInstructionText = "You must enter a valid e-mail address.";
e.Cancel = true;
}
}
protected void PasswordRecovery1_SendingMail(object sender, MailMessageEventArgs e)
{
string pwd = Membership.GetUser(PasswordRecovery1.UserName).ResetPassword(PasswordRecovery1.Answer);
string email = StorageByMail.BLL.SBMUser.SelectUser(
StorageByMail.Data.User.GetIDFromUserName(PasswordRecovery1.UserName)).Email;
MailMessage m = new MailMessage(ConfigurationManager.AppSettings["AdminEmail"].Trim(), email);
m.ReplyTo = new MailAddress(ConfigurationSettings.AppSettings["AdminEmailReply"].Trim());
StringBuilder sb = new StringBuilder();
sb.Append("Please return to the site and log in using the following information.\n");
sb.Append("User Name: " + email + "\n");
sb.Append("Password: " + pwd);
m.Body = sb.ToString();
m.Subject = "Password reset from StorageByMail.com";
SmtpClient o = new SmtpClient(ConfigurationManager.AppSettings["SMTPHost"].Trim());
string smtpUser = ConfigurationSettings.AppSettings["SMTPUser"].Trim();
string smtpPass = ConfigurationSettings.AppSettings["SMTPPassword"].Trim();
if (smtpUser.Length > 0 && smtpPass.Length > 0)
{
o.Credentials = new System.Net.NetworkCredential(smtpUser, smtpPass);
}
o.Send(m);
e.Cancel = true;
}
}
}
Without knowing a lot about ASP.NET membership, my guess would be that the line:
PasswordRecovery1.UserName = username;
// where username = Membership.GetUserNameByEmail(PasswordRecovery1.UserName);
is causing your problem. Even though you say you're not using username in your model, I'd bet that ASP.NET populates the username column in your database with a GUID. Take a look at your database, and see if that GUID matches up with the username column in your table for this user.

Categories