CreateNewUser and Send Verification Email - asp.net

I have a registration page with the following code: -
<%# Page Language="C#" %>
<%# Import Namespace="System.Web.Security" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
public void CreateUser_OnClick(object sender, EventArgs args)
{
// Create new user and retrieve create status result.
MembershipCreateStatus status;
string passwordQuestion = "";
string passwordAnswer = "";
if (Membership.RequiresQuestionAndAnswer)
{
passwordQuestion = PasswordQuestionTextbox.Text;
passwordAnswer = PasswordAnswerTextbox.Text;
}
try
{
MembershipUser newUser = Membership.CreateUser(UsernameTextbox.Text, PasswordTextbox.Text,
EmailTextbox.Text, passwordQuestion,
passwordAnswer, true, out status);
if (newUser == null)
{
Msg.Text = GetErrorMessage(status);
}
else
{
Response.Redirect("~/ok_reg.aspx");
}
}
catch
{
Msg.Text = "An exception occurred creating the user.";
}
}
public string GetErrorMessage(MembershipCreateStatus status)
{
switch (status)
{
case MembershipCreateStatus.DuplicateUserName:
return "Username already exists. Please enter a different user name.";
case MembershipCreateStatus.DuplicateEmail:
return "A username for that e-mail address already exists. Please enter a different e-mail address.";
case MembershipCreateStatus.InvalidPassword:
return "The password provided is invalid. Please enter a valid password value.";
case MembershipCreateStatus.InvalidEmail:
return "The e-mail address provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidAnswer:
return "The password retrieval answer provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidQuestion:
return "The password retrieval question provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidUserName:
return "The user name provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.ProviderError:
return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
case MembershipCreateStatus.UserRejected:
return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
default:
return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Create User</title>
</head>
<body>
<form id="form1" runat="server">
<h3>Create New User</h3>
<br />
<table cellpadding="3" border="0">
<tr>
<td>Account ID:</td>
<td><asp:Textbox id="UsernameTextbox" runat="server" /></td>
<td><asp:RequiredFieldValidator id="UsernameRequiredValidator" runat="server"
ControlToValidate="UserNameTextbox" ForeColor="red"
Display="Static" ErrorMessage="Required" /></td>
</tr>
<tr>
<td>Password:</td>
<td><asp:Textbox id="PasswordTextbox" runat="server" TextMode="Password" /></td>
<td><asp:RequiredFieldValidator id="PasswordRequiredValidator" runat="server"
ControlToValidate="PasswordTextbox" ForeColor="red"
Display="Static" ErrorMessage="Required" /></td>
</tr>
<tr>
<td>Confirm Password:</td>
<td><asp:Textbox id="PasswordConfirmTextbox" runat="server" TextMode="Password" /></td>
<td><asp:RequiredFieldValidator id="PasswordConfirmRequiredValidator" runat="server"
ControlToValidate="PasswordConfirmTextbox" ForeColor="red"
Display="Static" ErrorMessage="Required" />
<asp:CompareValidator id="PasswordConfirmCompareValidator" runat="server"
ControlToValidate="PasswordConfirmTextbox" ForeColor="red"
Display="Static" ControlToCompare="PasswordTextBox"
ErrorMessage="Confirm password must match password." />
</td>
</tr>
<tr>
<td>Email Address:</td>
<td><asp:Textbox id="EmailTextbox" runat="server" /></td>
<td><asp:RequiredFieldValidator id="EmailRequiredValidator" runat="server"
ControlToValidate="EmailTextbox" ForeColor="red"
Display="Static" ErrorMessage="Required" /></td>
</tr>
<% if (Membership.RequiresQuestionAndAnswer) { %>
<tr>
<td>Password Question:</td>
<td><asp:Textbox id="PasswordQuestionTextbox" runat="server" /></td>
<td><asp:RequiredFieldValidator id="PasswordQuestionRequiredValidator" runat="server"
ControlToValidate="PasswordQuestionTextbox" ForeColor="red"
Display="Static" ErrorMessage="Required" /></td>
</tr>
<tr>
<td>Password Answer:</td>
<td><asp:Textbox id="PasswordAnswerTextbox" runat="server" /></td>
<td><asp:RequiredFieldValidator id="PasswordAnswerRequiredValidator" runat="server"
ControlToValidate="PasswordAnswerTextbox" ForeColor="red"
Display="Static" ErrorMessage="Required" /></td>
</tr>
<% } %>
<tr>
<td colspan="3">
<asp:Label id="Msg" ForeColor="maroon" runat="server" /></td>
</tr>
<tr>
<td><asp:Button id="CreateUserButton" Text="Create User" OnClick="CreateUser_OnClick" runat="server" /></td>
<td><asp:Button id="PasswordRecover" Text="Password Recover" runat="server" PostBackUrl="~/recover.aspx" /></td>
</tr>
</table>
</form>
</body>
</html>
Here what i have to do is create a new user and send a verification mail to the email id provided by the user. User is being created without any problem, But I am finding bit hard to insert code for sending email id.
A little help is much appreciated. I need some guidance to send verification email to new users.

The System.Net.Mail namespace contains the various classes that are related to email. You can use some of the classes to send email. More information on this here
Also, it is recommended that the server-side processing code be put in the aspx.cs file (code behind) than embedding directly into the ASPX page.

Related

Changing the cssclass for a <tr> using vb.net

I have this and I want to hide rows dynamically using vb.net codebehind.
I am using VS2010.
This is my table:
<table>
<tr id="FromDateRow">
<td><asp:Label ID="FromDateLabel" runat="server">From date:</asp:Label></td>
<td>
<input type="text" id="txtFromDateF" class="needs-datepicker" />
<asp:TextBox id="txtFromDate" CssClass="hidden" runat="server" />
</td>
</tr>
<tr id="ToDateRow">
<td><asp:Label ID="ToDateLabel" runat="server">To date:</asp:Label></td>
<td>
<input type="text" id="txtToDateF" class="needs-datepicker" />
<asp:TextBox id="txtToDate" CssClass="hidden" runat="server" />
</td>
</tr>
<tr>
<td><asp:Label ID="CustomerCodeLabel" runat="server">Customer Code</asp:Label>:</td>
<td><asp:DropDownList ID="CustomerCodeDropDownList" runat="server" AutoPostBack="False" /></td>
</tr>
<tr>
<td><asp:Label ID="CINumberLabel" runat="server">CI Number</asp:Label>:</td>
<td><asp:TextBox ID="CINumberTextBox" runat="server" /></td>
</tr>
</table>
Now I want to do something like this:
Select Case value
Case DisplayDates.FromDate
ToDateRow.CssClass = "hidden"
FromDateRow.CssClass = ""
Case DisplayDates.ToAndFromDate
ToDateRow.CssClass = ""
FromDateRow.CssClass = ""
Case Else
ToDateRow.CssClass = "hidden"
FromDateRow.CssClass = "hidden"
End Select
For some reason I cannot access the ToDateRow and the FromDateRow from my codebehind.
The objects you are trying to reference in codebehind (the relevant tr elements) needs to be defined as runat="server"
If CssClass is not a known property for the object instance try using the following:
rowObject.Attributes.Add("class", "hidden");
You must have
runat="server
tag in table and tr to access from code behind.
After comment :
ToDateRow.Attributes("class") = "CssClass";
Ok I solved it.
By adding the runat="server" i was able to access the row.
And then I found the "visible"-property.
Now it works just fine.
Thx for the help

ASP.NET Enter key

I have a master page and based on that master page I created a page with a TextBox and two Validation controls for RequiredValidator and RegularExpressionValidator and one ValidationSummary.
when pressing the enter key in TextBox, I expected that both validator show their errorMessage on validationSummary but thats not what happening it only works when I press the button on page.
According to this page I wrapped my code with <asp:panel> and a DefaultButton attribute but it didn't solve the problem.
http://www.codeproject.com/KB/aspnet/aspnet_Enter_key_problem.aspx
I want to know what the problem here is and whether there is any workaround?
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
**<asp:Panel runat="server" DefaultButton="EmailSend">**
<table style="width: 100%">
<tr>
<asp:ValidationSummary ID="EmailValidation" runat="server" CssClass="failureNotification"
ValidationGroup="EmailValidation" />
</tr>
<tr>
<td style="width: 76px">
Email:
</td>
<td class="style1">
<asp:TextBox ID="EmailForget" runat="server" Width="244px"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="EmailRequiered" runat="server" ControlToValidate="EmailForget"
CssClass="failureNotification" ErrorMessage="RequiredFieldValidator" ValidationGroup="EmailValidation">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="EmailRegular" runat="server" ControlToValidate="EmailForget"
CssClass="failureNotification" ErrorMessage="email required"
ValidationGroup="EmailValidation">*</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td style="width: 76px">
</td>
<td class="style1">
<asp:Button ID="EmailSend" runat="server" Text="send" Width="56px" ClientIDMode="Static" />
</td>
<td>
</td>
</tr>
</table>
**<asp:Panel>**
</asp:Content>
Try adding this code
<script type="text/javascript">
if (document.addEventListener) {//if Firefox
document.addEventListener("keypress", fireFoxHandler, true);
} else {
document.attachEvent("onkeyup", ieHandler);
}
function fireFoxHandler(evt) {
if (evt.keyCode == 13) {
document.getElementById("EmailSend").click();
}
}
function ieHandler(evt) {
if (evt.keyCode == 13) {
document.getElementById("EmailSend").click();
}
}
</script>
Found this solution here.
(I didn't check this in MasterPage scenario, please check...)
If you are using IE then according to the answers on these two pages:
ASP.NET enter key and form submit with no javascript
Enter button does not submit form (IE ONLY) ASP.NET
you only need to add the following to your form
<!-- Fix for IE bug submit on pressing "Enter") -->
<div style="display:none">
<input type="text" name="hiddenText"/>
</div>
I solved this problem like this:
protected void Page_Load(object sender, EventArgs e)
{
textboxusername.Attributes.Add("onKeyPress", "javascript:if (event.keyCode == 13) __doPostBack('" + LinkButton1.UniqueID + "','')");
textboxpassword.Attributes.Add("onKeyPress", "javascript:if (event.keyCode == 13) __doPostBack('" + LinkButton1.UniqueID + "','')");
}
and this is the link..
<asp:LinkButton ID="LinkButton1" runat="server" class="btn" OnClick="LinkButton1_Click">

asp.net can only login in firefox

in my asp.net website i can only login in Firefox but not in chrome, internet explorer or safari.
here is my code :
string userName = LoginUserName.Text;
string password = LoginPassword.Text;
if (Page.IsValid)
{
if (Membership.ValidateUser(userName, password))
{
if (RemeberMe.Checked == true)
{
Response.Redirect("~/Home.aspx");
}
}
}
here is the login table :
<table>
<tr>
<td>
<asp:Label Text="Email:" AssociatedControlID="LoginUserName" runat="server"
id="LoginUserNamelabel" CssClass="label"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="LoginUserName" runat="server" Width="250px" CssClass="textbox"/>
<asp:RequiredFieldValidator id="LoginEmailRequired" runat="server" ControlToValidate="LoginUserName"
ErrorMessage="Email is required" ToolTip="Email is required"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:Label Text="Password:" AssociatedControlID="LoginPassword" runat="server"
ID="LoginPasswordlabel" CssClass="label"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="LoginPassword" runat="server" TextMode="Password" Width="250px" CssClass="textbox" />
<asp:RequiredFieldValidator ID="PassRequired" runat="server" ControlToValidate="LoginPassword"
ErrorMessage="Password is Required" ToolTip="Password is Required"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:CheckBox ID="RemeberMe" runat="server" Text="Remember me" CssClass="RemeberMe" />
</td>
</tr>
<tr>
<td><br />
<asp:Button ID="LoginButton" runat="server" Text="Login" OnClick="autoLogin" CssClass="Button" />
</td>
</tr>
<tr>
<td><br />
<asp:Label ID="FailureText" runat="server" EnableViewState="false" Visible="false" CssClass="Lfaluire">
Wrong Email or Password</asp:Label>
</td>
</tr>
</table>
using the AspNetSqlMembershipProvider.
i am using asp.net 4.0 , what is the problem
thanks
You always validate the username and password, but then only actually redirect if the user has checked the "Remember me" - This looks wrong. Could there be a co-incidence that you ticked the box in some test sessions but not others? ;)
Also you're not actually storing the fact that the user has logged in anywhere, so won't you have problems later with the User.Identity.IsAuthenticated still being false?
You should be using something like
FormsAuthentication.RedirectFromLoginPage Method whether or not the checkbox is checked...
If you want to do the redirect yourself you should be using FormsAuthentication.SetAuthCookie and then doing the redirect.
EDIT: Something like this
string userName = LoginUserName.Text;
string password = LoginPassword.Text;
if (Page.IsValid)
{
if (Membership.ValidateUser(userName, password))
{
if (RemeberMe.Checked)
{
// Set your own cookie here or something that you will later check for in Page_Load etc
}
// Need to tell ASP.NET authentication was successful
System.Web.Security.FormsAuthentication.SetAuthCookie(userName, True)
Response.Redirect("~/Home.aspx");
}
}
If you are hitting http://localhost then most of the browsers won't save the cookie that's being generated by your membership provider.
If this is the case, access it by a name that has a dot in it. See:
Cookies on localhost with explicit domain
Are cookies enabled in all these browsers? The most common culprit to the out-of-the-box ASP.NET login stuff "not working" is because by default, they have no fallback for when cookies are disabled.

displaying custom message on custom errors in validation summary control on client side?

I am using validation summary control to display error messages of asp.net validation controls.
There are some validations in page for which validation controls are not being used. I am using custom javascript and jquery code for these. Kindly guide how I can display messages of these errors in validation summary control along with asp.net validation controls.
The key is to use the Custom Validation control. This control supports client side scripting (so you can still use your javascript code to do it) but still ties into the validation framework asp.net provides.
From the microsoft article, something like this:
<SCRIPT LANGUAGE="JavaScript">
function validateLength(oSrc, args){
args.IsValid = (args.Value.length >= 8);
}
</SCRIPT>
<asp:Textbox id="text1" runat="server" text="">
</asp:Textbox>
<asp:CustomValidator id="CustomValidator1" runat=server
ControlToValidate = "text1"
ErrorMessage = "You must enter at least 8 characters!"
ClientValidationFunction="validateLength" >
</asp:CustomValidator>
As Patrick said you can add the custom validator controls in place of your custom javascript/jQuery code. And then accordingly you can add the summary validation control. Also you can change the error message in your javascript code. Please check the below code for your reference.
<script type="text/javascript">
function validatetxtLength(source, args)
{
var txtVal=document.getElementById('<%=txtusername.ClientID %>').value;
if(txtVal=="")
{
document.getElementById('<%=custxtValidator.ClientID %>').setAttribute("errormessage","Please Enter the User Name");
args.IsValid=false;
}
else if(txtVal.length>9)
{
document.getElementById('<%=custxtValidator.ClientID %>').setAttribute("errormessage","Username must have less than 10 characters");
args.IsValid=false;
}
else
{
args.IsValid=true;
}
return;
}
</script>
<div>
<table cellpadding="0" cellspacing="0" border="0" width="712px">
<tr>
<td colspan="3" align="center">
Validator Testing
</td>
</tr>
<tr>
<td>
Please Enter your User Name:
</td>
<td>
<asp:TextBox ID="txtusername" runat="server" Width="150px"></asp:TextBox>
</td>
<td>
<asp:CustomValidator ID="custxtValidator" runat="server" ErrorMessage="User Name must have less than 10 characters"
Text="*" ForeColor="Red" ClientValidationFunction="validatetxtLength"></asp:CustomValidator>
</td>
</tr>
<tr>
<td colspan="3" align="center">
<asp:Button ID="btnsubmit" runat="server" Text="Submit" />
</td>
</tr>
</table>
<asp:ValidationSummary ID="ValidationSummary1" HeaderText="Please check below validations:"
runat="server" DisplayMode="BulletList" EnableClientScript="true" />
</div>
This might be useful for you.

Themes wont work when using Server Side Tags on an ASP.NET Page

The code for the asp.net page is:
<div class="facebox_content">
<% if (CurrentUser.Role == "Free")
{
%>
<table cellpadding="0" cellspacing="0" style="border-collapse:collapse;width:380px;">
<tr>
<td>
User Name :
</td>
<td>
Membership Cost :
</td>
</tr>
<tr>
<td style="width:190px;">
<asp:TextBox ID="txtUserName" Enabled="false" runat="server" Text="<%= CurrentUser.Name %>"/>
</td>
<td style="width:190px;">
<asp:TextBox ID="txtCost" Enabled="false" runat="server" Text="2000"/>
</td>
</tr>
<tr>
<td>
<br />
Cheque / Draft No.:
</td>
<td>
<br />
Bank Drawn On :
</td>
</tr>
<tr>
<td style="width:190px;">
<asp:TextBox ID="txtChqNo" runat="server"></asp:TextBox>
</td>
<td style="width:190px;">
<asp:TextBox ID="txtBankName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<br />
Date :
</td>
<td>
<br />
City :
</td>
</tr>
<tr>
<td style="width:190px;">
<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
</td>
<td style="width:190px;">
<asp:TextBox ID="txtCity" runat="server"></asp:TextBox>
</td>
</tr>
</table>
<%
}
else if(CurrentUser.Role == "Pending")
{
%>
<p style="text-align:justify;">
Your Request is pending with our Administrators.
Please be patient while your request is processed.
Usually it takes 2-4 Days for your request to be processed after the payment has been received.
</p>
<%
}
else if(CurrentUser.Role == "Paid")
{
%>
<p style="text-align:justify;">
You are already a Paid Member of Website
</p>
<%
}
%>
The code for the C# file is:
protected void Page_PreInit(object sender, EventArgs e)
{
this.Theme = CurrentUser.Theme;
}
protected void Page_Load(object sender, EventArgs e)
{
txtUserName.Text = CurrentUser.Name;
ConfirmButton.Attributes.Add("onclick", "javascript:document.getElementById('" + lblMsg.ClientID + "').style.display='none';");
if (CurrentUser.Role != "Free")
ConfirmButton.Visible = false;
}
The code is giving the following error:
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[HttpException (0x80004005): The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).]
System.Web.UI.ControlCollection.Add(Control child) +8678903
System.Web.UI.PageTheme.SetStyleSheet() +478
System.Web.UI.Page.OnInit(EventArgs e) +8699660
System.Web.UI.Control.InitRecursive(Control namingContainer) +333
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +378
Please some one help me out..!!
Maybe you can try in another way:
Aspx:
<asp:PlaceHolder runat="server" ID="FreeHolder" Visible="false">
<table> ... </table>
</asp:PlaceHolder>
<asp:PlaceHolder runat="server" ID="PendingHolder" Visible="false">
<p style="text-align:justify;">
Your Request is pending with our Administrators. ...
</p>
</asp:PlaceHolder/>
<asp:PlaceHolder runat="server" ID="PaidHolder" Visible="false">
...
</asp:PlaceHolder/>
Code-Behind:
if (CurrentUser.Role == "Free")
{
FreeHolder.Visible = true;
} else if (CurrentUser.Role == "Pending") {
PendingHolder.Visible = true;
} else if (CurrentUser.Role == "Paid") {
PaidHolder.Visible = true;
}

Resources