I'm now work on ASP.NET project
and want to use Page.Cache property to cache the String data like bellow way.
but, it behaves like having a Session scope.
I understand Page.Cache property is retuning a current System.Caching.Cache object
and that must have an Application scope.
I could check below code works fine, but my project's code not -- it makes cache for per session.
And, that replaced Cache of Application (with Lock and UnLock) works fine too.
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim key_str As String = "cache_key"
Dim cached_value = Cache.Get(key_str)
If cached_value Is Nothing Then
cached_value = "stored_value"
Cache.Insert(key_str, cached_value, Nothing, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(5), CacheItemPriority.Normal, New CacheItemRemovedCallback(AddressOf RemovedCallback))
End If
Label1.Text = cached_value
End Sub
Public Sub RemovedCallback(ByVal key As String, ByVal value As Object, ByVal removedReason As CacheItemRemovedReason)
Debug.WriteLine("#Callback!")
End Sub
End Class
above code
works fine
my project code
works like session scope
and If replaced Cache with Application, that works fine
Are there any possible to occur such a behavior or not?
(or I just made a mistake on anywhere else in logics?)
Please point out If concerning some configure files.
I maybe made a mistake.
My project is a Azure project and so Page.Cache is to store a data for per azure instance? Right?
Related
Using vb.net 4.5 and Telerik 2017.2.711.45 (Q2)
I am trying to get radgrid filter expressions and a public string variable to persist across postbacks.
With EnableViewState=FALSE, radgrid filter expressions do not persist through postback, however a public string variable (stringVar) does persist.
When I set EnableViewState=TRUE the filter expressions in radgrid do persist, however it causes stringVar to not persist.
From my understanding of ViewState, it makes no sense that setting EnableViewState=TRUE would cause stringVar to not persist across postbacks. I would love to know why this is occurring and what I could do to resolve this.
EDIT:
The highlighted Line is where an error would be thrown because ReportTitle no longer has a value.
Partial Class displayxslgrid
Public ReportTitle As String
Public ReportsDB As reportDataBase
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Page.EnableViewState = True
Reports = New reportDataBase.Global_Functions(System.Web.HttpContext.Current)
End Sub
Protected Sub RadGrid1_NeedDataSource(sender As Object, e As Telerik.Web.UI.GridNeedDataSourceEventArgs) Handles RadGrid1.NeedDataSource
Call BindRadGrid1()
End Sub
Protected Sub RadGrid1_ItemCommand(ByVal source As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles RadGrid1.ItemCommand
Dim strReportTitle As String
Select Case e.CommandName
Case RadGrid.ExportToExcelCommandName, RadGrid.ExportToWordCommandName, RadGrid.ExportToCsvCommandName
strReportTitle = ReportTitle.Trim
End Select
End Sub
Public Sub BindRadGrid1()
Dim strReportTitle As String
Dim dt As DataTable = Nothing
ReportTitle = dt.Rows(0).Item("ReportTitle")
strReportTitle = dt.Rows(0).Item("ReportTitle").ToString
'RadGrid1 Data source gets set here along with other stuff
End Sub
End Class
Using view state is normal, and Telerik controls need it to preserve their values across post-backs. A public string property on your page class should not persist, and should be set/calculated every time. If you absolutely need something like that to persist, save the value in a hidden server control, or have it in the QueryString of the URL.
So it turns out, that that variable was not truly persisting. It was getting its value from the bindradgrid1. When EnableViewState=True the need data source event is not fired, therefore the bindradgrid1 is not called and the variable does not get a value. Simple fix was adding a bindradgrid1() in the item command sub so that even with EnableViewState=True, bindradgrid1() will still get called. Thanks for all who helped.
This is probably is straight forward.
I have a DropDownList and once a user click on an item I need to remember what they clicked before the DropdownList gets rebound so I made a variable outside.
But the problem is that variable cant be seen. The only time I managed to get it to work is using Public Shared variableoutside as Integer. But this makes it available to every page I only need it on this page I am running.
Dim variableoutside as Integer
Protected Sub lstTest_DataBound(sender As Object, e As EventArgs) Handles lstTest.DataBound
if variableoutside > 0 Then lstTest.SelectedIndex = variableoutside
End Sub
Protected Sub lstTest_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstTest.SelectedIndexChanged
variableoutside = lstTest.SelectedIndex
lstTest.DataValueField = "ID"
lstTest.DataTextField = "testvalue"
lstTest.DataSource = List_TestA.List_Test()
lstTest.DataBind()
End Sub
Fields only live as long as the request. On postback you get a new instance of the Page class, so new instance fields.
A Shared (static in C#) field does live longer (entire lifetime of the application), but it's value is shared between all users of your site - probably not what you want.
A solution is to store that value in Session. That is designed for request-spanning storage of user-specific values. Note that the values are stored as Object, so you will need to cast back to Int.
EDIT
for instance, your code
Protected Sub lstTest_DataBound(sender As Object, e As EventArgs) Handles lstTest.DataBound
if variableoutside > 0 Then lstTest.SelectedIndex = variableoutside
End Sub
could be
Protected Sub lstTest_DataBound(sender As Object, e As EventArgs) Handles lstTest.DataBound
Dim variableoutside as Integer
variableoutside = Session("ListIndex") ' probably cast this to Integer
if variableoutside > 0 Then lstTest.SelectedIndex = variableoutside
End Sub
(note that I am guessing at the correct VB syntax, so you may need to tweak this)
And of course in the other method, instead of:
variableoutside = lstTest.SelectedIndex
use this to set that session value:
Session("ListIndex") = lstTest.SelectedIndex
You can remove that class field, as that's no longer used.
Wow, that is really cool. I like it, Thank you...
I changed it a little though and ditched the Dim variableoutside
and used the Session("lstTest") as my main variable. It remembers every time.
You have opened lots of doors for me, and now I can use them to remember lots
of settings for DropDownList,CheckBoxes, Textboxes.
Only thing I wanted to know is how many of those session variables are you allowed, as I am assuming that the sessions are using cookies and cookies have a max allowed per client and browser before that start overwriting themselves. At least this was true when I was using PHP back in the day.
I have the following code. During page load, I get the customer object from the database. After that when I try to access the same object in a different method, the object comes out as empty. Assume Student object has properties like firstName, lastName etc.
Public class Test
Public oStudent as Student
Public Sub Page_Load(ByVal sender as Object, ByVal e as System.EventArgs) Handles Me.Load
oStudent = getStudent(22) 'This is just a sample. This is not my actual database.
End Sub
Public Sub Update(ByVal sender as Object, ByVal e as System.EventArgs) Handles crtlStudent.Update
Update(oStudent)'This one updates makes a database call to update the studnet
End Sub
End class
When the page loads, the student is returned from the database correctly. However, when I'm on my update method, oStudent object becomes null/empty. Is this the way the page life cycle works? If yes, I would need to store the oStudent in a session or cache it right? Is there any other way to prevent the oStudent from becoming null other using session variables or caching it?
It is not the case that the object is null in the other method but after the page is disposed. That happens at the end of every page's lifecycle, so when it was rendered as HTML and sent to the client.
So you either have to re-initialize/load the object on every postback or persist it somewhere. In your sample-code you are loading it always in Page_Load, hence i doubt that it's null anywhere. So i guess that it's not the real code which could be:
Public Sub Page_Load(ByVal sender as Object, ByVal e as System.EventArgs) Handles Me.Load
If Not IsPostBack Then
oStudent = getStudent(22) ' in a button-click handler it will be null since it's a PostBack
End If
End Sub
Is there any other way to prevent the oStudent from becoming null
other using session variables or caching it?
Nine Options for Managing Persistent User State in Your ASP.NET Application
i am using the WebBrowser control in asp.net page. here is the simple code:
Public Class _Default
Inherits System.Web.UI.Page
Private WithEvents browser As WebBrowser
Dim th As New Threading.Thread(AddressOf ThreadStart)
Sub ThreadStart()
browser = New WebBrowser
AddHandler browser.DocumentCompleted, AddressOf browser_DocumentCompleted
browser.Navigate("http://www.someurl.com/")
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
th.SetApartmentState(Threading.ApartmentState.STA)
th.Start()
th.Join()
End Sub
Private Sub browser_DocumentCompleted(ByVal sender As Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs)
If browser.Document IsNot Nothing Then
Dim textbox As HtmlElement = browser.Document.GetElementById("txt1")
textbox.InnerText = "some text"
Dim button As HtmlElement = browser.Document.GetElementById("btn1")
button.InvokeMember("click")
End If
End Sub
End Class
the problem is that the webbrowser's DocumentCompleted event is not being handled. It looks like the page request finishes before anything else could happen.
what's the solution to this problem?
I really recommend reading this article(He won a price for it..)
Using the WebBrowser Control in ASP.NET
http://www.codeproject.com/KB/aspnet/WebBrowser.aspx
His solution is to create 3 threads for it to work..
I'm not sure but I have some concerns about the way you wrote your code.
You are creating and initializing your thread as soon as your class instance is created. This is before the form has been loaded.
I can't say for sure this couldn't work but I would definitely recommend creating the thread in your Load event handler, just before you use it.
I wrote some similar code in C# to generate a website thumbnail. Although that code does not use the DocumentCompleted event, I played with that event when I wrote it and it seemed to work okay. You can compare my code to yours.
Also, I should mention I have one hosting account where the code doesn't work. It seems to simply die when I call Thread.Join. However, it doesn't appear that's the issue you're running into.
Partial Class ClientCenter_UpdateSub
Inherits System.Web.UI.Page
Structure PInfo
Dim Name As String
Dim Surname As String
End Structure
Dim OldPInfo As New PInfo
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
'blah blah
OldPInfo.Name = Dt.Rows(0).Item("Name").ToString
OldPInfo.Surname = Dt.Rows(0).Item("Surname").ToString
end if
end sub
End Class
The first time the page loads my structrure is filled correctly.
After an AJAX postback all the structure fields are setting to nothing. (It seems that the Dim OldPInfo As New PInfo is called again), but i should better ask the SO Experts.
So anyway, what am i doing wrong here?
First off, You should never assign a variable outside of a property or a method.
Second, web applications are stateless (which means NOTHING is automatically saved from call to call - unless you store it somewhere like Viewstate, Session, etc.).
Remember to accept this answer if it helps solve your problem.