Data inside a LIst<String[]> dissappears (UWP) - c#

the situation is the following:
On Page one i have a button that leads to page two and transports itself as an object to that site.
On page 2 i can set a few things that are stored in a List<string[]> that list is now moved by calling a method on Page one that sets the List on that page. and then i return to page one.
Everything is set and the data was received.
Now as soon as i try to access that data it gets null. I have no statement anywhere in the code that could set it to null. I only have to references:
1.
public void setMaterialData(List<string[]> data )
{
MaterialData = data;
}
and 2.
dataObject.materialdata = MaterialData;
and i already checked if the constructor is called again and overwrites it, but it doesn't. And strangely that happens with nothing else in my code so far.
Things that might be important:
I have the cache mode set to enabled,
I noticed that the constructor of the Window is called when i navigate away from page one to page two and i don't know why?(there is no reference to my list in there though)
Thank you in advance for your answer.

if you are not caching page then the newly navigated page is a new instance of the page and that maybe one possibility of getting field and property to Null
another possibility is resetting the variable as the page loads because every time the
page comes up to display it fires up page_loaded event if you are using that for initializing variable and other components than that may reset them to null
can you can check and confirm that if the navigated page is the same as the saved instance simply by checking (savedObj == this)

Related

Passing dynamic value from one ASP page to another using Session?

Guys I am trying to pass a variable from one page to another. Upon searching I found that either QueryString method is used or Session is used for passing variable. I don't like QueryString method as it displays data in URL which could be modified so I went for sessions.
Now I have added a DataGridView in asp which has a button in each row. Upon clicking this button, a session variable is created having the value of 1st column of the row in which the button was clicked and then it redirects to another page in which I am using this session variable.
Now the problem is, when I was using the Visual Studio debugger, this was working fine and the variable value kept changing according to the button click. But once I uploaded the site to hosting, the variable is created the first time I click the button in DataGridView but when I press the button again in different row, the variable value doesn't change. It remains constant, unless I press F5 in browser on the redirected page, only then the value gets updated.
I think the value gets stored in browser's cache and doesn't change until I force refresh the page. What should I do to solve this problem? is there any other way to pass variable other than the above two mentioned methods?
Code for creating session and redirecting :
GridDataItem item = (GridDataItem)e.Item;
string ticketid = item["ID"].Text;
Session["viewID"] = ticketid;
Response.Redirect("View.aspx");
Code for retrieving session :
String s = Session["viewID"] as String;
I would also like to avoid using cookies, many users have cookies disabled in their browsers so using cookies wont be optimal.
Try this on button click event to store in cookie
Response.Cookies["viewID"].Value = Convert.ToBase64String(Encoding.UTF8.GetBytes(ticketid));
and you can get value using this code:
Try this:-----
String s =Encoding.UTF8.GetString(Convert.FromBase64String(Request.Cookies["viewID"].Value));
Sorry I forget .Value after Request.cookies["viewID"]
It was just saving the value in cache. I have to force turnoff the cache settings in ASP web application. Problem solved.

Do I need to cleanup after using System.Reflection in an aspx page?

I have the following method that is called when reloading certain pages in my app. The point being to interrupt the current transaction, ask for authentication and call a specified function when coming back to the page to complete the transaction. State, and the method name are saved in Session in the interim.
After redirecting back to the page, the method executes and everything looks fine, but when clicking on a link to the same page it now just displays the same page, not a new page with empty fields etc. and, no page events fire. Eventually if I leave the page for long enough, maybe 5 minutes, it will refresh the page or clicking a button with a Response.Redirect call will do it.
Call the same page method normally w/o reflection and it looks to be fine. It seems as if using reflection may be keeping the page object in memory and not allowing it to be GCed. What is going on here? There are plenty of workarounds, but I'd still like to understand it for the future.
protected override void OnLoadComplete(EventArgs e)
{
base.OnLoadComplete(e);
if (IsRestoredPageState && priorPageState.CallingFunction != null)
{
var completeAction = this.GetType().GetMethod(priorPageState.CallingFunction);
completeAction.Invoke(this, null);
completeAction = null;
}
}

Viewstate history gets affected by activity on a different page

I have a current problem where on one page, the Viewstate info is disappearing if we open a different page and do a few postbacks there, ie:
Open ListPage, change form selected options and do postback
Press button that opens AddPage on new Tab
On AddPage, add several new entries doing several postbacks, close tab
Go back to ListPage try to refresh the grid
On ListPage, viewstate is empty
So if I have a property that is storing and getting it's value from viewstate, on step 5 is getting null from viewstate.
if (ViewState["Stuff"] == null)
return MyObject.Default;
else
return (MyObject)ViewState["Stuff"];
From my understanding viewstate history size is by default 9 ( <sessionPageState historySize="9" /> ) but I wasn't expecting this to be shared between different pages and don't want to change this value.
I can go around the properties stored by storing them in session with a Guid generated per page, but the form controls and anything that got it's value from the database needs to be re-setted.
Is there any way to make the viewstate history independent between tabs/windows? Or any idea how to go around it?
I'm using Telerik controls on each page if that helps.
Edit: this explanation helped me understand how exactly the viewstate info is stored in session and how sessionPageState configuration affects it.
Found out what was happening,
By default the Pages are storing the ViewState in Session, ie, using the System.Web.UI.SessionPageStatePersister. Knowing this, then the observed behaviour is normal. It only stores a certain amount of page states (postbacks) and for every postback, the older info get lost, no matter in which tab/page the postback is being made of, as long as it's in the same session.
I added this to my pages to tell it to store the ViewState in the page itself, in an hidden field. That was already what I assumed it was happening.
protected override PageStatePersister PageStatePersister
{
get
{
return new HiddenFieldPageStatePersister(this);
}
}

How to clear Session when navigating away from one page

I googled this about 1/2 a hour no hit's. Scenario is that, dynamic scripts are saved in string builder whose "string" representation is stored in session. It just happens that when user navigates away from one page to another the script[from session] gets registered using "RegisterStartupScript". The script is registered in PreRender event of the Page. So i would like to clear this script in session while the page navigates away btw rule out a option to create another session variable and clear previous one. It's a overhead :(
Why are you storing this in Session, do you need to maintain this script in between GET requests?
If only postbacks are relevant you could store it in viewstate as this is maintained only when doing a postback.
If you want this string to be available on GET requests too you might want to introduce a different variable which has an identifier identifying the page for which the script is generated. If the requested page doesn't match the control variable you will have to generate a new script.
How is the user navigating away from the page? Can't you use an ASP.NET button instead of a hyperlink, and then do a Redirect in code once you have cleared your session variable?
protected void btnDoSomething_Click(object sender, EventArgs e)
{
Session["Value"] = String.Empty;
Response.Redirect(strURL, false);
}
OR You could add a variable in the query string and check it in the Page_Load event of the target page:
Webform1.aspx?reset=true
Since I cant comment yet, use onUnload().
It fires on full postbacks too. Ajax postbacks dont fire!
What you need to do, is guaranty inside the onUload function that you only clear the session when you want. Like setting a variable isPostBack to true before the postbacks so onUnload sees the variable and doenst send a request to clear the session.
You may use the JavaScript onUnload() and call an AJAX service, that will clear the server side session.

user control event handler lost on postback

I have a menu usercontrol called LeftMenu that has a bulletedlist of linkitems. It's on the ascx page as such:
<asp:BulletedList ID="PublisherList" DisplayMode="LinkButton" OnClick="PublisherList_Click" cssClass="Menu" runat="server"></asp:BulletedList>
I databind the list in the page_load under if(!isPostBack)
I'm having an issue on a page that loads the control. When the page first loads, the event handler fires. However, when the page posts back it no longer fires and in IE8, when I'm debugging, I get "Microsoft JScript runtime error: Object expected" in Visual Studio pointing at "__doPostBack('LeftMenu$PublisherList','0')." In FF I don't get the error, but nothing happens. I'm not loading the control dynamically, it's loaded on the aspx page using:
<%# Register TagPrefix="Standards" TagName="LeftMenu" Src="LeftMenu.ascx" %>
<Standards:LeftMenu ID="LeftMenu" runat="server"/>
Any ideas of where I'm losing the event handler?
I just realized this is happening on another user control I have as well. A text box and a button and I'm using the default button to make sure pressing the enter key uses that button. .Net converts that in the html to:
<div id="SearchBarInclude_SearchBar" onkeypress="javascript:return WebForm_FireDefaultButton(event, 'SearchBarInclude_QuickSearchButton')">
so as soon as i enter a key in the box I get a javascript error at the line saying "object expected." It seems like the two issues are related.
Edit Again: I think I need to clarify. It's not that I'm clicking on the menu item and it can't find the selected item on postback. I have this search page with the left navigation on it and then the main content of the page is something that causes a postback. Everything is fine with this postback. Once that page has been posted back, now if I click on the bulleted list in the left navigation I get a javascript error and it fails. The page_init for the LeftMenu control is never called.
It sounds like you might be losing the click because you are not DataBinding the list on PostBack. Therefore, the post back is trying to refer to a control (a specific bulleted list item) that does not exist.
You should try binding the list again on PostBack just to see if that fixes your issue. BUT, what should REALLY happen is that the LeftMenu and the BulletedList should store their information into ViewState so that you can ensure that the data that was shown to the user on their initial page load is the same data that the PostBack is processing and working with.
If you have EnableViewState=true for your UserControl and all controls within it, everything should work fine. With ViewState enabled, ASP will reinflate your controls from ViewState after Init has fired. This means that the postback event arg (which points to an index in your control list) will still find the control in that list position. Otherwise the list is empty on postback.
However, ViewState is the work of the devil and was designed simply to foster the illusion that you are working in a stateful environment. It is okay to use it for small amounts of data but typically not advisable for templated controls like repeaters and lists because you have no idea how much data is going to be created in ViewState.
If you are dealing with static, or relatively static data, store it in the application cache and rebind your lists in Page.Init every time (note that it has to be in Init because post-init is when ASP rebinds from ViewState; if you get in there first, your data will be used instead).
If you are dealing with volatile data, you have a problem because the data you rebind must be exactly the same as the original page request, otherwise the postback events will be firing against the wrong rows. In that case you need to either store your initial data in Session or you simply store the list of rows ids (in a hidden variable or Session) and you recreate the data to bind against from the ids each time.
An even better solution is to not use postback events at all. Try to turn all your events into GETs that have an ID on the query string. You can still create the list using binding the first time through the page (as you are currently doing), and you can even GET the same page with a new ID.
If you need to keep state on the same page but need to respond to the user changing a radio button selection (or something else), think about using Ajax calls to update the screen. You also do that with an ID that you pass to the Ajax call.
In general, the more you move from using stateful ASP, the lighter and more responsive your pages will become. You will also be in a better position to move to stateless MVC if necessary. You will also save lots of time lost to debugging obscure problems because ViewState is not available when you need it to be.
The best analysis of ViewState I've read is in the link below. If you fully understand how it works, you can continue to use it without necessarily incurring the costs.
http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/truly-understanding-viewstate.aspx
It's possible that this might be javascript related, and that a script that is loading earlier in the page is throwing an error and causing the page to not be loaded properly.
Are your usercontrols loading any javascript onto the page? Can you check for javascript errors on the initial load of the page?
I moved the code into an existing project we have and for some strange reason, I stopped getting the javascript errors and instead got:
"Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%# Page EnableEventValidation="true" %> in a page.
For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation."
I haven't quite figured out where I'm supposed to put the register event validation with a user control, but in the mean time I just set enableeventvalidation=false and it seems to work now.
It looks like the doPostBack function is missing since its arguments are literals so they couldn't be the cause. Is that one of your own functions or did you mean to call the ASP __doPostBack function?
Have a look at the Firefox error console or allow script debugging in IE and see exactly what object can't be found. Even better, download Firebug and debug it.
I had a similar issue. It turned out that Akamai was modifying the user-agent string because an setting was being applied that was not needed.
This meant that some .NET controls did not render __doPostBack code properly. This issue has been blogged here.

Categories