refresh page after 3 seconds using c# - 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.

Related

Save pdf to jpeg using c# and pdfiumviewer library

I need to convert a pdf file into jpeg using c#.
The solution (dll library) have to be free.
I have searched a lot of information on the web but seems that the library pdfiumviewer might be helpful here. It is also available as nuget.
I have tried this code without success, because the new file in jpg format is not saved.
How to do resolve this?
using PdfiumViewer;
using System;
using System.Drawing.Imaging;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
try
{
using (var document = PdfDocument.Load(#"sample.pdf"))
{
var image = document.Render(0, 300, 300, true);
image.Save(#"output.png", ImageFormat.Png);
}
}
catch (Exception ex)
{
// handle exception here;
}
}
}
}
Edit #01
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
try
{
using (var document = PdfDocument.Load(#"C:\\Users\\aaa\\Documents\\Visual Studio 2013\\WebSites\\GroupDocsConversion\\sample.pdf"))
{
var image = document.Render(0, 300, 300, true);
image.Save(#"C:\\Users\\aaa\\Documents\\Visual Studio 2013\\WebSites\\GroupDocsConversion\\output.png", ImageFormat.Png);
}
}
catch (Exception ex)
{
Response.Write("Error: " + ex.Message);
}
}
}
Try this combined solution with iTextSharp and Ghostscript.NET ( available on Nuget ).
If necessary install Ghostscript 9.52 for Windows (32 bit)
I hope I was helpful.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs" Inherits="Default4" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="flupload" runat="server" />
<br />
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
</div>
</form>
</body>
</html>
using Ghostscript.NET;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Hosting;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default4 : System.Web.UI.Page
{
protected void btnSubmit_Click(object sender, EventArgs e)
{
String PdfFolderPath = HostingEnvironment.MapPath("~/PdfFolder/" + flupload.FileName);
HttpPostedFile file = HttpContext.Current.Request.Files[0];
file.SaveAs(PdfFolderPath);
Pdf2ImageConversion(flupload.FileName, PdfFolderPath);
}
private void Pdf2ImageConversion(string FileName, string PdfFolderPath)
{
String FileNameWithoutExtension = Path.GetFileNameWithoutExtension(FileName);
String ImgFolderPath = HostingEnvironment.MapPath("~/ImgFolder/"
+ FileNameWithoutExtension + ".jpeg");
var info = new System.IO.FileInfo(ImgFolderPath);
if (info.Exists.Equals(false))
{
GhostscriptPngDevice img = new GhostscriptPngDevice(GhostscriptPngDeviceType.Png16m);
img.GraphicsAlphaBits = GhostscriptImageDeviceAlphaBits.V_4;
img.TextAlphaBits = GhostscriptImageDeviceAlphaBits.V_4;
img.ResolutionXY = new GhostscriptImageDeviceResolution(200, 200);
img.InputFiles.Add(PdfFolderPath);
img.Pdf.FirstPage = 1;
img.Pdf.LastPage = 1;
img.PostScript = string.Empty;
img.OutputPath = ImgFolderPath;
img.Process();
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
}

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;

Registration inserting into MS Access database multiple times

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();"/>

Asp.net, using <%=getter%> in aspx file, The Controls collection cannot be modified because the control contains code blocks

i have an aspx, aspx.cs file, in the aspx file i m using javascript functions,
in the javascript code i use the getter (<%=getSize%>) method defined in the aspx.cs file,
but the page returns: "The Controls collection cannot be modified because the control contains code blocks" why?
<!-- language-all:lang-js -->
<%# Page Language="C#" AutoEventWireup="true" CodeFile="uploadFile.aspx.cs"
Inherits="UploadControl_CustomProgressPanel" Title="Untitled Page" %>
<!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">
<title>Untitled Page</title>
<script language="javascript" type="text/javascript">
var size = <%=getSize%>;
var id= 0;
function ProgressBar()
{
if(document.getElementById("FileUpload1").value != "")
{
document.getElementById("divProgress").style.display = "block";
document.getElementById("divUpload").style.display = "block";
id = setInterval("progress()",20);
return true;
}
else
{
alert("Select a file to upload");
return false;
}
}
function progress()
{
//size = size + 1;
if(size > 299)
{
clearTimeout(id);
}
document.getElementById("divProgress").style.width = size + "pt";
document.getElementById("lblPercentage").firstChild.data = parseInt(size / 3) + "%";
}
aspx.cs file:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
public partial class UploadControl_CustomProgressPanel : System.Web.UI.Page
{
protected int size = 2;
protected int getSize{ get { return this.size; }}
protected void Page_Load(object sender, EventArgs e)
{
string UpPath;
UpPath = "C:\\";
if (! Directory.Exists(UpPath))
{
Directory.CreateDirectory("C:\\");
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//StatusLabel.Text = "File scelto, Upload in corso..";
if(FileUpload1.HasFile)
{
try
{
string filePath = Request.PhysicalApplicationPath;
filePath += "classic/hub/csv/";
filePath += FileUpload1.FileName;
this.size = 50;
FileUpload1.SaveAs(filePath);
//StatusLabel.Text = "Upload status: File uploaded!";
Label1.Text = "Upload successfull!";
}
catch(Exception ex)
{
//StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
}
You haven't posted the full HTML but try to move your script out of the <head> tag.
Is getSize a property or a function? If its a property size will take the value that it is at page load, if the its a function then you need to look at page methods as you cannot call it in this way, heres an example

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