Message After Redirecting VB.Net - asp.net

I redirect the user to the same page but I would like for a popup message stating the error. I cannot use messagebox because it does not work in the app. I tried Response.Write did not work. I have put a label with the error message but I do not know how to make it appear when the page reloads because of the error.
Could I use page_load, and IsPostBack? If so, how can I tell that it is reloading because of the catch error? Or if you know a better way...
Idea I have when error happens about the page_load:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
//This could be in IsPostBack if needed.
If (the catch error happen) then
Show Label next to the button.
EndIf
If Page.IsPostBack Then
End If
My code to redirect the user when error happens:
ElseIf e.CommandName = "Remove" Then
Try
Dim dto As PDto = MyPage.DelegateP.GetPDtoByPrimaryKey(Me.OPId)
If dto.Id > 0 Then
dto.LUser = MyPage.LUser
MyPage.DelegateP.DeletePDto(dto)
End If
Me.PanelOtherPForm.Style("display") = "none"
Me.FormViewDetails.Style("display") = "none"
Me.CurrentOPId = 0
Me.Repeater1.DataBind()
BubbleOPChanged()
Catch ex As Exception
Response.Redirect(String.Format("/Default.aspx?i={0}&c={1}", MyPage.DtoPage.PageID, Me.CId))
End Try

You could attach an error code to the URL as a parameter when you redirect.
Then on page load, check if the parameter is there and deal with it as you see fit.

Yes, MsgBox won't work when you publish your app to the server but you can make a pop up message with client side script. In this example, I force an error to happen and show you the error message in a pop up message that should run fine on your server.
Try
'Force an error to happen for testing
Dim test As Integer
test = "test"
Catch ex As Exception
Dim errorText As String
errorText = Replace(ex.Message, """", "") 'Script will error if we don't replace double quotes
errorText = Replace(errorText, "'", "") 'Replace single quotes, too
ClientScript.RegisterStartupScript(Me.[GetType](), "testAlert", "alert('" + errorText + "');", True)
End Try

Related

variable not being set with value from querystring

I'm trying to pass a GUID variable via the query string. When I run my game, I can see the needed variable in the querystring when it hits the page(planetID):
http://ec2.us-east-2.compute.amazonaws.com/World_Generation/GeneratePlanet.aspx?planetID=3b757g83-f211-1236-a52c-226fw9a9f9d5
However, when I try to display that variable, I get this error in my browser console window(Chrome):
Uncaught ReferenceError: planetID is not defined
Here is my code. You can see that I am declaring the variable 'planetID' and setting it from the query string value:
Partial Public Class PlanetGallery
Page.Header.DataBind()
Public planetID As String = ""
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not String.IsNullOrEmpty(Request.QueryString("planetID")) Then planetID = Request.QueryString("planetID")
ScriptManager.RegisterStartupScript(Page, Me.Page.GetType, "test", "alert('planetID from PlanetGallery_PageLoad Sub' + planetID);", True)
End Sub
End Class
I'm not sure why it's not working. I think I need another pair of eyes.
If anyone has any suggestions, I'd love to hear them!
Thanks!
Since you're getting the error at browser console, you should change your code like this:
ScriptManager.RegisterStartupScript(Page, Me.Page.GetType,
"test", "alert('planetID from PlanetGallery_PageLoad Sub" + planetID + "');", True)
The problem is because javascript cannot access to codebehind variables.
Your javascript is registered like this:
<script>
alert("planetID from PlanetGallery_PageLoad Sub " + planetID);
</script>
So planetID becomes a variables this way.

Trouble using response.redirect

Hi and sorry for my poor english.
I have an Asp.net + Vb.Net application and here is an example of code illustrating my problem :
First I have Default.aspx page with 2 buttons, "Valid" and "Redirect"
Protected Sub butvalid_Click(sender As Object, e As EventArgs) Handles butvalid.Click
If (File.Exists(Server.MapPath("log.txt"))) Then
Dim lines() As String = IO.File.ReadAllLines(Server.MapPath("log.txt"))
Dim tmp As Integer = Convert.ToInt32(lines(lines.Length - 1))
tmp = tmp + 1
File.AppendAllText(Server.MapPath("log.txt"), Environment.NewLine & tmp.ToString)
Else
File.WriteAllText(Server.MapPath("log.txt"), "1")
End If
End Sub
Protected Sub Redirect_Click(sender As Object, e As EventArgs) Handles Redirect.Click
Response.Redirect("accueil.aspx")
End Sub
Valid button write into a txt file and Redirect is redirecting ...
Here is the page_load code of accueil.aspx :
Threading.Thread.Sleep(3000)
Response.Redirect("default.aspx")
The problem is when I click on Redirect button in Default.aspx page, the valid button remains accessible and user can click on Valid button.
How can I disable Valid button after Redirect click ?
Thanks in advance.
Place this in Page_OnLoad handler and fire at each postback to make sure it is bound. This will disable the button on the client side, and when the page load fires again after the click is and response to the server is done, the button will be enabled again.
Redirect.Attributes.Add("onclick", "javascript:"
+ butvalid.ClientID + ".disabled=true;"
+ Page.ClientScript.GetPostBackEventReference(Redirect, null));

LinkButton postbackurl Error in asp.net

I want to send a Message by clicking on a LinkButton through yahoo messenger in Asp.net. Some times It works and sometimes I get this errors: Windows can not access the spesified device, path or file. You may not have appropriate permission to access this item and also Error: Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server. The status code returned from the server was: 400 This is my code in VB, What is wrong with it?
Protected Sub LinkButton2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles LinkButton2.Click
Dim idname As String = "YMID"
Dim message As String = "Hello, This is my YM message"
Dim sendim As String = String.Format("ymsgr:SendIM?{0}&m={1}", idname, message)
LinkButton2.PostBackUrl = (sendim)
End Sub

Make asp.net webpage respond to WebClient request

I have run into a problem in my asp.net and vb.net programming. I have made a website which connects to a database to authenticate users. I have made another page which my windows form application uses to authenticate users so the program does not have to connect directly to the MySql Database as this is insecure.
So far, the code for my asp.net page is:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
If Request.QueryString.Keys(0) = "key" And Request.QueryString.Keys(1) = "getapikeyv1" And Request.QueryString.Keys(2) = "authapienc2" Then
Dim key As String = Request.QueryString.Get("key")
If key = "dua9r3rqpK{WPDWp9r93af03r8yqrEPIF{A}W~DW)D08q3raewdawdug9q8wdyaw9wq" Then
returnLabel.Text = "XYeJay4XVh6amvf1kJ34Y6y6hR0sSokP9oJFsi0Mxl4QB0T86W0iac9o2nRfCmFmsONq6sPz+rdX+/NqFk3inHRGnwnqf0IsQXE/M/SvnvY="
Else
returnLabel.Text = "invk"
End If
Else
returnLabel.Text = "invalidrequest"
End If
End If
End Sub
The default value for 'returnLabel' is INVALIDREQUEST. My api keys defined above are working fine so are not needed to be considered here. However, when I use the following code to communicate with the webpage, it always returns with returnLabel's value as 'INVALIDREQUEST'. Even if I put the returnLabel.Text = "1233" at the beginning of the Me.Load sub, the page still returns INVALIDREQUEST when I communicate with it through my program!
I use this code to request:
Try
Dim APIRequest As New WebClient
APIRequest.QueryString.Add("key", r9j0wqfha0fh0wf0.DecryptString128Bit(APIKey5, dVadaihwdq93ra0w0))
APIRequest.QueryString.Add("getapikeyv1", "")
APIRequest.QueryString.Add("authapienc2", "")
Dim ako39rqwfa As String = APIRequest.DownloadString(EncryptionPageUrl)
MsgBox(ako39rqwfa)
Dim m As Match = Regex.Match(ako39rqwfa, "<span id=""returnLabel"">.*?</span>")
APIKey00 = m.Value.Replace("<span id=""returnLabel"">", "").Replace("</span>", "")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
As you can see, the WebClient I use is fine but the Me.Load sub in the webpage is not responding the request made by the program...
Is there any way I can make the webpage respond to the WebClient.DownloadString() function?
Thanks,
Rodit
(ps. c# or vb code would be appreciated)
Change your asp.net page to check the query string like this, not sure if you can assume they are in a certain order:
If Request.QueryString.Get("key") isnot nothing And
Request.QueryString.Get("getapikeyv1") isnot nothing And
Request.QueryString.Get("authapienc2") isnot nothing Then

Server.Transfer("error_404.aspx") in Application_Error returns a blank page

I look for HttpExceptions in the Application_Error sub of my global.asx
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
Dim ex As Exception = HttpContext.Current.Server.GetLastError()
If ex IsNot Nothing Then
If TypeOf (ex) Is HttpUnhandledException Then
If ex.InnerException Is Nothing Then
Server.Transfer("error.aspx", False)
End If
ex = ex.InnerException
End If
If TypeOf (ex) Is HttpException Then
Dim httpCode As Integer = CType(ex, HttpException).GetHttpCode()
If httpCode = 404 Then
Server.ClearError()
Server.Transfer("error_404.aspx", False)
End If
End If
End If
End Sub
I can step through this code and confirm it does hit the Server.Transfer("error_404.aspx"), as well as the Page_Load of error_404.aspx, but all it shows is a blank page.
Are you clearing the Response buffer? You have no clue what is already there, since you are doing this in the Application_Error catch-all. Server.Transfer just appends whatever the new page generates onto the existing Response. Obviously this could create some issues.
Does it work if you change the Server.Transfer to a Response.Redirect? (You may have to use the HTTPContext.Current prefix from where you are in global.asax.)
I'm not sure that a Server.Transfer is a good idea in the context of what you're doing, since you're effectively asking IIS to render the global.asax URL to the browser.
I think if some error occurs, Server.Transfer won't fire.
Server.Transfer is not a good method for this. Try with Response.Redirect. It should work.
If you have any exception is there any requirement for maintaining the states? If not, go with Response.Redirect.

Resources