ASP.NET page freezing - c#

So, I'm making an ASP.NET page in C#. I have a very simple form with 2 textboxes and 3 buttons on it. When I click a button for 'submit' it makes a call to an SQL Server database to retrieve some info. Once the data's retrieved, I have an if statement to check one of the loaded values. The problem is that the page seems to freeze after the button is clicked, and I can't click it again. I can still enter data in the textboxes, but the button doesn't show up as a LinkButton, the mouse icon doesn't change or anything. The code for the ASPX.CS page is below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CharacterSheet.BLL;
using CharacterSheet.Data;
public partial class Login : System.Web.UI.Page
{
protected void ClearButton_Click(object sender, EventArgs e)
{
UserBox.Text = "";
PassBox.Text = "";
}
protected void SubmitButton_Click(object sender, EventArgs e)
{
PlayerController pc = new PlayerController();
Player player;
if (UserBox.Text.Contains('#') && UserBox.Text.Contains(".c"))
player = pc.GetByEmail(UserBox.Text);
else
player = pc.GetByUser(UserBox.Text);
if (player != null)
{
if (!player.Flagged)
{
if (PassBox.Text != player.Password)
{
ErrorLabel.Text = "Password does not match our records. Please retype carefully...";
player.LoginAttempts++;
if (player.LoginAttempts >= 3)
player.Flagged = true;
pc.Update(player);
}
else
Response.Redirect(SiteData.LoginMainPage);
}
else
ErrorLabel.Text = "Your account has been flagged. Please e-mail our support team.";
}
else
ErrorLabel.Text = "Unable to find user. Please retype carefully...";
}
}
And the code for the ASP markup page:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
<style type="text/css">
.leftColumn
{
text-align: right;
}
.style1
{
width: 30%;
text-align: right;
height: 47px;
}
.style2
{
width: 70%;
text-align: right;
height: 47px;
}
</style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
<table>
<tr>
<td class="leftColumn">
<asp:Label ID="Label1" runat="server" CssClass="FormText"
Text="Username or Email"></asp:Label>
</td>
<td>
<asp:TextBox ID="UserBox" runat="server" ToolTip="Enter your username here"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="UserBox" ErrorMessage="Username or Email is required"
ForeColor="Red">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="leftColumn">
<asp:Label ID="Label2" runat="server" CssClass="FormText" Text="Password"></asp:Label>
</td>
<td>
<asp:TextBox ID="PassBox" runat="server" TextMode="Password"
ToolTip="Enter your password here" TabIndex="1"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ErrorMessage="Password is required" ForeColor="Red"
ControlToValidate="PassBox">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style1"></td>
<td class="style2">
<asp:ValidationSummary ID="ValidationSummary" runat="server"
CssClass="ValidationSumary" ForeColor="Red" Height="43px"
style="text-align: left" Width="335px" DisplayMode="List" />
<asp:LinkButton ID="SubmitButton" runat="server" CssClass="FormButton"
TabIndex="2" onclick="SubmitButton_Click" PostBackUrl="~/Login.aspx">Submit</asp:LinkButton>
<asp:LinkButton ID="ClearButton" runat="server" CausesValidation="False"
CssClass="FormButton" TabIndex="3" onclick="ClearButton_Click">Clear</asp:LinkButton>
<asp:LinkButton ID="NewAcctButton" runat="server" CausesValidation="False"
CssClass="FormButton" TabIndex="4">Create Account</asp:LinkButton>
<br />
<asp:Label ID="ErrorLabel" runat="server" ForeColor="Red"
CssClass="FormErrorLabel"></asp:Label>
</td>
</tr>
</table>
</asp:Content>
Thanks to anyone who can help with this! :-)
EDIT: Upon further investigation (commenting out lines of code sequentially), I find that the problem arises when I update "ErrorLabel.Text". If I don't do that, then it functions just fine...this is confusing me a lot now...

If there is any unwanted code in aspx page or runtime error came then the page will freeze.To avoid this analyze your code once again and remove unwanted things it will run.

After randomly clicking buttons in the properties of the label, I find it stops breaking when I don't attach a CSS class to the label...I have no idea why, but it fixed the problem.

Related

How to delete specific listview items in ASP.NET C#?

Here is my messageview.aspx, which has list view to show user messages.
On delete button click, I want to capture the current table row value, and call the sql stored procedure accordingly. However, I am unable to access the fields like Sender Email-ID, Sender Role, and Message inside delete button click function. how can I do so?
<%# Page Title="" Language="C#" MasterPageFile="~/DefaultLayout.Master" AutoEventWireup="true" CodeBehind="MessageView.aspx.cs" Inherits="SchoolMgmtSystem.MessageView" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div class="jumbotron">
<h1>Inbox</h1>
</div>
<asp:ListView ID="lvgetMessages" runat="server" OnSelectedIndexChanged="lvgetMessages_SelectedIndexChanged">
<EmptyDataTemplate>
<table runat="server" style="background-color: #FFFFFF; border-collapse: collapse; border-color: #999999; border-style: none; border-width: 1px;">
<tr>
<td>No data was returned.</td>
</tr>
</table>
</EmptyDataTemplate>
<LayoutTemplate>
<table class="table table-border">
<tr>
<th> Sender Email ID</th>
<th> Sender Role </th>
<th> Message</th>
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr style="background-color: #DCDCDC; color: #000000;">
<td>
<asp:Label ID="emailIDLabel" runat="server" Text='<%# Eval("[SenderEmailID]") %>' />
</td>
<td>
<asp:Label ID="SenderRoleLabel" runat="server" Text='<%# Eval("RoleName") %>' />
</td>
<td>
<asp:Label ID="MessageLabel" runat="server" Text='<%# Eval("[Message]") %>' />
</td>
<td>
<asp:Button ID="ButtonDelete" runat="server" Text="Delete" onclick="ButtonDelete_Click" UseSubmitBehavior="False" />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
<div class="form-group" runat="server" style="display:block">
<asp:Button ID="ButtonBack" runat="server" Text="Back" CssClass="btn-primary center-block" OnClick="ButtonBack_Click" />
</div>
</asp:Content>
The code behind message view is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BAL;
using System.Data;
namespace SchoolMgmtSystem
{
public partial class MessageView : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lvgetMessages.DataSource = null;
lvgetMessages.DataBind();
String roleId = Request.QueryString["RoleId"];
String userId = Request.QueryString["UserId"];
String userEmailId = AdminBizz.GetEmailId(userId, roleId);
DataTable dtMessageInfo = RoleBizz.GetUserMessages(userEmailId);
if (dtMessageInfo.Rows.Count > 0)
{
lvgetMessages.DataSource = dtMessageInfo;
lvgetMessages.DataBind();
}
}
protected void lvgetMessages_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void ButtonDelete_Click(object sender, EventArgs e)
{
}
protected void ButtonBack_Click(object sender, EventArgs e)
{
String roleId = Request.QueryString["RoleId"];
String userId = Request.QueryString["UserId"];
Response.Redirect("MessageSend.aspx?UserId=" + userId + "&RoleId=" + roleId);
}
}
}
Here is the screen shot -
What you can probably do is get the NamingContainer of your delete button and find the other controls within it.
protected void ButtonDelete_Click(object sender, EventArgs e)
{
var control = (Control)sender;
var container = control.NamingContainer;
// access your controls this way
var emailIDLabel= container.FindControl("emailIDLabel") as Label;
var senderRoleLabel = container.FindControl("SenderRoleLabel") as Label;
var messageLabel = container.FindControl("MessageLabel") as Label;
}
You can do something like the answer for this question.
But remember to validate the value (with int.TryParse(string) for example).
<asp:Button ID="ButtonDelete" runat="server" Text="Delete"
OnClick="ButtonDelete_Click"
UseSubmitBehavior="False"
CommandName="Deleterecord"
CommandArgument='<%# Eval("[SenderEmailID]") %>'/>
protected void ButtonDelete_Click(object sender, EventArgs e)
{
int id;
var button = (Button)sender;
if(!int.TryParse(button.CommandArgument, out id))
{
// log.Write("possible sql injection");
return;
}
// do what you want
}

Find the selected value of a RadioButton inside a Lightbox that is inside a Repeater

I have a Repeater that contains a link labeled "Change Membership" that when clicked opens a lightbox with a radiobuttonlist and a button. When the button in the lightbox is clicked I have a callback event where I need to find the selected value of the radiobutton list first here is the repeater:
<script language="JavaScript" type="text/javascript">
function CreateBox(id) {
$(document).ready(function () {
$("#lnk" + id).fancybox({
'closeBtn': true,
helpers: {
overlay: { closeClick: false }
}
});
});
}
</script>
Head
Body
<asp:Repeater ID="repProspects" runat="server" OnItemDataBound="repProspects_ItemDataBound">
<ItemTemplate>
<asp:HiddenField ID="hfRequestID" runat="server" Value='<%# DataBinder.Eval(Container, "DataItem.RequestID") %>' />
<asp:HiddenField ID="hfRecruiterNumber" runat="server" Value='<%# DataBinder.Eval(Container, "DataItem.RecruiterCardNumber") %>' />
<asp:HiddenField ID="hfCompanyID" runat="server" Value='<%# DataBinder.Eval(Container, "DataItem.CompanyID") %>' />
<asp:HiddenField ID="hfMemberType" runat="server" Value='<%# DataBinder.Eval(Container, "DataItem.MemberType") %>' />
<asp:HiddenField ID="hfLifeDuesAmount" runat="server" Value='<%# DataBinder.Eval(Container, "DataItem.Dues") %>' />
<asp:HiddenField ID="hfDerivedAnnualDues" runat="server" />
<asp:HiddenField ID="hfDerivedInstallments" runat="server" />
<asp:HiddenField ID="hfRblSelectedValue" runat="server" />
<asp:HiddenField ID="hfSetMemberType" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="hfState" runat="server" Value='<%# DataBinder.Eval(Container, "DataItem.HomeState") %>' />
<asp:HiddenField ID="hfCountry" runat="server" Value='<%# DataBinder.Eval(Container, "DataItem.HomeCountry") %>' />
<asp:HiddenField ID="hfBirthday" runat="server" Value='<%# DataBinder.Eval(Container, "DataItem.Birthday") %>' />
<div id='h<%# DataBinder.Eval(Container, "DataItem.ID") %>' class="header" onclick='ToggleDisplay(<%# DataBinder.Eval(Container, "DataItem.ID") %>);'>
<img id="img<%# DataBinder.Eval(Container, "DataItem.ID") %>" alt="" src="../images/plusIconSmaller.png" />
<%# DataBinder.Eval(Container, "DataItem.FirstName")%>
<% if (DataBinder.GetDataItem("DataItem.MiddleName") != "")
{ %>
<%# DataBinder.Eval(Container, "DataItem.MiddleName")%>
<% } %>
<%# DataBinder.Eval(Container, "DataItem.LastName")%>
<% if (DataBinder.GetDataItem("DataItem.Suffix") != "")
{ %>
<%# DataBinder.Eval(Container, "DataItem.Suffix")%>
<% } %>
(<%# DataBinder.Eval(Container, "DataItem.CurrentStatus")%>, <%# DataBinder.Eval(Container, "DataItem.BranchOfService")%>)
<asp:Label ID="lblRecruitedBy" runat="server"></asp:Label>
<%# Convert.ToDateTime(DataBinder.Eval(Container, "DataItem.DateCreated")).ToShortDateString()%>
</div>
<div id='reqid<%# DataBinder.Eval(Container, "DataItem.RequestID") %>'></div>
<div id='d<%# DataBinder.Eval(Container, "DataItem.ID") %>' class="details">
<table width="100%">
<tr>
<td valign="top" width="25%"><u><b>Address</b></u><br />
<%# DataBinder.Eval(Container, "DataItem.HomeAddressLine1")%><br />
<%# DataBinder.Eval(Container, "DataItem.HomeCity")%>, <%# DataBinder.Eval(Container, "DataItem.HomeState")%> <%# DataBinder.Eval(Container, "DataItem.HomeZipCode")%><br />
<%# DataBinder.Eval(Container, "DataItem.HomeCountry")%></td>
<td valign="top" width="20%"><u><b>Qualifying Service</b></u><br />
<asp:Label ID="lblServiceInfo" runat="server"></asp:Label></td>
<td valign="top" width="20%"><u><b>Contact Info</b></u><br />
<% if (DataBinder.GetDataItem("DataItem.Phone") != "")
{ %>
<%# FormatPhone(DataBinder.Eval(Container, "DataItem.Phone").ToString()) %>
<% } %>
<asp:Label ID="lblMemberPhone" runat="server"></asp:Label>
<%# DataBinder.Eval(Container, "DataItem.Email")%><br />
Birthday: <%# Convert.ToDateTime(DataBinder.Eval(Container, "DataItem.Birthday")).ToShortDateString()%></td>
<td valign="top" width="20%"><u><b>Membership</b></u><br />
<%# DataBinder.Eval(Container, "DataItem.MemberType")%><br />
$<asp:Label ID="lblDuesAmount" runat="server"></asp:Label>
<br />
<a href='#ChgMemType<%# DataBinder.Eval(Container, "DataItem.ID") %>' onclick='CreateBox(<%# DataBinder.Eval(Container, "DataItem.ID") %>);' id='lnk<%# DataBinder.Eval(Container, "DataItem.ID") %>' >Change Membership</a>
</td>
<td valign="top" align="center">
<asp:Button ID="lnkApprove" Style="border: 1px solid black; border-radius: 7px; padding: 5px; cursor: pointer; background-color: #990000; width: 130px; color: white; font-weight: bold" Text="Approve & Pay" runat="server" CommandArgument='<%# DataBinder.Eval(Container, "DataItem.ID") %>' OnClientClick="return confirm('Are you sure you want to approve this member application?');" OnCommand="lnkApprove_Click"></asp:Button><br />
<br />
<asp:Button ID="lnkReject" Style="border: 1px solid black; border-radius: 7px; padding: 5px; cursor: pointer; background-color: #990000; width: 130px; color: white; font-weight: bold" Text="Reject" runat="server" CommandArgument='<%# DataBinder.Eval(Container, "DataItem.ID") %>' OnClientClick="return confirm('Are you sure you want to reject this member applictation?');" OnCommand="lnkReject_Click"></asp:Button></td>
</tr>
</table>
</div>
<div id='ChgMemType<%# DataBinder.Eval(Container, "DataItem.ID") %>' style="display: none; width:400px; text-align: left">
<h3>Change Membership Type </h3>
<p>Please select the membership type below:</p>
<input id='hfChangedMemberType' value="<%# DataBinder.Eval(Container, "DataItem.ID") %>" type="hidden" />
<div id="RadioDiv">
<asp:RadioButtonList ID="_rblMemberTypes" runat="server">
<asp:ListItem Text="Annual" Value="Annual">Annual</asp:ListItem>
<asp:ListItem Text="Life" Value="Life">Life</asp:ListItem>
<asp:ListItem Text="Installment" Value="Installment">Installment</asp:ListItem>
</asp:RadioButtonList>
</div>
<asp:LinkButton ID="lbSetMemType" EnableViewState="true" CommandArgument='<%# DataBinder.Eval(Container, "DataItem.RequestID") %>' OnCommand="lbSetMemType_Command" CssClass="button" runat="server">Save</asp:LinkButton>
</div>
</ItemTemplate>
</asp:Repeater>
Next is the code behind event when the Save button is clicked:
protected void lbSetMemType_Command(object sender, CommandEventArgs e)
{
decimal dDuesAmount = 0;
bool bSuccess = false;
int iRequestID = Convert.ToInt32(e.CommandArgument);
string sMemType = "";
HiddenField hfDerivedAnnualDues;
HiddenField hfDerivedInstallments;
HiddenField hfLifeDuesAmount;
HiddenField hfSetMemberType;
foreach (RepeaterItem item in repProspects.Items)
{
// Checking the item is a data item
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
var reqid = item.FindControl("hfRequestID") as HiddenField;
if (Convert.ToInt32(reqid.Value) == iRequestID) {
var rdbList = item.FindControl("_rblMemberTypes") as RadioButtonList;
if (rdbList != null)
{
foreach (ListItem li in rdbList.Items)
{
if (li.Selected == true)
{
sMemType = li.Text;
}
}
}
// Get the selected value
hfSetMemberType = item.FindControl("hfRblSelectedValue") as HiddenField;
sMemType = rdbList.SelectedValue;
// sMemType = hfSetMemberType.Value;
hfDerivedAnnualDues = item.FindControl("hfDerivedAnnualDues") as HiddenField;
hfDerivedInstallments = item.FindControl("hfDerivedInstallments") as HiddenField;
hfLifeDuesAmount = item.FindControl("hfLifeDuesAmount") as HiddenField;
}
}
}
switch (sMemType)
{
case "Annual":
{
//dDuesAmount = Convert.ToDecimal(hfDerivedAnnualDues.Value);
break;
}
case "Life":
{
//dDuesAmount = Convert.ToDecimal(hfLifeDuesAmount.Value);
break;
}
case "Installments":
{
// dDuesAmount = Convert.ToDecimal(hfDerivedInstallments.Value);
break;
}
default:
{
//dDuesAmount = Convert.ToDecimal(hfDerivedAnnualDues.Value);
break;
}
}
bSuccess = logicManager.UpdateNewMemberAppMemType(iRequestID, sMemType, dDuesAmount);
}
I can set breakpoints and I can see the values in the hiddenfields are correct however I can't get the right clicked value on this statement:
sMemType = rdbList.SelectedValue;
I get the initial value but not the user clicked value?
First, you're missing OnItemCommand="lbSetMemType_Command" in your actual code.
Also, iterating through your repeater by hand will give you poor performance result, especially if you're looking for just the value of a radiobutton.
Now, lets do a MCVE example together. According to your code, you're trying to build a RadioButtonList inside a Repeater, with a LinkButton who use the radio's button value. In our case, let's just print the value of said choosen button in a label, proving our case.
MCVE.aspx
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<asp:Repeater ID="rptTest" runat="server" OnItemCommand="rptTest_ItemCommand">
<ItemTemplate>
<asp:RadioButtonList ID="rdlTest" runat="server">
<asp:ListItem Text="Annual" Value="Annual"></asp:ListItem>
<asp:ListItem Text="Life" Value="Life"></asp:ListItem>
<asp:ListItem Text="Installment" Value="Installment"></asp:ListItem>
</asp:RadioButtonList>
<asp:LinkButton runat="server" ID="lbValidationTest" OnClick="lbValidationTest_Click" runat="server" >Fetch Value</asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
<asp:Label runat="server" ID="lblViewResult"></asp:Label>
</asp:Content>
I'm using the default masterpage when you create a new project on VS. It really doesnt matter here
And the codebehind
MCVE.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication
{
public partial class MCVE: Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<int> uselessData = new List<int>(new int[] { 1, 2 });
this.rptTest.DataSource = uselessData;
this.rptTest.DataBind();
}
}
protected void rptTest_ItemCommand(object source, RepeaterCommandEventArgs e)
{
RadioButtonList list = (RadioButtonList)e.Item.FindControl("rdlTest");
this.lblViewResult.Text = list.SelectedValue;
}
}
}
After some tries, we clearly see that this is not working as intended. There is in fact some known issues between the Repeater & the RadioButtonListforbidding us to do just that.
So, what to do now ? We have plenty of solutions, we can for example use javascript to get and set our values in a hidden field ; we could iterate through or entire repeater tree and check every button or even use the CommandArgument to locate the RadioButtonList's index and fetch it in codebehind.
Let's implement the javascript solution. We are going to inject the value of our index in a hidden field present in the repeater. I think its better to treat this behaviour client side rather than server-side, but I could be mistaken and would love some output on this.
So let's add a very dirty javascript code to our view
MCVE.aspx New Version
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<asp:Repeater ID="rptTest" runat="server" OnItemCommand="rptTest_ItemCommand">
<ItemTemplate>
<div>
<asp:HiddenField runat="server" ID="hfSelectedValue" />
<asp:RadioButtonList ID="rdlTest" runat="server" >
<asp:ListItem Text="Annual" Value="Annual" onclick="QuickAndDirtyHiddenSetDontUseItInProd(this)"></asp:ListItem>
<asp:ListItem Text="Life" Value="Life" onclick="QuickAndDirtyHiddenSetDontUseItInProd(this)"></asp:ListItem>
<asp:ListItem Text="Installment" Value="Installment" onclick="QuickAndDirtyHiddenSetDontUseItInProd(this)"></asp:ListItem>
</asp:RadioButtonList>
<asp:LinkButton runat="server" ID="lbValidationTest" runat="server" UserSubmitBehavior="true" >Fetch Value</asp:LinkButton>
</div>
</ItemTemplate>
</asp:Repeater>
<asp:Label runat="server" ID="lblViewResult"></asp:Label>
<script>
function QuickAndDirtyHiddenSetDontUseItInProd(data) {
$(data).parent().parent().parent().parent().siblings("input[name*=hfSelectedValue]").val(data.value);
}
</script>
</asp:Content>
We just changed 3 things. We're going to track a hidden field for each radiobuttonlist we're going to create, we added a script to change the value of said hidden field and linked the two with the onclic.
Now, on our codebehind, we just have to track the hidden field grouped with the click on the ButtonLink (ie, in the same RepeaterItem) and we're good to go.
MCVE.aspx.cs New Version
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication
{
public partial class MCVE: Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<int> uselessData = new List<int>(new int[] { 1, 2 });
this.rptTest.DataSource = uselessData;
this.rptTest.DataBind();
}
}
protected void rptTest_ItemCommand(object source, RepeaterCommandEventArgs e)
{
HiddenField hiddenField = (HiddenField)e.Item.FindControl("hfSelectedValue");
this.lblViewResult.Text = hiddenField.Value;
}
}
}
Pretty Self-explanatory, we just find the hidden field in our repeater, and we use it to fill the label.

Need Help in ASP.Net C# login page

What is wrong with this code? I have tried a lot of methods. But it always show login failed. No Build Errors though. I have a database named honeypot and a table called register in it,with username row and password row as varchars. I'm using built in login control. Can anyone help? I'm using Visual studio 2013.
home.aspx.cs
enter code here
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
namespace CodeInjection4
{
public partial class Home : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
}
private static int count = 0;
protected void log1_Authenticate(object sender, AuthenticateEventArgs e)
{
if (log1.UserName == "Admin" && log1.Password == "Admin")
{
Response.Redirect("Adminhome.aspx");
}
else if (YourValidationFunction(log1.UserName, log1.Password))
{
Session["User"] = log1.UserName;
e.Authenticated = true;
Response.Redirect("userhome.aspx");
log1.TitleText = "Successfully Logged In";
}
else
{
e.Authenticated = false;
count++;
if (count >= 3)
{
count = 0;
Session["User"] = log1.UserName;
Server.Transfer("MainPage.aspx");
}
}
}
private SqlConnection strConnection = new
SqlConnection("server=.\\SQLEXPRESS;database=honeypot;integrated security=true;");
private bool YourValidationFunction(string UserName, string Password)
{
bool boolReturnValue = false;
String SQLQuery = "SELECT UserName, Password FROM Register";
SqlCommand command = new SqlCommand(SQLQuery, strConnection);
SqlDataReader Dr;
try
{
strConnection.Open();
Dr = command.ExecuteReader();
while (Dr.Read())
{
if ((UserName == Dr["UserName"].ToString()) & (Password == Dr["Password"].ToString()))
{
boolReturnValue = true;
}
}
Dr.Close();
}
catch
{
}
return boolReturnValue;
}
protected void lnkRegis_Click(object sender, EventArgs e)
{
Response.Redirect("AdUserAcc.aspx");
}
}
}
Home.aspx
enter code here
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Home.aspx.cs" Inherits="CodeInjection4.Home" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script runat="server">
</script>
<style type="text/css">
#form1 {
text-align: center;
}
.auto-style1 {
width: 981px;
text-align: left;
}
.auto-style2 {
width: 961px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
Forestalling Code Injection</div>
<asp:Login ID="log1" OnAuthenticate="log1_Authenticate" runat="server" Width="1062px">
<LayoutTemplate>
<table cellpadding="1" cellspacing="0" style="border-collapse:collapse;">
<tr>
<td>
<table cellpadding="0">
<tr>
<td align="center" colspan="2">Log In</td>
</tr>
<tr>
<td align="right" class="auto-style2">
<asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">User Name:</asp:Label>
</td>
<td class="auto-style1">
<asp:TextBox ID="UserName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName" ErrorMessage="User Name is required." ToolTip="User Name is required." ValidationGroup="log1">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right" class="auto-style2">
<asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label>
</td>
<td class="auto-style1">
<asp:TextBox ID="Password" runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="PasswordRequired" runat="server" ControlToValidate="Password" ErrorMessage="Password is required." ToolTip="Password is required." ValidationGroup="log1">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td colspan="2">
<asp:CheckBox ID="RememberMe" runat="server" Text="Remember me next time." />
</td>
</tr>
<tr>
<td align="center" colspan="2" style="color:Red;">
<asp:Literal ID="FailureText" runat="server" EnableViewState="False"></asp:Literal>
</td>
</tr>
<tr>
<td align="right" colspan="2" style="text-align: center">
<asp:Button ID="LoginButton" runat="server" CommandName="Login" Text="Log In" ValidationGroup="log1" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</LayoutTemplate>
</asp:Login>
<br />
<asp:Button ID="Button1" runat="server" Text="Register" PostBackUrl="~/AdUserAcc.aspx" />
</form>
</body>
</html>
You are selecting all the users and looping through them. You have break out of the loop if you find a matching username and password such as
if ((UserName == Dr["UserName"].ToString()) & (Password == Dr["Password"].ToString()))
{
boolReturnValue = true;
break;
}
Othwerwise the next user will set it back to false.
A couple of notes:
Selecting all users and iterating through them is not scalable and wouldn't perform well. Instead you can pass in the username and password in WHERE clause. If you get a match then the login info is correct.
I'd recommend using logical-AND operator (&&) instead of bitwise-AND (&). Here's a SO thread with related discussion: Usage & versus &&
Consider using salted password hashes as opposed to plaintext passwords.

Design View ListView ASP.NET Logic

I am trying to input logic in the source view in Asp.Net ListView. The problem is that the program is writing on the screen false or true when executing "If (isItTrue(test))". Does anyone know how to solve this problem?
<%# test= Eval("testId")%>
<%
If (isItTrue(test)) Then
%>
<asp:Button ID="btnTest" runat="server" Text="Like" />
<%
Else
%>
<asp:Label runat="server" Text="hello" </asp:Label>
<%
End If
%>
You could use ItemDataBound to check informations like this and show or hide the controls using your condition. try something like this in your code behine:
protected void ListViewTest_ItemDataBound(object sender, ListViewItemEventArgs e)
{
// if it is data item
if (e.Item.ItemType == ListViewItemType.DataItem)
{
// call your function
if (isItTrue("test"))
{
// show the button
e.Item.FindControl("btnTest").Visible = true;
}
else
{
// show the label
e.Item.FindControl("lblTest").Visible = true;
}
}
}
And in your Listview, you could do something like this, setting the event and adding the controls on the place holder
<asp:ListView ID="ListViewTest" DataSourceID="..." OnItemDataBound="ListViewTest_ItemDataBound" runat="server">
<LayoutTemplate>
<table>
<tr>
<th>Column Name</th>
</tr>
<tr runat="server" id="itemPlaceholder" />
</table>
</LayoutTemplate>
<ItemTemplate>
<tr style="background-color: #CAEEFF" runat="server">
<td>
<%-- both controls are here --%>
<asp:Button ID="btnTest" runat="server" Visible="false" Text="Like"></asp:Button>
<asp:Label ID="lblTest" runat="server" Visible="false" Text="hello"></asp:Label>
</td>
</tr>
</ItemTemplate>
</asp:ListView>
Are you sure it's not this line: <%# test= Eval("testId")%> that is writing true or false to the output?

Problem in using RequiredFieldValidator control in asp.net c#

I am using RequiredFieldValidator in my asp.net program. I have a sign out button which is used to terminate the session, but when i click on this sign out button without inserting any values in any of the text box the RequiredFieldValidator throws an error and i am not able to sign out.
I want to sign out a user without inputting any of the values in the textbox.
Please check my code in case of any problem in my code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class EntryForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{// CHEK SESSION VARIABLE AND LOAD dropdownlist1 WITH VALUES
if (!IsPostBack)
{
String DB = "";
String AccountID = "";
if (Session["login"] != null && Session["db"] != null)
{
AccountID = Session["login"].ToString();
DB = Session["db"].ToString();
Label9.Text = AccountID;
}
else
{
Response.Redirect("log.aspx");
}
HiddenField1.Value = DB.ToString();
DropDown a = new DropDown();
a.filldropdown1(this.DropDownList1, DB);
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
// LOG OUT***********////////////
Session.Abandon();
Response.Redirect("log.aspx");
}
.aspx code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="EntryForm.aspx.cs" Inherits="EntryForm" %>
<%# Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit.HTMLEditor" tagprefix="cc1" %>
<!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 runat="server">
<title></title>
<style type="text/css">
.style1
{
width: 330px;
}
.style2
{
text-align: center;
}
.style3
{
text-align: center;
width: 38px;
}
.style4
{
text-align: center;
width: 109%;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table style="width:90%; height: 30px;">
<tr>
<td class="style1">
<asp:Label ID="Label8" runat="server" style="text-align: left"
Text="Welcome"></asp:Label>
<asp:Label ID="Label9" runat="server" style="text-align: left"></asp:Label>
</td>
<td align="center" width="100%" style="text-align: right">
<asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click"
style="text-align: right">Log Out</asp:LinkButton>
</td>
</tr>
</table>
</div>
<table style="width:95%;" align="center" bgcolor="Silver">
<tr>
<td>
<asp:Label ID="Label1" runat="server" Text="Type : "></asp:Label>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server"
ControlToValidate="DropDownList1" ErrorMessage="*"
InitialValue="<-- Select -->">*</asp:RequiredFieldValidator>
</td>
<td>
<asp:Label ID="Label2" runat="server" Text="No. :"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" Width="75px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="TextBox1" ErrorMessage="*">*</asp:RequiredFieldValidator>
</td>
<td>
<asp:Label ID="Label3" runat="server" Text="Year :"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server" Width="75px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server"
ControlToValidate="TextBox2" ErrorMessage="Enter Year">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="TextBox2" ErrorMessage="Enter year"
ValidationExpression="^\d{4}$">YYYY</asp:RegularExpressionValidator>
</td>
<td>
<asp:Label ID="Label4" runat="server" Text="Order Date : "></asp:Label>
<asp:TextBox ID="TextBox3" runat="server" Width="75px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server"
ControlToValidate="TextBox3" ErrorMessage="Enter proper format">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server"
ControlToValidate="TextBox3" ErrorMessage="Enter valid date"
ValidationExpression="^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$">dd/mm/yyyy</asp:RegularExpressionValidator>
</td>
<td>
<asp:Button ID="Button2" runat="server" Text="GO" onclick="Button2_Click" />
</td>
</tr>
</table>
<br />
<table style="width:100%;">
<tr>
<td style="text-align: center">
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True"
style="text-align: center" Visible="False"
onselectedindexchanged="DropDownList2_SelectedIndexChanged">
</asp:DropDownList>
</td>
</tr>
</table>
<br />
<table style="width:100%;">
<tr>
<td style="text-align: center" width="100%">
<asp:Label ID="Label5" runat="server" Text="Label" Visible="False"
style="text-align: center"></asp:Label>
</td>
<td style="text-align: center" width="100%">
<asp:Label ID="Label6" runat="server" Text="Vs" Visible="False"></asp:Label>
</td>
<td style="text-align: center" width="100%">
<asp:Label ID="Label7" runat="server" Text="Label" Visible="False"></asp:Label>
</td>
</tr>
</table>
<br />
<table style="width:100%;" border="1">
<tr>
<td class="style3" width="100%">
</td>
<td class="style4" width="100%">
<cc1:Editor ID="Editor1" runat="server" Width="60%" AutoFocus="true"
style="text-align: right" />
</td>
<td class="style2" width="100%">
</td>
</tr>
</table>
<br />
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:HiddenField ID="HiddenField1" runat="server"/>
</form>
</body>
</html>
There are 2 ways you can do this
put validation group property to your controls
ValidationGroup="input"
OR
On your sign out link button, put
CausesValidation="false"
Use validation group property to group the items to be validated.
http://www.w3schools.com/ASPNET/prop_webcontrol_imagebutton_validationgroup.asp
On your Sign Out button set CausesValidation property to false
<asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click"
CausesValidation="False"
style="text-align: right">Log Out</asp:LinkButton>
There is a property of button CausesValidation; set it to false. Than the validations on page won't fire.

Categories