I have the following code to check that a query string has not changed:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
Label_Error.Visible = false;
string query_string = Request.QueryString["GUID"].ToString();
Session["GUID"] = query_string;
}
else
{
string GUID = "";
try
{
GUID = Session["GUID"].ToString();
}
catch (Exception)
{
Session.Abandon();
Response.Redirect("CheckOutErrorPage.htm");
return;
}
if (GUID.Equals(Request.QueryString["GUID"].ToString()) == false)
{
Session.Abandon();
Response.Redirect("CheckOutErrorPage.htm");
}
}
}
Now, I have this code in a button-click event handler to check that the value of the query string has not changed (again):
protected void ImageButton_LogIn_Click(object sender, ImageClickEventArgs e)
{
Validation val = new Validation();
string GUID = "";
string query_string = "";
try
{
GUID = Session["GUID"].ToString();
query_string = Request.QueryString["GUID"].ToString();
}
catch (Exception)
{
Session.Abandon();
Response.Redirect("CheckOutErrorPage.htm");
return;
}
if (val.EmptyString(GUID) == true || val.checkTransactionGUIDExists(GUID) == false || GUID.Equals(query_string) == false)
{
Session.Abandon();
Response.Redirect("CheckOutErrorPage.htm");
}
Now, the problems are two:
1) if I change the query string in the URL and click on the button, the user is not redirected to the error page.
2) if I change the query string in the URL and hit enter in the address bar, the user is not redirected to the error page.
What I want basically is that, when the user is redirected to the web page, it saves the query string into a session. If the user changes the value of the query string in the address bar, and either pressed enter in the address bar or presses my button, he is redirected to the error page.
However, my code is failing. Can anyone help please? Thanks :)
How about this instead?
protected void Page_Load(object sender, EventArgs e)
{
// Always get the query string no matter how the user go to this page
string query_string = Request.QueryString["GUID"].ToString();
// Only store the query string in Session if there is nothing in Session for it
if(null == Session["GUID"])
{
Session["GUID"] = query_string;
}
if (!this.IsPostBack)
{
Label_Error.Visible = false;
}
// Always check to see if the query string value matches what is in Session
string GUID = "";
try
{
GUID = Session["GUID"].ToString();
}
catch (Exception)
{
Session.Abandon();
Response.Redirect("CheckOutErrorPage.htm");
return;
}
if (GUID.Equals(Request.QueryString["GUID"].ToString()) == false)
{
Session.Abandon();
Response.Redirect("CheckOutErrorPage.htm");
}
This should solve your problem of the Session value being overwritten when a query string is put into the address bar and enter is pressed by the user.
I think you problem is that Response.Redirect needs the false at the final of the sentence like Response.Redirect("CheckOutErrorPage.htm", false); becouse that you have it inside the try cath the error will be throw.
I hope that help you.
Related
I have cookies and viewstate in below control .
This ajax Control is used to upload multiple file images.
protected void OnUploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
int userid = 25;
DAL_Cart objdalcart = new DAL_Cart();
if (Viewstate["Imagestringname"] == null)
{
objdalcart.InsertTempImage(userid, ImageName, 1);
}
else
{
objdalcart.InsertTempImage(userid, ImageName, 0);
}
Response.Cookies["JewelleryUserCookiesUserId"].Value = Convert.ToString(userid);
Response.Cookies["JewelleryUserCookiesUserId"].Expires = DateTime.Now.AddYears(1);
Viewstate["Imagestringname"] = ImageName + ",";
}
The issue is when I try to retrive view state value or Cookies value on different click event of button in same page I am not able to retrive the value
protected void lnkcheckout_Click(object sender, EventArgs e)
{
if (Request.Cookies["JewelleryUserCookiesUserId"] == null || Request.Cookies["JewelleryUserCookiesUserId"].Value == "")
{
}
if (Viewstate["Imagestringname"] != null)
{}
}
For both the case it is going in if condition. for viewstate I have placed Enableviewstate=true on master page .Any idea why?
Review
Want ajax multiple file upload on my button click event
var c = new HttpCookie("JewelleryUserCookiesUserId");
c.Value = Convert.ToString(userid);
c.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(c);
Just note: this is insecure. the client can manipualte the cookie...
I have the following code from the site master (where the login form is)
protected void btnLogin_Click(object sender, EventArgs e)
{
string dt = DateTime.Now.ToString();
Response.Cookies["LastLogin"].Value = dt.ToString();
Response.Cookies["LastLogin"].Expires = DateTime.Now.AddDays(365);
}
So basically I save the current datetime in a cookie when a users logs in.
Then in the profile review page, I wrote the following:
protected void Page_Load(object sender, EventArgs e) {
if (!Page.IsPostBack)
{
if (Request.Cookies["LastLogin"] != null)
{
lblMessage.Text = Request.Cookies["LastLogin"].Value;
}
}}
The thing is that it works (it displays the date and time), but not for the previous log in but for the actual login, obviously, but thats why I'm asking - How can I solve this without having to do anything with database? How can I not "override" the previous value but also save the new one?
Using one cookie LastLogin to save the last login information which can used by rest of your application and CurrentLogin to save current login timestamp.
protected void btnLogin_Click(object sender, EventArgs e)
{
string dt = DateTime.Now.ToString();
if (Response.Cookies["CurrentLogin"] != null)
{
HttpCookie oldLoginCookie = new HttpCookie("LastLogin")
{
Expires = Response.Cookies["CurrentLogin"].Expires,
Value = Response.Cookies["CurrentLogin"].Value
};
Response.SetCookie(oldLoginCookie);
}
HttpCookie loginCookie = new HttpCookie("CurrentLogin")
{
Expires = DateTime.Now.AddDays(365),
Value = dt.ToString()
};
Response.Cookies.Add(loginCookie);
}
Also using SetCookie() instead of Cookies.Add() to avoid multiple cookies from being added as advised here. Your Page_Load methods should work as-is as long as you make the above changes.
When doing the login, you can store the previous date (Response.Cookies["LastLogin"].Value, before overwriting it) into a new cookie - then check this new cookie in your page load.
You do need to check that the LastLogin is not empty, in case this is the very first login.
Something like this:
protected void btnLogin_Click(object sender, EventArgs e)
{
if(Request.Cookies["LastLogin"] != null)
{
Request.Cookies["PrevLogin"].Value = Request.Cookies["LastLogin"].Value;
Request.Cookies["PrevLogin"].Expires = DateTime.Now.AddDays(365);
}
string dt = DateTime.Now.ToString();
Response.Cookies["LastLogin"].Value = dt.ToString();
Response.Cookies["LastLogin"].Expires = DateTime.Now.AddDays(365);
}
I am beginning Windows Phone development with Silverlight and web services. I have a web services for User Login where I have two checks before the user is Allowed to log in. I am unable to perform both checks. Only one check is called. My code:
private void login_action(object sender, RoutedEventArgs e)
{
string _username = txtUser.Text;
string _password = txtPass.Password;
kollserviceClient client = new kollserviceClient();
client.validUserCredentialAsync(_username, _password);
client.validUserCredentialCompleted += Client_validUserCredentialCompleted;
client.isStudentUserAsync(_username);
client.isStudentUserCompleted += Client_isStudentUserCompleted;
}
private void Client_isStudentUserCompleted(object sender, isStudentUserCompletedEventArgs e)
{
if (!e.Result)
{
MessageBox.Show("User is Not a Student. Unable to Login", "Error", MessageBoxButton.OK);
return;
}
}
private void Client_validUserCredentialCompleted(object sender, validUserCredentialCompletedEventArgs e)
{
if (e.Result)
{
IsolatedStorageSettings.ApplicationSettings["lgusername"] = txtUser.Text;
NavigationService.Navigate(new Uri("/Home.xaml", UriKind.RelativeOrAbsolute));
}
}
If the Credentials are valid the user is able to log in whether he/she is a student user or not. How can I make both check to be executed?
The way this is coded, I don't believe that you can guarantee the order in which the service calls will return. Therefore, you could store the results from each call, then call a 3rd method that evaluates that both calls have returned. Another option would be to chain the calls so that it does not check if the user is a student until it returns from the credential check and passes, then you can navigate from the return of that call.
First option example:
private void login_action(object sender, RoutedEventArgs e)
{
string _username = txtUser.Text;
string _password = txtPass.Password;
kollserviceClient client = new kollserviceClient();
client.validUserCredentialAsync(_username, _password);
client.validUserCredentialCompleted += Client_validUserCredentialCompleted;
client.isStudentUserAsync(_username);
client.isStudentUserCompleted += Client_isStudentUserCompleted;
}
private bool? isStudent = null;
private bool? isAuthenticated = null;
private void Client_isStudentUserCompleted(object sender, isStudentUserCompletedEventArgs e)
{
isStudent = e.Result;
EvaluateAndNavigate();
}
private void Client_validUserCredentialCompleted(object sender, validUserCredentialCompletedEventArgs e)
{
isAuthenticated = e.Result;
if (isAuthenticated)
{
IsolatedStorageSettings.ApplicationSettings["lgusername"] = txtUser.Text;
}
EvaluateAndNavigate();
}
private void EvaluateAndNavigate()
{
if(isStudent.HasValue && isAuthenticated.HasValue) //both calls have returned
{
if(isStudent.Value && isAuthenticated.Value)
{
NavigationService.Navigate(new Uri("/Home.xaml", UriKind.RelativeOrAbsolute));
}
else
{
MessageBox.Show(string.Format("{0}Unable to Login", isStudent.Value ? "" : "User is Not a Student. " ), "Error", MessageBoxButton.OK);
}
}
}
I am trying to have an error message displayed when a username and password are not recognized.
if (rdr.Read())
{
int id = int.Parse(rdr.GetValue(0).ToString());
string fname = rdr.GetString(1);
Session["ID"] = id;
Session["FName"] = fname;
con.Close();
Response.Redirect("Home.aspx");
}
else
{
Response.Redirect("Login.aspx?err='blabla'"); //Display message
}
The following code (Page_Load) is supposed to be invoked in the else statement, but it is not:
public partial class _Default : System.Web.UI.Page
{
protected string err = "";
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form.Count > 0)
{
err = Request.Form["err"];
}
}
}
Why is this the case?
Thank you all so much!
This is a GET value in the query string, not a POST value in the form. You can use Request.QueryString[] or Request[] which contains POST and GET values.
if (Request.QueryString.Count > 0)
{
err = Request.QueryString["err"];
}
or
if (Request.Count > 0)
{
err = Request["err"];
}
Also, the query string value belongs to the Login page, so you won't be able to access it from _Default. Move your Page_Load logic to Login.aspx.cs.
Generally speaking, based off the class name _Default, I believe you have placed this code in the Default.aspx page. Place the code in the Load for the Login.aspx page. And then also follow the direction provided by jrummell.
i have a confirm and alert message box.
both are getting displayed at the right time.
but in confirm box when i press cancel the applyaction_button_click is getting executed, which should not happen as i return false.
Similar is the case with alert box which returns false still applyaction_button_click is getting executed.
here is my code:
protected void Page_Load(object sender, EventArgs e)
{
ApplyAction_Button.Attributes.Add("onclick", "ShowConfirm();");
}
protected void ApplyAction_Button_Click(object sender, EventArgs e)
{
// Action to be applied
}
JS function:
function ShowConfirm() {
//check if checkbox is checked if is checked then display confirm message else display alert message
var frm = document.forms['aspnetForm'];
var flag = false;
for (var i = 0; i < document.forms[0].length; i++) {
if (document.forms[0].elements[i].id.indexOf('Select_CheckBox') != -1) {
if (document.forms[0].elements[i].checked) {
flag = true
}
}
}
if (flag == true) {
if (confirm("Are you sure you want to proceed?") == true) {
return true;
}
else {
return false;
}
} else {
alert('Please select at least Checkbox.')
return false;
}
}
thanks
When you have a client side event on an asp server control that has a server event and both get triggered with the same action, returning true or false on the client doesn't stop it from executing its server event.
You could try to prevent the button's server event from executing by doing some kind of postback in your javascript code.