How to clear/change the query string in aspx page? - c#

I have two pages
1. a.aspx and
2. b.aspx
I pass query string from "b.aspx?save=success" to a.aspx.
In Page Load of a.aspx I have the following code:
Page_Load()
{
if(!Postback)
{
if (Request.QueryString["save"] != null)
{
noDataFound.InnerHtml = "operation success";
}
}
}
Problem: On load of a.aspx page I get the message "operation success". This is Ok.But When I refresh the page again I get the same message as "operation success". How not to display again the same message on page refresh(pressing F5or reload).

function invokeMeMaster() {
var isPostBack = <%= Page.IsPostBack ? "true" : "false" %> ;
if (!isPostBack) {
/* START */
var query = getQueryParams(document.location.search);
var p = query.save;
if (sessionStorage.hits) {
sessionStorage.hits = Number(sessionStorage.hits) + 1;
} else {
sessionStorage.hits = 1;
}
if (p == "success" && (sessionStorage.hits) % 2 == 0) {
document.getElementById("<%=noDataFound.ClientID %>").innerText = "Testing...........";
}
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {}, tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
}
return params;
}
/* END */
} else {
document.getElementById("<%=noDataFound.ClientID %>").innerText = "";
}
}
window.onload = function () {
invokeMeMaster();
};

untested solution (Keeping F5 or Reload of Page in mind), may be you have do something like below:
if(!IsPostBack)
{
if (Request.QueryString["save"] != null && Session["CheckSuccess"] == null)
{
noDataFound.InnerHtml = "operation success";
Session["CheckSuccess"] = "true";
}
else
noDataFound.InnerHtml = string.Empty;
}

The best I can think of is using the IsPostback property to check that.
if (!this.IsPostback)
{
// first try
if (Request.QueryString["save"] != null)
{noDataFound.InnerHtml = "operation success";}
}
NOTE: IsPostback is not set on refresh, only if clicking a button or something alike triggers the ASP.NET postback action.
The other thing you could do is set a Session variable then the 'operation succesful' must be shown (probably you determine this in another Page.
// other page
Session["showSaveMessage"] = true;
// this page
if (Session["showSaveMessage"] == true)
{
// show message
Session["showSaveMessage"] = false;
}
A third option is to move this client side. Create a javascript action on load of the page. When a specific part is added to the query string (#showmessage), you can catch that and show the message (How to get the value from the GET parameters?).
Then redirect to the parameterless version (#) by setting the url to the stripped version. Set window.location.href or window.location.search for that (this won't cause a call to the webserver, since it is all client side).
This circumvents the drawbacks of the first solution, but introduces more code client side. Luckily, ASP.NET MVC has some mechanisms for this. Unfortunately ASP.NET Web Forms doesn't have those.

Related

How to conditionally PopAsync based on what page is currently show to user

Within the same page of my app the user can send off two websocket requests. That I then get two websocket responses. In each of those responses I pop the page from the nav stack. This is in their profile page where they can edit some basic info or change their password. Hopefully they usually would only do one but in the chance they do both and click save then it pops the page twice.
I have been trying to check the current page and if they are still on the profile page to go ahead and pop it but if they are not then skip the popping.
It seems like popasync is not actually removing the page from the stack because I will call the nav stack to a list afterwards to check and it's still there. I tried doing a check if any pages in the stack were the profile pages to then pop it. That still could be sloppy incase there were multiple instances of it in the stack but it would atleast get me in the right direction.
I also tried using MessagingCenter to bring it back to the code behind but that didn't do the trick either.
The main problem here is I only want to pop the page if that is the page the user is currently looking at.
If anyone could point me in the right direction that would be much appreciated.
else if (root.payload?.data?.updateUserFields != null)
{
DabGraphQlUpdateUserFields fields = root.payload.data.updateUserFields;
dbSettings.StoreSetting("Email", fields.email);
dbSettings.StoreSetting("FirstName", fields.firstName);
dbSettings.StoreSetting("LastName", fields.lastName);
GlobalResources.WaitStop();
var UserName = GlobalResources.GetUserName().Split(' ');
GuestStatus.Current.UserName = GlobalResources.GetUserName();
Device.BeginInvokeOnMainThread(() => { Application.Current.MainPage.DisplayAlert("Success", "User profile information has been updated", "OK"); ; });
DabProfileManagementPage profilePage = new DabProfileManagementPage();
Device.BeginInvokeOnMainThread(() =>
{
if (Application.Current.MainPage.Navigation.NavigationStack.Any(p => p is DabProfileManagementPage))
{
var existingPagess = Application.Current.MainPage.Navigation.NavigationStack.ToList();
Application.Current.MainPage.Navigation.PopAsync();
var _lastPage = Application.Current.MainPage.Navigation.NavigationStack.LastOrDefault();
Application.Current.MainPage.Navigation.RemovePage(_lastPage);
var existingPages = Application.Current.MainPage.Navigation.NavigationStack.ToList();
}
});
//Device.BeginInvokeOnMainThread(() => { Application.Current.MainPage.Navigation.PopAsync(); });
}
else if (root.payload?.data?.updatePassword != null)
{
GlobalResources.WaitStop();
if (root.payload.data.updatePassword == true)
{
Device.BeginInvokeOnMainThread(() => { Application.Current.MainPage.DisplayAlert("Success", "Your password has been updated", "OK"); ; });
Device.BeginInvokeOnMainThread(() =>
{
if (Application.Current.MainPage.Navigation.NavigationStack.Any(p => p is DabProfileManagementPage))
{
var existingPagess = Application.Current.MainPage.Navigation.NavigationStack.ToList();
Application.Current.MainPage.Navigation.PopAsync();
var _lastPage = Application.Current.MainPage.Navigation.NavigationStack.LastOrDefault();
Application.Current.MainPage.Navigation.RemovePage(_lastPage);
var existingPages = Application.Current.MainPage.Navigation.NavigationStack.ToList();
}
});
//Device.BeginInvokeOnMainThread(() => { Application.Current.MainPage.Navigation.PopAsync(); });
}
}
As Jason pointed out I just added variable of type int and increased it after a pop happened and reset it once it tries to go past 2. I also reset it to 0 once the user clicks to open the page again. The only issue, which shouldn't happen often is if the user tries to go and change info for a third time without leaving the page. No pop will happen. I thought about adding a timer but I have had apps get messy with timers before so I opted to keep it as is for now. Hoping I do find a way to pop once every time no matter how many times the user decides to hit that function.
else if (root.payload?.data?.updateUserFields != null)
{
DabGraphQlUpdateUserFields fields = root.payload.data.updateUserFields;
dbSettings.StoreSetting("Email", fields.email);
dbSettings.StoreSetting("FirstName", fields.firstName);
dbSettings.StoreSetting("LastName", fields.lastName);
GlobalResources.WaitStop();
var UserName = GlobalResources.GetUserName().Split(' ');
GuestStatus.Current.UserName = GlobalResources.GetUserName();
Device.BeginInvokeOnMainThread(() => { Application.Current.MainPage.DisplayAlert("Success", "User profile information has been updated", "OK"); ; });
if (popRequests < 1)
{
popRequests = popRequests + 1;
Device.BeginInvokeOnMainThread(() => { Application.Current.MainPage.Navigation.PopAsync(); });
}
else
popRequests = 0;
}
else if (root.payload?.data?.updatePassword != null)
{
GlobalResources.WaitStop();
if (root.payload.data.updatePassword == true)
{
Device.BeginInvokeOnMainThread(() => { Application.Current.MainPage.DisplayAlert("Success", "Your password has been updated", "OK"); ; });
if (popRequests < 2)
{
popRequests = popRequests + 1;
Device.BeginInvokeOnMainThread(() => { Application.Current.MainPage.Navigation.PopAsync(); });
}
else
popRequests = 1;
}
}

session does not appear in the label

I created session to move data between pages using c# asp.net but the result does not appear and the program does not give me error in the code
first page code:
Session["New1"] = desc1.Text;
to send data to Label in Second page
code:
var userType = (string)Session["New1"];
if (userType != null)
{
Label1.Text = userType.ToString() ;
}
else
{
// test "2" etc
}
Try this,
if (Session["New1"]!= null)
{
Label1.Text = Session["New1"].ToString() ;
}
else
{
// test "2" etc
}
Try explicitly checking of your Session variable exists before attempting to use it to avoid any null-reference issues :
// Explicitly check that it exists
if (Session["New1"] != null)
{
// Then grab it (if it is a non-string type, then you can use as to cast it
// (e.g. a List might use Session["List"] as List<Widget>;)
Label1.Text = Convert.ToString(Session["New1"]);
}
else
{
// Do something here
}
This assumes that your value will be set prior to this code getting called. Additionally, any hiccups to the web server (e.g. timeouts, restarts, major exceptions, etc.) will clear all of the values within the Session.

How to implement an Action Filter in NopCommerce

I want to change some code in an action of the OpcSaveBilling action from the CheckoutController. I don't want to alter the core code of NopCommerce so i need to try to overide the code with my own custom code.
I've read this article to get me started http://www.pronopcommerce.com/overriding-intercepting-nopcommerce-controllers-and-actions. From what I've read you can execute your own code before an action is executed and after an action is executed. But what I am not getting is the part that the article is leaving open (the actual code that needs to be executed).
What I basicly want is the same function of the original code but with some custom tweaks. I've added a checkbox in the OnePageCheckout view and based on that checkbox it needs to skip the enter shipping addresss part in the checkout or not. (Use the billing address for the shipping address)
I already have that code added to in the core code and this work and skips the step (NOTE: I know I still need to manually add the billing address as shipping address) but like i said i don't want to alter the code in the core of NopCommerce but override of it.
If my question is not understandable and you need more code or explanation I'm happy to provide more. If the way I am doing this is not suitable for what I want, i would appreciate if you tell me!
My code:
The Action Filter class:
using Nop.Web.Controllers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace Nop.Plugin.Misc.MyProject.ActionFilters
{
class ShippingAddressOverideActionFilter : ActionFilterAttribute, IFilterProvider
{
public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
{
if (controllerContext.Controller is CheckoutController && actionDescriptor.ActionName.Equals("OpcSaveBilling", StringComparison.InvariantCultureIgnoreCase))
{
return new List<Filter>() { new Filter(this, FilterScope.Action, 0) };
}
return new List<Filter>();
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// What do I put in here? So that I have the code of the core action but with my custom tweaks in it
}
}
}
Registered the class in DependencyRegistar in the same Nop plugin
builder.RegisterType<ShippingAddressOverideActionFilter>().As<System.Web.Mvc.IFilterProvider>();
A working example with custom code in it. But this is in the core action.
public ActionResult OpcSaveBilling(FormCollection form)
{
try
{
//validation
var cart = _workContext.CurrentCustomer.ShoppingCartItems
.Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart)
.Where(sci => sci.StoreId == _storeContext.CurrentStore.Id)
.ToList();
if (cart.Count == 0)
throw new Exception("Your cart is empty");
if (!UseOnePageCheckout())
throw new Exception("One page checkout is disabled");
if ((_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed))
throw new Exception("Anonymous checkout is not allowed");
int billingAddressId = 0;
int.TryParse(form["billing_address_id"], out billingAddressId);
if (billingAddressId > 0)
{
//existing address
var address = _workContext.CurrentCustomer.Addresses.FirstOrDefault(a => a.Id == billingAddressId);
if (address == null)
throw new Exception("Address can't be loaded");
_workContext.CurrentCustomer.BillingAddress = address;
_customerService.UpdateCustomer(_workContext.CurrentCustomer);
}
else
{
//new address
var model = new CheckoutBillingAddressModel();
TryUpdateModel(model.NewAddress, "BillingNewAddress");
//validate model
TryValidateModel(model.NewAddress);
if (!ModelState.IsValid)
{
//model is not valid. redisplay the form with errors
var billingAddressModel = PrepareBillingAddressModel(selectedCountryId: model.NewAddress.CountryId);
billingAddressModel.NewAddressPreselected = true;
return Json(new
{
update_section = new UpdateSectionJsonModel()
{
name = "billing",
html = this.RenderPartialViewToString("OpcBillingAddress", billingAddressModel)
},
wrong_billing_address = true,
});
}
//try to find an address with the same values (don't duplicate records)
var address = _workContext.CurrentCustomer.Addresses.ToList().FindAddress(
model.NewAddress.FirstName, model.NewAddress.LastName, model.NewAddress.PhoneNumber,
model.NewAddress.Email, model.NewAddress.FaxNumber, model.NewAddress.Company,
model.NewAddress.Address1, model.NewAddress.Address2, model.NewAddress.City,
model.NewAddress.StateProvinceId, model.NewAddress.ZipPostalCode, model.NewAddress.CountryId);
if (address == null)
{
//address is not found. let's create a new one
address = model.NewAddress.ToEntity();
address.CreatedOnUtc = DateTime.UtcNow;
//some validation
if (address.CountryId == 0)
address.CountryId = null;
if (address.StateProvinceId == 0)
address.StateProvinceId = null;
if (address.CountryId.HasValue && address.CountryId.Value > 0)
{
address.Country = _countryService.GetCountryById(address.CountryId.Value);
}
_workContext.CurrentCustomer.Addresses.Add(address);
}
_workContext.CurrentCustomer.BillingAddress = address;
_customerService.UpdateCustomer(_workContext.CurrentCustomer);
}
// Get value of checkbox from the one page checkout view
var useSameAddress = false;
Boolean.TryParse(form["billing-address-same"], out useSameAddress);
// If it is checked copy the billing address to shipping address and skip the shipping address part of the checkout
if (useSameAddress)
{
var shippingMethodModel = PrepareShippingMethodModel(cart);
return Json(new
{
update_section = new UpdateSectionJsonModel()
{
name = "shipping-method",
html = this.RenderPartialViewToString("OpcShippingMethods", shippingMethodModel)
},
goto_section = "shipping_method"
});
}
// If it isn't checked go to the enter shipping address part of the checkout
else
{
if (cart.RequiresShipping())
{
//shipping is required
var shippingAddressModel = PrepareShippingAddressModel(prePopulateNewAddressWithCustomerFields: true);
return Json(new
{
update_section = new UpdateSectionJsonModel()
{
name = "shipping",
html = this.RenderPartialViewToString("OpcShippingAddress", shippingAddressModel)
},
goto_section = "shipping"
});
}
else
{
//shipping is not required
_genericAttributeService.SaveAttribute<ShippingOption>(_workContext.CurrentCustomer, SystemCustomerAttributeNames.SelectedShippingOption, null, _storeContext.CurrentStore.Id);
//load next step
return OpcLoadStepAfterShippingMethod(cart);
}
}
}
catch (Exception exc)
{
_logger.Warning(exc.Message, exc, _workContext.CurrentCustomer);
return Json(new { error = 1, message = exc.Message });
}
}
Nobody can tell you what you need to put in OnActionExecuting, because there is so much you can do in it.
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// What do I put in here? So that I have the code of the core action but with my custom tweaks in it
}
Rule of thumb? Write any code like how you'll write an Action. The only tweak is, instead of returning ActionResult, you should set filterContext.Result (you can't return anything as this is a void method).
For example, setting the following will redirect to home page before even executing the action you are overriding.
filterContext.Result = new RedirectToRouteResult("HomePage", null);
Remember this is OnActionExecuting, so this is executed before the Action you are overriding. And if you redirects it to another page, it'll not call the Action you are overriding. :)

C# ASP Confirm Pop Up (Again)

I looked around in several forums for an answer to my problem, but I only found the solution in combination with a button.
I have to "translate" a website from Javascript to C# ASP because I have to store data in a SQL DB.
Now, I had a validation routine were the entries were checked before the data as sent by mail (that was in the old website, now it should be stored). One of the checks was only a warning (confirm) and not an error (alert). In JavaScript I did this with:
if (a > b){
Check = confirm("Are you sure your entry is correct?");;
if (Check == false){
return false;
}
}
Since I have many more checks before and after this part, I can't hook it to a button.
Is there a way to solve it like the alert? e. g.
<script type = "text/javascript" language = "javascript">
<asp:Literal id="ltlAlert" runat="server" EnableViewState="False"> </asp:Literal>
</script>
private void Say(string Message)
{
// Format string properly
Message = Message.Replace("'", "\\'");
Message = Message.Replace(Convert.ToChar(10).ToString(), "\\n");
Message = Message.Replace(Convert.ToChar(13).ToString(), "");
//Display as JavaScript alert (!)
ltlAlert.Text = "alert('" + Message + "')";
}
like:
private bool Ask(string Message)
{
// Code to display confirm from Javascript here
return;
}
I'm pretty new to C# (otherwise I programmed in VB, VBA and - Long ago - in COBOL) so I'm still trying to get my bearings.
Are you looking for something like the following where you can check several conditions before submitting a form? The button would call that JavaScript function.
function ValidateForm(){
if(email is invalid){
alert("Email is invalid");
return;
}
if(phone is invalid){
alert("phone is invalid");
return;
}
var Check = confirm("Are you sure your entry is correct?");
if (Check == false){
return false;
}
else{ Submit Form };
}

My cookie test isn't working

I am testing to see whether the user has cookies turned on and I don't seem to be doing something right.
Here is my test:
private bool CookiesAllowed()
{
var testCookie = new HttpCookie("TestCookie", "abcd");
System.Web.HttpContext.Current.Response.Cookies.Set(testCookie);
var tst = System.Web.HttpContext.Current.Request.Cookies.Get("TestCookie");
if (tst == null || tst.Value == null)
{
return false;
}
return true;
}
I'm putting a cookie out there... and then getting it back. But it always succeeds.
Here is how I'm disabling them:
I go to Gmail and it tells me my cookies are disabled so I believe I am doing that part right.
What am I doing wrong?
EDIT
To answer James' question, I am calling this from my logon screen, which is my entry screen as the first check:
public ActionResult LogOn(string id)
{
if (!CookiesAllowed())
{
return View("CookiesNotEnabled");
}
Also, I have tested this live, outside of visual studio and not at localhost and it did the same thing.
You have to let your client/browser do a new Request in order to see if you get the cookie back. When you add a Cookie to the response object, you can only check the presence of it in subsequent new Requests.
Here's a way to do it within the same page in ASP.NET WebForms (since I saw your edit indicating you are using MVC):
private bool IsCookiesAllowed()
{
string currentUrl = Request.RawUrl;
if (Request.QueryString["cookieCheck"] == null)
{
try
{
var testCookie = new HttpCookie("SupportCookies", "true");
testCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(testCookie);
if (currentUrl.IndexOf("?", StringComparison.Ordinal) > 0)
currentUrl = currentUrl + "&cookieCheck=true";
else
currentUrl = currentUrl + "?cookieCheck=true";
Response.Redirect(currentUrl);
}
catch
{
}
}
return Request.Cookies.Get("SupportCookies") != null;
}
This code snippet is inspired by this thread.

Categories