Lost HttpContext in a custom event - asp.net

I'm getting the 'Response is not available in this context error' calling the following function:
Private Sub ReloadPage(ByVal inNumber As Integer) Handles tempaux.Advertise
'Response.Redirect("tope.aspx?dep=" & CStr(inNumber))
Response.Write("<script>window.open('tope.aspx?dep= & CStr(inNumber)','topFrame');</script>")
End Sub
I've changed the line adding the System.Web.HttpContext.Current before Response.Write and I get 'Object reference not set to an instance of an object'.
To give some background: tope.aspx is, as you can see, opened in topframe. As soon as it loads it starts a CustomTimer object I've defined:
Public Class tope
Inherits System.Web.UI.Page
Public funciones As funciones = New funciones
Dim WithEvents tempaux As CustomTimer = Global.objCustomTimer
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim inUserProfile As Int64
Try
tempaux.StartTimer()
Catch ex As Exception
'bla bla
End Try
As you can see I've declared the CustomTimer in the Global.asax. The CustomTimer object raises an Advertise event every 5 seconds and passes 'inNumber' as a parameter for the tope.aspx page to refresh some label, a simple thing. CustomTimer is a class I made to manage the timer, it doesn't inherits any other class( For what I've learned in my search it has to inherit some httpthing but I'm not sure). I'm guessing that at some point the httpcontext is being lost (I've searched in google and I couldn't figure its lifecycle or whatever information that tells me why it 'dies). Can anyone help me to find out what is the problem?
thanks

Your timer exists outside of the tope page class, so it is possible that the timer event is firing after the response from the page is complete and there is no longer a HttpContext.Current instance.
It sounds like what you are trying to do is to change an advertising banner on a page every 5 seconds, once the page is loaded. You need to do that using a javascript timer, which would fire every 5 seconds and make a request back to your web server for a new advertisement.

Related

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

using control states in server control

I have a server control that I am trying to get to save properties as control states but for some reason the properties are not persisting across partial postbacks.
The psuedo code is as follows:
Public Class FileUpload
Inherits ScriptControl
Implements INamingContainer, IPostBackEventHandler
Public Property newFileExt() As String
Get
Dim foundList As String = DirectCast(ViewState(Me.UniqueID & "_fileExt"), String)
If foundList IsNot Nothing Then
Return foundList
Else
Return String.Empty
End If
End Get
Set(ByVal value As String)
ViewState(Me.UniqueID & "_fileExt") = value
End Set
End Property
Protected Overrides Sub OnInit(ByVal e As System.EventArgs)
MyBase.OnInit(e)
Page.RegisterRequiresControlState(Me)
End Sub
Protected Overrides Function SaveControlState() As Object
Dim controlState(6) As Object
controlState(0) = MyBase.SaveControlState()
controlState(1) = newFileExt
Return controlState
End Function
Protected Overrides Sub LoadControlState(ByVal savedState As Object)
Dim controlState() As Object
controlState = CType(savedState, Object)
MyBase.LoadControlState(controlState(0))
newFileExt = CType(controlState(1), String)
End Sub
end class
On this control is an asyncFileUpload ajaxcontroltoolkit control and a button. I have an event for upload complete:
Protected Sub SaveUploadedFile(ByVal sender As Object, ByVal e As AjaxControlToolkit.AsyncFileUploadEventArgs) Handles asyncFileUpload.UploadedComplete
newFileExt= "Some Value"
end sub
Protected Sub bntSelectResults_click(ByVal sender As Object, ByVal e As EventArgs) Handles bntSelectResults.Click
If (newFileExt= "") Then
'this always returns as empty
End If
end sub
So, UploadedComplete is complete it should set the controls state. then, when the user click the button it should read it. Through debugging, I can see that it is set correctly in UploadedComplete event but null when read. Is this due to the cycle of the page or something?
Thanks
jason
EDIT
I traced out the path for how the page cycle is running:
User clicks the async file upload control's browse button and selects a file. This causes the upload process to start
a. OnInit gets called
b. LoadControlState gets called
c. OnLoad gets called
d. asyncFileUpload.UploadedComplete gets called and I set the newFileExt property
here.
e. SaveControlState gets called. newFileExt is set here properly
User clicks a button on the control that initiates another partial postback/update of the update panel
a. OnInit gets called
b. LoadControlState gets called. I can see that the newFileExt property is not set
c. OnLoad gets called
d. Buttons click event gets called and the property is read (which is no longer set)
e. SaveControlState gets called and cycle ends
So, as best as I can tell, the asyncFileUpload application has issues with ViewStates/ControlStates. I ended up just just using sessions.

problem using winforms WebBrowser in asp.net

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.

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

ASP.NET BasePage Class Page_Load not Fired on Postback

I have the following BasePage class...
Public Class BasePage
Inherits System.Web.UI.Page
Private litError As Literal
Protected SO As Session
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
SO = Session.Item("SO")
If SO Is Nothing Then
Session.Abandon()
Response.Redirect("~/timeout.htm")
End If
litError = Page.FindControl("litError")
If litError IsNot Nothing Then
litError.Visible = False
End If
End Sub
Protected Sub ShowMessage(ByVal Message As String)
Show(Message, "message")
End Sub
Protected Sub ShowError(ByVal Message As String)
Show(Message, "error message")
End Sub
Protected Sub ShowSuccess(ByVal Message As String)
Show(Message, "success message")
End Sub
Private Sub Show(ByVal Message As String, ByVal CssClass As String)
If litError IsNot Nothing Then
litError.Text = String.Format("<span class=""{0}"">{1}</span>", CssClass, HttpUtility.HtmlEncode(Message))
litError.Visible = True
End If
End Sub
End Class
Every page in this application inherits this class. The SO variable represents a custom session class, that is very simple and just holds a couple of basic settings to be used throughout the application. The problem is, my Page_Load in this base class does not fire if a natural postback occurs (in this case, it is a gridview postback by sorting/paging). Then later in my code when I reference SO, I get a null reference exception because it hasn't been pulled from session.
Why doesn't the base Page_Load fire?
Try moving your code into the Page_Init event.
Microsoft has some info on each event in the lifecycle http://msdn.microsoft.com/en-us/library/ms178472.aspx. This MSDN page tells you what types of things you should handle in each event.
You might want to think about implementing SO as a property, where the Get does (not sure if this is correct VB...)
Dim so As Session = Session.Item("SO")
If so Is Nothing Then
Session.Abandon()
Response.Redirect("~/timeout.htm")
End If
return so
It could be that something else is happening in the Init events that is causing it to fail. So rather than it not being called it just hasn't been called yet.
It could be that the autoevent wireup isn't wiring it up correctly, tend to override the OnInit event and attach the events manually myself, I have also read somewhere that this improves perfomance by not requiring the framework to do heaps of reflection on every post.
But back to your problem... try making the SO object private and create a property accessor for it that first checks that if the private is set, if not set it, before returning the private variable. If it isn't set and can't be found then it can abort the same way you are doing in the Load. This means that to load the variable you won't be dependent on the Page_Load from firing and thus the SO object should be available for you during the init routines, if you need it.

Resources