ASP.NET DLL instances conflict - asp.net

I am new to asp.net and i am trying to solve a problem.
I have created a simple aspx page (asp web site) that references a vb.net class.
I am handling one class instance using the session context object (don't know if there is a better way).
The class has a sub that sets a string value and a function that returns it.
I compile and run the web site project and then set the value "1" from one aspx page and the value "2" from another page (i open a second tab or browser by copying-paste the url from the first page) and then retrieve the values, both pages will show "2".
The same class in a vb.net form application (.exe) works just fine when the exe instances are running, the first returns the value "1" and the second the value "2". This is how i want it to work in my web site project, different pages different dll instances.
Class:
Public Class Class1
Private sExten As String
Public Sub setExten(value As String)
sExten = value
End Sub
Public Function getExten() As String
Return sExten
End Function
End Class
aspx:
Partial Class _Default
Inherits System.Web.UI.Page
'trying to ensure one instance is running
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Session.Add("ClassLibrary1", New ClassLibrary1.Class1)
End If
End Sub
'txtSetValue.text contains value "1" or "2"
Protected Sub btnSet_Click(sender As Object, e As EventArgs) Handles btnSet.Click
CType(Session.Item("ClassLibrary1"), ClassLibrary1.Class1).setExten(txtSetValue.text)
End Sub
'the txtShowValue shows "1" in the first and "2" in the second page
Protected Sub BtnGet_Click(sender As Object, e As EventArgs) Handles BtnGet.Click
txtShowValue.Text = CType(Session.Item("ClassLibrary1"), ClassLibrary1.Class1).getExten()
End Sub
End Class

Both pages are sharing the same Session.Item("ClassLibrary1"). You can try to store the value in a hidden field, or a invisible label.

Related

EnableViewState causing loss of value

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.

how to access webpage control in a class

I took a div id="DivErr" runat="server"
This is my Web Page written a class within
Public Class ReceiptInv Inherits System.Web.UI.Page
Partial Class MyTimer
Private Sub New()
End Sub
Public Shared timer As New Timer(5000)
' Enable the timer to run
Public Shared Sub StartRuning()
AddHandler timer.Elapsed, AddressOf timer_Elapsed
timer.Start()
End Sub
' This method will be called every 5 seconds
Private Shared Sub timer_Elapsed(ByVal sender As Object, ByVal e As ElapsedEventArgs)
Dim TMR As New ReceiptInv
TMR.DivErr.Visible = False
End Sub
End Class
End Class
I want to make this DivErr visible false in every 5 seconds.
But error in line
TMR.DivErr.Visible = False
NullReferenceException Unhandled By Usercode
Object reference not set to an instance of an Object
Can anyone tell what i am doing wrong ?? Thanks in Advance..
You need to get a real instance of the page, then you can access the controls and properties of it. Since your method is Shared you cannot access controls of the current page's instance (easily).
But you can try to get the page-instance via HttpContext.CurrentHandler.
Private Shared Sub timer_Elapsed(ByVal sender As Object, ByVal e As ElapsedEventArgs)
Dim page = TryCast(HttpContext.CurrentHandler, ReceiptInv)
If page IsNot Nothing Then
page.DivErr.Visible = False
End If
End Sub
However, why does the method need to be shared at all? A Shared timer is shared by all requests!
Apart from that i suspect that you're trying to make a control visible/invisible every 5th second. That won't work this way since you're using a server timer. You could use an ASP.NET-Ajax-Timer instead: http://msdn.microsoft.com/en-us/library/bb386404(v=vs.100).aspx

How to persist an object in webform

As I'm self taught my VB coding is not bad but my use of OOP is poor. I'm sure this can be done but I have not found out how yet.
I am building a webforms app which needs to grab data about a user from AD. I have a Person Class which I can use as follows
Public Class _Default
Inherits System.Web.UI.Page
Dim LoggedOnPerson As Person 'Added here so available throughout class
Private strLoggedOnUser As String
Private strADDomain As String
Private strADUserID As String
Public Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
strLoggedOnUser = Request.ServerVariables("LOGON_USER").ToUpper
strADDomain = strLoggedOnUser.Split("\")(0)
strADUserID = strLoggedOnUser.Split("\")(1)
If Not IsPostBack Then
'Dim LoggedOnPerson As Person *** changed to
LoggedOnPerson = New Person
'Get details from AD for logged on user
LoggedOnPerson.GetDetails(strADDomain, strADUserID)
'Store in Session
Session("LoggedOnUser") = LoggedOnUser
'This will now give me access to details such as
'LoggedOnPerson.EmailAddress
'LoggedOnPerson.GivenName
'LoggedOnPerson.TelephoneNo etc.
Else
'Postback so pull in details from Session
LoggedOnUser = Session("LoggedOnUser")
End If
End Sub
End Class
My problem is that I cannot access LoggedOnPerson in other events. e.g.
Public Sub SaveDetails()
Dim email As String = LoggedOnPerson.Email
'This now produces correct result. No error that LoggedOnPerson is not declared
End Sub
I of course get LoggedOnPerson is not declared error. How can I get around this.
You have created the object of "Person" inside Page_Load event. Take it outside and declare at the class level. Also add that object to view state/session state on Page_Load event and typecast it to "Person" class inside other events.

Scope of Page.Cache property in ASP.NET 4.0

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?

Help with refreshed ASP.NET page clearing public array

Hey all, i am new at everything VB.net/ASP.net so i need some help with a problem i am currently having.
I have an ASCX.vb page that lets the user choose someone from a table. Once they do select someone, the page reloads with that persons information into another table below that one where they can submit an order for that person or remove that person.
Problem being is that i wanted to store the users ID that are selected but it seems that everytime the page reloads to show an update, it dim's my array again back to default.
This is my code once they choose a user:
Namespace prog.Controls
Partial Public Class progReportGrid
etc....
Public strIDArray() As String = {"0000770000"} 'Just a dummy place holder
Private Sub gvData_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gvData.RowCommand
Dim idIndexNumber As Integer = Array.IndexOf(strIDArray, strID)
For i As Integer = 0 To strIDArray.Length - 1
System.Diagnostics.Debug.WriteLine(strIDArray(i))
Next
If idIndexNumber = -1 Then
ReDim Preserve strIDArray(strIDArray.Length)
strIDArray(strIDArray.Length) = strID
RaiseEvent EmployeeSelected(Me, New ESEventArgs(strID))
End If
End Sub
So everytime to page reloads the Public strIDArray() As String = {"0000770000"} gets called again and, of course, clears anything that was saved to it other than 0000770000.
How can i keep it from doing this?
UPDATE
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
'do what?
End If
End Sub
David
Perhaps you have a misunderstanding with the stateless model of a web application. Anything that is not stored in the ViewState or Session or a shared application variable will NOT persist through postbacks.
This means that when you declare your
Public strIDArray() As String
as a standard variable, it will be re initialized every time the page posts back.
For example, here's a simple flow of how this works:
The user opens their browser and opens up your aspx web page.
The request goes to your server, and all the controls including progReportGrid are instantiated as new instances and added to the page. (this is where your variable gets set to its original value every time)
A bunch of events are fired, including the Me.Load event
Controls that were added to the page are asked to generate their HTML
The HTML gathered from all the controls on the page is sent back to the user
So because your controls are all re-instantiated every post back, class variables like strIDArray are pretty much thrown out after the page is sent to the user.
Instead, if you want the page to remember what value the array had last postback and add more to it next postback, you have to use either ViewState, or Session.
For example:
Private Property StrIDArray() As String()
Get
If ViewState("StrIDArray") Is Nothing
ViewState("StrIDArray") = New String() {"0000770000"}
Return ViewState("StrIDArray")
End Get
Set(ByVal value As String())
ViewState("StrIDArray") = value
End Set
End Property
Now if you used this property instead of your variable, you could manipulate that array and as long as the user is on that page, the value of that array will persist across postbacks.
Use the Page.IsPostBack property in your Page_Load method.
This property is false for the first time the page loads and false for every postback afterwards.
If you set your default value strIDArray() = {"0000770000"} within If (Page.IsPostBack <> true) then it will not get reset on the postback.
EDIT : My VB syntax is VERY shaky but let me try it out
Partial Public Class EARNReportGrid
Begin
Public strIDArray() As String // DO NOT INITIALIZE it here. ONLY DECLARE IT
.....
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
//INITIALIZE the ARRAY
strIDArray = New String(){"00007700000"}
End If
End Sub
......
End

Resources