Executing a Javascript function from Global.asax - asp.net

I am attempting to call a javascript function on a particular page from my global.asax file, as demonstrated below. I have read in other forums that this is possible using the method below. However, I am struggling to get this to work. I am not receiving any errors in the console, however the function is simply not executing. The function does work as expected and can be called from the page on which it is created without any issues. Any assistance would be greatly appreciated.
Sub Application_AcquireRequestState(ByVal sender As Object, ByVal e As EventArgs)
Try
Dim currentPage = HttpContext.Current.Request.Url.ToString()
If Not currentPage.ToLower().Contains("Online/default.aspx") Then
If HttpContext.Current.Session("UserID") Is Nothing Then
Dim MyPage As System.Web.UI.Page
MyPage = HttpContext.Current.Handler
MyPage.ClientScript.RegisterClientScriptBlock(MyPage.GetType(), "MyScriptKey", "function f(){closeWin(); Sys.Application.remove_load(f);}Sys.Application.add_load(f);", True)
Session.Abandon()
Response.Redirect("~/")
End If
End If
Catch ex As Exception
End Try
End Sub

Related

Calling RegisterAsyncTask on an async method

I posted a previous problem (asp.net UpdatePanel with UserControls and Page Level Async Method), and think I have narrowed down my issue to a separate question.
I have an asp.net page, which needs to call an async method from a library.
I load the page as follows:
Private _dlgt As AsyncTaskDelegate
Protected Delegate Sub AsyncTaskDelegate()
Protected Sub Page_Load(ByVal sender As Object, ByVal e As
Dim LoadTask As New PageAsyncTask(AddressOf OnBegin, AddressOf OnEnd, AddressOf OnTimeout, "AsyncTask1", True)
Page.RegisterAsyncTask(LoadTask)
End Sub
Public Function OnBegin(ByVal sender As Object, ByVal e As EventArgs, ByVal cb As AsyncCallback, ByVal extraData As Object) As IAsyncResult
_dlgt = New AsyncTaskDelegate(AddressOf Update)
Dim result As IAsyncResult = _dlgt.BeginInvoke(cb, extraData)
Return result
End Function
Private Async Function Update() As Task
Dim AController As New CIP_WS.ARFController
Dim ARFTask As Task(Of CIP_WS.ARF) = AController.GetARFWithResultsAsync(Client.ClientID, PRN, Nothing, StartTime, EndTime, CIP_WS.LabResultController.InequalityModes.AsIs)
ARF = Await ARFTask
PrintResults()
End Function
The problem (I think), is that I have to set the page attribute to async=true, as I need to await a task. However (according to MS), if i set the attribute to true, the whole page will be processed asynchronously. If set to false, "the thread that executes the page will be blocked until all asynchronous tasks are complete". The latter is what I need, as it is loading and displaying the page, before the data (i.e before the update async method returns), and I am only getting placeholders.
To be clear, the Update method never completes. The Page_Load always complete without await the method to finish.
I feel so close, but far on getting this to work now. Any help, much appreciated.
EDIT____
Firstly thanks for the responses so far.
I have tried the following code previously and it 90% works, but thanks for the suggestion.
Dim LoadTask As New PageAsyncTask(AddressOf Update)
Page.RegisterAsyncTask(LoadTask)
It is probably my own fault, but I have been trying to keep the problem simple, but it is bigger than this.
The code above only 90% works, because it loads the data async fine, and then the page renders and loads as expected. However, I have some dynamic user-controls, which also load fine initially, but do not behave correctly during postbacks. In this case, when a user click a button, it does not change the visibility of a panel within the specific user-control. I have fully documented the issue on the link to another SO question above, but in short it works fine when I do not use async, but not when I have an async call during load.
I moved on to another part of the project , while I took a break from that problem, and started async-ing another part of the site. Again, I hit more dynamic user-controls, but this time the async call was in the load of the user-control rather than the page. I had exactly the same issue, except it was a drop down not persisting selections, rather than a panel visibility not persisting. I figured out I needed to call the asyn method in the following way
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim LoadTask As New PageAsyncTask(AddressOf OnBegin, AddressOf OnEnd, AddressOf OnTimeout, "AsyncTask1", True)
Dim LoadTask As New PageAsyncTask(AddressOf OnBegin, AddressOf OnEnd, AddressOf OnTimeout, "AsyncTask1", True)
Page.RegisterAsyncTask(LoadTask)
Page.ExecuteRegisteredAsyncTasks()
PrintGraph()
End If
End Sub
It was both manually passing true to force parallel processing, and calling ExecuteRegisteredAsyncTasks that fixed it for the cuser-ontrols and this page as a whole. It now works perfectly async. The only extra thing I did have to do, which effects other async calls in the project was add the following to the config:
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="false" />
The only bummer with this is, I have to call all PageAsyncTask using the fully overloaded method (onLoad,OnEnd,OnTimeOut,State,Parallel), rather than just passing the main method. I think due to having to handle the TimeOut manually after adding the key, but I am not sure.
Sooo... I then tried to take this knowledge to help with my original issue, and it is still not having it!
So I can either:
1) Use the following, load the data async, and load the page fine initially, but any postback reverts user-controls back to original state. This would also have a knock on effect to the other async issue I had, which meant all future async tasks needed to be registered as per item 2, so this would re-break that now working page.
Dim LoadTask As New PageAsyncTask(AddressOf Update)
Page.RegisterAsyncTask(LoadTask)
2) Use the following, which does not wait for the registered async method to complete (from what I can tell), so loads the webpage without essentially updating any controls. As per a comment, I accept there maybe something else wrong, that I have failed to do.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As
Dim LoadTask As New PageAsyncTask(AddressOf OnBegin, AddressOf OnEnd, AddressOf OnTimeout, "AsyncTask1", True)
Page.RegisterAsyncTask(LoadTask)
End Sub
I can make this work to the same extent as item 1, if I don't use the IAsyncResult approach as per MS docs, and just call the method for OnBegin, but this still has the same issue as 1.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As
Dim LoadTask As New PageAsyncTask(AddressOf Update, AddressOf OnEnd, AddressOf OnTimeout, "AsyncTask1", True)
Page.RegisterAsyncTask(LoadTask)
End Sub
it should be noted I can use the IAsyncResult approach successfully in the other page scenario where the user-control is calling the async load method.
Private _dlgt As AsyncTaskDelegate
Protected Delegate Sub AsyncTaskDelegate()
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim LoadTask As New PageAsyncTask(AddressOf OnBegin, AddressOf OnEnd, AddressOf OnTimeout, "AsyncTask1", True)
Page.RegisterAsyncTask(LoadTask)
Page.ExecuteRegisteredAsyncTasks()
PrintGraph()
End sub
Public Function OnBegin(ByVal sender As Object, ByVal e As EventArgs, ByVal cb As AsyncCallback, ByVal extraData As Object) As IAsyncResult
_dlgt = New AsyncTaskDelegate(AddressOf ReLoadSelectors)
Dim result As IAsyncResult = _dlgt.BeginInvoke(cb, extraData)
Return result
End Function
`3) Load the data synchronous, and everything just works again, including the user-controls persisting their values, but just dead slow.
I am going out of my mind with this one. Works fine sync for everything, just not async. Manged to get it to work on one page, where the user-control needs to do the async load call, but cannot make it work on another page, where the page has to do the async load call. One type of task registration waits for the async data method to return, but the fully overloaded version using IAsyncResult does not.
Please if anyone can spot where I have gone wrong, and put me out of my misery, I would be so grateful.
Yes, you need to set Page.Async to true in order to use RegisterAsyncTask. All the registered tasks are guaranteed to finish before page prerender event.
what's the definition of AsyncTaskDelegate? Why not use PageAsyncTask.ctor(Func handler) ? Something like below.
Dim LoadTask As New PageAsyncTask(AddressOf Update)
Page.RegisterAsyncTask(LoadTask)

page refresh detection code not working

I found a nice article on how to detect page refresh in this article: Detecting browser 'Refresh' from Code behind in C#, I tried to follow the code and use it in a web form application written in vb.net.
My problem is that when I refresh the page using the browser refresh button, the boolean IsPageRefresh, always remains false. So the code that I am trying to prevent from executing on page refresh, keeps getting executed.
Here is an example if my vb.net code including the converted code from the article:
Dim IsPageRefresh As Boolean = False
Protected Sub Account_reset_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
ViewState("ViewStateId") = System.Guid.NewGuid().ToString()
Session("SessionId") = ViewState("ViewStateId").ToString()
Else
If ViewState("ViewStateId").ToString() <> Session("SessionId").ToString() Then
IsPageRefresh = True
End If
Session("SessionId") = System.Guid.NewGuid().ToString()
ViewState("ViewStateId") = Session("SessionId").ToString()
End If
End Sub
Protected Sub Account_reset_LoadComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LoadComplete
If (Not Page.IsPostBack) Then
If Not IsPageRefresh Then
If Not String.IsNullOrEmpty(Request("key")) Then
If Not (Customer.SignInByResetKey(Request("key"))) Then
Customer.Messages.Add("Invalid password reset key", MessageType.Error)
FormsAuthentication.SignOut()
Functions.Redirect(SiteLink.ResetPassword)
Else
' Do Nothing
End If
Else
Functions.Redirect(SiteLink.ResetPassword)
End If
Else
'Do Nothing
End If
End If
End Sub
I would like to ask for help to try to identify where I possibly am making the mistake, or if there is a better method.
I saw many articles that show how to catch page refresh in code behind, but they use the PreRender method, and I cannot implement that solution due to how to website was built.
I hope I can get some positive feedback.
Many thanks.

Only IE10 returning Invalid Postback

I swear I have a love hate relationship with Microsoft. This is being thrown only in IE 10.
Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/>
Now,
On the #page I have ValidateRequest = "False"
In the Web.config I have httpRuntime requestValidationMode="2.0"
I am NOT using any Ajax or have a ScriptManager
I am checking for PostBack
Removed combobox code but it does use AutoPostBack
Here is my code
Private Sub Page_Init(sender As Object, e As EventArgs) Handles Me.Init
Try
Dim User As New UserRole(Me.SiteID, Master.UserName)
If User.GetLevel(Permissions.Edit) >= Levels.Page Then
Exit Sub
End If
Catch ex As Exception
End Try
Response.Redirect("/Manage/Errors/Unauthorized.aspx")
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Me.IsPostBack = True Then
Exit Sub
End If
Try
Dim Item As New PageBase(Me.PageID)
Me.txtCode.Text = Item.Code
Catch ex As Exception
Master.ShowError("Flex encountered a problem reading this page.")
End Try
End Sub
Private Sub cmbSnippet_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbSnippet.SelectedIndexChanged
If Me.cmbSnippet.SelectedIndex = 0 Then
Exit Sub
End If
Try
Dim Filename As String = String.Format("/Manage/Editors/Text/Scripts/{0}", Me.cmbSnippet.SelectedValue)
Me.txtCode.Text = My.Computer.FileSystem.ReadAllText(Server.MapPath(Filename))
Exit Sub
Catch ex As Exception
End Try
Master.ShowError("Flex encountered a problem reading the snippet.")
End Sub
Private Sub btnOk_Click(sender As Object, e As EventArgs) Handles btnOk.Click
Try
Dim Item As New PageBase(Me.PageID)
Item.Code = Me.txtCode.Text
If Item.Update = True Then
Me.ShowUpdateTime()
Exit Sub
End If
Catch ex As Exception
End Try
Master.ShowError("Flex encountered a problem modifying this page.")
End Sub
Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
Response.Redirect(String.Format("/Manage/Preview.aspx?PageID={0}", Me.PageID))
End Sub
This may or may not solve the issue.
.NET 4 and earlier don't know what IE 10 is. It's not in the list of browsers .NET knows about, so .NET assumes the browser is something that can't handle...well, anything really. Javascript and cookies, and I suspect more, get screwed over. So:
Download this: http://www.hanselman.com/blog/content/binary/App_BrowsersUpdate.zip, which is taken from here:
http://www.hanselman.com/blog/BugAndFixASPNETFailsToDetectIE10CausingDoPostBackIsUndefinedJavaScriptErrorOrMaintainFF5ScrollbarPosition.aspx,
which is referenced from here: IE10 User-Agent causes ASP.Net to not send back Set-Cookie (IE10 not setting cookies)
Extract the files and put them in your application's App_Browser directory. Rebuild and see if that works.

Web Controls Not Talking to Each other in ASP.NET using VB.NET

I have an asp.net page that loads two controls, Control A and Control B. Control A has some generic form submit and clear buttons that trigger click events in its' own code behind which use reflection to call the update function in Control B which has a few input fields. I have debugged this and everything seems to be in order, however; when the update function in control B is called the input fields are not returning a value when using inputname.text or me.inputname.text. Does anyone have any ideas why this is not working? Any guidance would be appreciated.
This is the code in Control A's codebehind which calls the update method in Control B's code behind
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click
Try
Dim lctlControl = Session("SelectedQstnCtl")
Dim methodObj = lctlControl.GetType().GetMethod("UpdateGenInfo", BindingFlags.NonPublic Or BindingFlags.Instance)
' Execute UpdateGenInfo method to update the data
methodObj.Invoke(lctlControl, Nothing)
Catch ex As Exception
'TODO: check for concurrency error here
End Try
End Sub
This is the update function in Control B that is being called. The session values are being passed, but the form fields are not.
Protected Sub UpdateGenInfo()
Dim lclUtil As New clUtility
Dim genInfo As New clGenInfo
Try
Dim dt As Integer
'Update Data for 1-2
dt = genInfo.UpdateGenInfo_E1_01_02(Session("ConnStrEP"), Me.varLastUpdate, Session("AppNo"), Session("RevNo"), _
Me.txtPrName.Text, Me.txtPrAddr1.Text, Me.txtPrAddr2.Text, _
Me.txtPrCity.Text, Me.txtPrState.Text, Me.txtPrZip.Text)
Catch ex As Exception
'Display error
lclUtil.DisplayMsg(Me.lblErrMsg, String.Format("Error Location: Sub LoadGenInfo (ctlE1_01_02) {0}", ex.Message))
End Try
End Sub
The most likely cause is that the control instance stored in the session is not the control instance on the current page. For example, if you're storing the control instance in the session when the page is first loaded, and retrieving it on post-back, it will be a different instance.
If you can't give Control A a direct reference to Control B, then change your code to store the reference in the Page.Items collection:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Page.Items("SelectedQstnCtl") = TheSelectedQstnCtl
End Sub
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click
Dim lctlControl = DirectCast(Page.Items("SelectedQstnCtl"), YourControlClass)
lctlControl.UpdateGenInfo()
End Sub
I see you are using reflection which might be an overkill for that task.Try referencing the method in the control directly.Make then method UpdateGenInfo public and then reference it like this.
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click
Try
Dim lctlControl = CType(Session("SelectedQstnCtl"),YourControlClass)
lctlControl.UpdateGenInfo()
Catch ex As Exception
End Sub
Public Function UpdateGenInfo()
'your code here
Catch ex As Exception
End Try
End Function
This way you can easily trace where your values are getting lost.Let me know how it goes.
Try yet another simple approach working demo here
In control a
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim testb1 = CType(Me.NamingContainer.FindControl("testb1"), testb)
testb1.UpdateGenInfo()
End Sub
In control b
Public Function UpdateGenInfo()
Try
Dim a = Me.TextBox1.Text
Catch ex As Exception
End Try
End Function
Aspx Parent Page
<uc1:testa ID="testa1" runat="server" />
<uc2:testb ID="testb1" runat="server" />
The controls in testb are in an update panel.Try this and let me know if this works.

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.

Resources