response.redirect doesnt work - c#

When control reaches response.redirect line then the following error is produced in browser.
the url in response.redirect is correct.
The page isn't redirecting properly
Firefox has detected that the server is redirecting the request for this address in a way that will never complete.
* This problem can sometimes be caused by disabling or refusing to accept
cookies.
here is the code
using System;
using System.Collections;
using System.Configuration;
using System.Data;
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;
public partial class MasterPage : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void imgbtnLogin_Click(object sender, ImageClickEventArgs e)
{
UserFunction objUser = new UserFunction();
UserProperties objUserProperties = new UserProperties();
IUserFunction iUserFunction = (IUserFunction)objUser;
objUserProperties.UserName = txtUserName.Text;
objUserProperties.Password = txtPassword.Text;
string userName = txtUserName.Text; ;
string password = txtPassword.Text; ;
DateTime login = DateTime.Now;
DateTime? logout = null;
int UserId;
string StartUpPage;
bool success = iUserFunction.ValidateUser(objUserProperties, out StartUpPage);
if (success)
{
Session["UserId"] = objUserProperties.UserId;
Session["RoleId"] = objUserProperties.RoleId;
Session["UserName"] = objUserProperties.UserName;
Session["MyTheme"] = objUserProperties.Theme;
iUserFunction.AddLoginHistory(objUserProperties.UserId, login, logout, 1);
Response.Redirect(StartUpPage);
}
else
{
Label1.Text = "Wrong UserName/password.";
//ScriptManager.RegisterStartupScript(this, this.GetType(), "ClientScript", "alert('Invalid Credential');", true);
}
}
}

Could it be that you are redirecting to an endless loop? Here is a link to some info for that error.
If you had code like below for the two pages this could happen.
Page1.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
Response.Redirect(Page2Url);
}
Page2.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
Response.Redirect(Page1Url);
}
UPDATE
If you are positive it's not an infinite loop in your code I would follow the steps in this link and see if the issues is caused by cookies.

You are redirecting to the same page, causing an infinite loop.

Related

Issue with Session Variables

So I'm trying to make a simple banking website using C# and ASP.net and I'm just learning about Session Variables for the first time. I have a starting account balance of 1000 dollars and I want to transfer that to another page and have that balance updated via withdrawals or deposits and then update the balance. Heres my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Project4.Forms
{
public partial class Services : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click1(object sender, EventArgs e)
{
double userInput = double.Parse(txtAmount.Text);
Session["userInput"] = userInput;
Session["balance"] = 1000.00;
double balance = Convert.ToDouble(Session["balance"]);
Session["userAction"] = ddlSelectService.SelectedItem.Text;
if (ddlSelectService.SelectedItem.Text == "Withdrawl")
{
balance -= userInput;
}
else if (ddlSelectService.SelectedItem.Text == "Deposit")
{
balance += userInput;
}
else
{
}
Response.Redirect("Status.aspx");
}
}
}
I understand the root of my problem is probably the original Session["balance"] = 1000.00; but I'm not sure how to declare a starting amount and then it not affect the balance when I return to this page from the results page. Any help is appreciated, also as I said in the beginning this is a barebones simple atm website please don't suggest anything too crazy because I am a beginner.
I don't do asp.net, so this is just a guess, but maybe try only setting the default value if it's null, something like: if (Session["balance"] == null) Session["balance"] = 1000;. It also seems like this should be in the Page_Load event, not the btnSubmit_Click event, since it only has to happen once.
Finally, don't forget to update the session variable after setting the new balance:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["balance"] == null) Session["balance"] = 1000;
}
protected void btnSubmit_Click1(object sender, EventArgs e)
{
double userInput;
if (!double.TryParse(txtAmount.Text, out userInput))
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert",
"alert('Input must be a valid double');", true);
return;
}
Session["userInput"] = userInput;
double balance = Convert.ToDouble(Session["balance"]);
Session["userAction"] = ddlSelectService.SelectedItem.Text;
if (Session["userAction"] == "Withdrawl")
{
balance -= userInput;
}
else if (Session["userAction"] == "Deposit")
{
balance += userInput;
}
Session["balance"] = balance;
Response.Redirect("Status.aspx");
}

How to make an login form, my button doesnt do anything

First at all i am new at visual C#. I am trying to make a simple login form with only password login, but when i press button nothing happens. I want to check if there is a user in db which is online.
I dont know where i am making the mistake.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SportStat.Forme
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void btnUlaz_Click(object sender, EventArgs e)
{
ulaz();
}
private void ulaz()
{
if (txtPassword.Text == "")
{
MessageBox.Show("Morate upisati lozinku", "caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
return;
}
var sql = "select * from users where password='" + txtPassword.Text + "'";
var dt = sustav.puniDt(sql);
if (dt.Rows.Count == 0)
{
MessageBox.Show("Neispravna lozinka", "caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
txtPassword.Focus();
return;
}
if ((string)dt.Rows[0]["password"] != txtPassword.Text)
{
MessageBox.Show("Neispravna lozinka", "caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
txtPassword.Focus();
return;
}
sustav i = new sustav();
i.idUser = (int)dt.Rows[0]["idUser"];
i.pswd = (int)dt.Rows[0]["pswd"];
i.prezimeIme = (int)dt.Rows[0]["prezimeIme"];
i.idKlub = (int)dt.Rows[0]["idKlub"];
int count = i.pswd;
if (count == 1)
{
MessageBox.Show("Login Successful!");
this.Hide();
frmMain fm = new frmMain();
fm.Show();
}
this.Close();
}
private void Form2_Load(object sender, EventArgs e)
{
}
}
}
Can someone help me with this problem.
Can't comment, too low rep..
Try to put another button on the form and call ulaz(); from that new button.
Sometimes, if you delete button and add them again, or copy paste code, methods get autoassign another name.
For example:
private void btnUlaz_Click(object sender, EventArgs e)
{
ulaz();
}
private void btnUlaz_Click_1(object sender, EventArgs e)
{
ulaz();
}
First one wont work.
I don't know if this is the case in your problem but it's worth trying..

Writing to CSV File in C#

I am creating a clock for clocking into a business. Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
String Code;
String Name;
String InOut;
Boolean Luke = true;
String csvPath = "C:/users/luke/documents/C#/csvProject.csv";
StringBuilder Header = new StringBuilder();
StringBuilder csvData = new StringBuilder();
public Form1()
{
InitializeComponent();
FormBorderStyle = FormBorderStyle.None;
WindowState = FormWindowState.Maximized;
TopMost = true;
Header.AppendLine("Timestamp, Name");
File.AppendAllText(csvPath, Header.ToString());
textBox1.Font = new Font("Arial", 30, FontStyle.Bold);
}
private void button_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
Code = Code + button.Text;
textBox1.Text = Code;
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
FormBorderStyle = FormBorderStyle.Sizable;
WindowState = FormWindowState.Normal;
TopMost = false;
}
}
private void button13_Click(object sender, EventArgs e)
{
//clear
Code = null;
textBox1.Text = Code;
}
private void button10_Click(object sender, EventArgs e)
{
//in or out
DateTime timeStamp = DateTime.Now;
if (Code == "123")
{
Name = "Luke";
}
Button button = (Button)sender;
csvData.AppendLine(timeStamp + "," + Name + "," + button.Text);
File.AppendAllText(csvPath, csvData.ToString());
Code = null;
textBox1.Text = Code;
}
private void button14_Click(object sender, EventArgs e)
{
}
}
}
My layout consists of a number pad, in button, and out button. When the user presses the in button after they enter their code, the program should write in the CSV file: Timestamp, Name, In. When I tested the code by clocking in, the program writes one row correctly. When I clock in and then clock out, it creates two rows of me clocking in and one row of me clocking out. I was wondering if anyone could help me find what is going wrong in the code. Thanks.
You need to empty csvData after writing it to the file.

persistent text boxes in c# asp.net

I fill the textboxes on page_load event.Then I edit textboxes data and tried to update data. Variables are assigned with old values. How can I do to get the new values.
Here is my 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.Configuration;
using System.Data;
using System.Data.SqlClient;
public partial class mymembertype : System.Web.UI.Page
{
public static int mem_typeid;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["valueid"] != null)
{
mem_typeid = (int)(Session["valueid"]);
string memtype_name = Convert.ToString(Session["valueName"]);
string rate = Convert.ToString(Session["rate"]);
txtmembtype.Text = Convert.ToString(memtype_name);
txtdscrate.Text = rate;
Insert_membertype.Text = "Update";
}
}
protected void Insert_membertype_Click(object sender, EventArgs e)
{
funtions fun = new funtions();
if (txtmembtype.Text != "" && txtdscrate.Text != "" )
{
if (Insert_membertype.Text == "Save")
{
string membetype = txtmembtype.Text;
int dscrate = Convert.ToInt32(txtdscrate.Text);
bool chk = fun.Insert_membertype(membetype, dscrate);
if (chk)
lblInfo.Text = " saving membertype successful";
else
lblInfo.Text = "Error saving membertype";
}
else
{
string membetype = txtmembtype.Text;
int dscrate = Convert.ToInt32(txtdscrate.Text);
bool chk = fun.Update_memberType(mem_typeid, membetype, dscrate);
if (chk)
lblInfo.Text = " Updating membertype successful";
else
lblInfo.Text = "Error Updating membertype";
}
}
}
}
As you see second condition block is for updating data. But it have only values in page load.Now new data is assigned. Please ....
Your problem is that Page Load is called before the event handler for your controls. If you want to understand more about the order things happen in ASP.net just Google "ASP.Net Page Lifecycle" - if you're going to be doing a lot of development I recommend at least getting a basic understanding of what ASP.Net is doing.
You'll want to change your page load to check if the current request is a postback.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack && Session["valueid"] != null)
{
// Doing stuff
}
}
The "IsPostBack" variable is false the first time the page is loaded, and then is true for every subsequent load.
Try if(!IsPostBack) method in Pageload event
You need to write the code inside page_load under IsPostback condition like below to get the updated values
if (!IsPostBack)
{
// Bind your code here
}
write a code GetData Method.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetData();
}
}
public void GetData()
{
}

computation after choosing on a dropdownlist

I'm creating a simple patients billing program using Asp.net c#. Now, I have a dropdownlist with items "Ward" , "Semi Private" and "Private" If the user would choose ward the textbox below it would automatically be 700, if Semi Private it should be 1000 and if Private it should be 2000. I also have a textbox under it indicating how many days the patient stayed, the user is the one who should input the days, and for example he's from the ward room and the days he stayed was 3 then the computation should be 700 * 3. I also have a textbox that will display the answer. I hope u guys understand the things I explained above. So far, here are my codes:
Default.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.Text == "Ward")
{
TextBox4.Text = "700";
}
if (DropDownList1.Text == "Semi Private")
{
TextBox4.Text = "1000";
}
if (DropDownList1.Text == "Private")
{
TextBox4.Text = "2000";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
}
}
First of all add an attribute in your asp tag for dropdownlist like-
<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="true">
Then in the event, write the following code-
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = DropDownList1.SelectedItem.ToString();
if(selected == "Ward")
{
int NetAmount = 700 * 3; //you can use any int variable in place of "3" as well
TextBox1.Text = NetAmount.ToString();
}
else if(selected == "Semi Ward")
{
TextBox1.Text = "1000";
}
else
{
TextBox1.Text = "2000"
}
}
That's it. Hope it will help.

Categories

Resources