Display custom ASP.NET error page without rewriting URL - javascript

Currently working on error pages for my website in ASP.NET. I'm using a web configuration file to redirect the user to an error page if the server was unable to find the requested page. Below is the customErrors tag I used in my configuration file:
<customErrors mode="On" defaultRedirect="~/ErrorPages/Error.aspx">
<error statusCode="404" redirect="~/ErrorPages/Error.aspx"/>
</customErrors>
It's currently working but my problem is that I don't want the user to see my error page in the URL as displayed below:
/MySite/ErrorPages/Error.aspx?aspxerrorpath=/MySite/ImaginaryPage.aspx
I'm expecting something like what google has:
Google Error Page
Is there a way to do this without Javascript?

This article might help you out and here is a snippet from it:
http://blog.dmbcllc.com/aspnet-application_error-detecting-404s/
void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
if (ex is HttpException)
{
if (((HttpException)(ex)).GetHttpCode() == 404)
Server.Transfer("~/Error404.aspx");
}
}
Really the key part of this is if you want to maintain the same URL as what was requested, then Response.Redirect is NOT what you want as it goes back to the client to issue a second request thus changing the URL. You want to remain on the server so the appropriate call would be Server.Transfer. This particular event handler goes into your Global.asax.cs file and the method will get raised up for any 404s that are associated within the context of your application.
Unfortunately, it will skip past your customErrors configuration section and rely on a more programmatic approach however the code is fairly simple from a maintenance standpoint.

you can just add: redirectMode="ResponseRewrite"
like this
<customErrors defaultRedirect="Error404.aspx" mode="RemoteOnly"
redirectMode="ResponseRewrite" >
<error statusCode="404" redirect="Error404.aspx" />
</customErrors>

Related

Injecting JS into Literal and firing after page load

I have an ASPx/C# page that on clicking Save it will post back to the server. If the content within the controls already exists in the data stores which are checked it is supposed to pop-up an alert. The previous programmer used:
<asp:Literal ID="litError" runat="server" />
with the code behind ultimately sending:
litError.Text = "<script type='javascript'>alert('An error occured while processing this request. If the error persists, please contact the help desk.');</script>";
This JS alert is not popping up in spite of the debug reporting everything correctly processing through. I have scoured the internet, including here, for several days trying to find a resolution. I have tried many variations to get this to fire.
I'm suspecting that the script cannot fire on the AJAX because it is just not there during the Load stage of the life cycle, but would like some verification.
The script is in the btnSave_OnClick method. Unfortunately, due to the nature of the web application I cannot show more of the code, but the script should fire on exception of an item existing in either the app DB or if the user exists in our AD system already.
I was able to resolve my issue by completely removing the use of the ASP Literal control. I believe my first attempts at using this didn't have a properly formatted string, but it is now correctly functioning with the below code implemented in the code behind:
StringBuilder sbError = new StringBuilder();
sbError.Append("<script language='javascript' type='text/javascript'>alert('" + strError + "');</script>");
ScriptManager.RegisterStartupScript(this, this.GetType(), "sbError", sbError.ToString(), false);
Thanks to Zaigham and James for trying to help. I believe the reason the Literal control method did not work was because there was a ScriptManager control on the page(s) that were attempting to use that method.
I am not exactly sure why the script in literal is not working, but you can try this instead.
Your script text
string script = "<script>alert('Your alert message goes here');</script>";
Then use the method RegisterClientScriptBlock (in the same event where you previously set the error text) to inject the script to the page during the postback.
Page.ClientScript.RegisterClientScriptBlock(typeof(YOUR_PAGE_TYPE), "alert", script);
When the page is loaded back, you should see the alert popped up.
what I understand is; you want to run client script from code behind in the button click event (based on a condition). The best way to achieve this is to use ScriptManger class. Example:
Protected void btnSave_OnClick()
{
ScriptManager.RegisterStartupScript(btnSave, btnSave.GetType(), "myscript",
"alert('Your alert message goes here');", true);
}

C# Windows Forms App - send request by opening html

I made a simple html testpage. If the page is opened (http://localhost/cut/public/updateFile) then I send a timestamp to my webserver, where the value is written into a file date.txt e.g.:
4/8/2017 # 14:50:19
I also wrote a C# Windows Forms App which makes a request to the webserver to get the value of this file (date.txt), every X seconds.
My goal is to show the current time in a notification box every X seconds by reading it from the file on the server (for practice only)
However, before I get the file content, I need to update it first of course to get the current date and time.
Is it possible to solve this with the rules defined above?
This is my attempt:
private void timerA_Tick(object sender, EventArgs e)
{
sendWebRequest("http://localhost/cut/public/updateFile");
timerA.Stop();
timerA2.Interval = 5000;
timerA2.Start();
}
private void timerA2_tick(object sender, EventArgs e)
{
//Returns the content of date.txt
string response = sendWebRequest("http://localhost/cut/public/fileApi?action=read&targetFile=date");
//Show Notification
notifyIcon1.Visible = true;
notifyIcon1.Icon = SystemIcons.Exclamation;
notifyIcon1.BalloonTipTitle = "File content";
notifyIcon1.BalloonTipText = response;
notifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
notifyIcon1.ShowBalloonTip(10000);
timerA2.Stop();
timerA.Start();
}
/**
* Send request and get response as string
*/
public static string sendWebRequest(string URL)
{
WebRequest request = WebRequest.Create(URL);
WebResponse response = request.GetResponse();
StreamReader streamReader = new StreamReader(response.GetResponseStream());
return (string)streamReader.ReadToEnd();
}
However I always get 4/8/2017 # 14:50:19 it does not update as It should.
It obviously does not work this way, since WebRequest.Create does only gets the html file as it is and delivers it back to my C# Application, but it does not execute the javascript where I make the request to the server.
I only created this example above to ask if it is somehow possible to achive this at this way or if C# is not designed to solve problems like this?
My only idea is to create a hidden webbrowser in my Form1 and open http://localhost/cut/public/updateFile to start the update but I am not sure if this even works.
I created a webbrowser element and call the update URL like this:
webBrowser1.Navigate("http://localhost/cut/public/updateFile");
However, there are plenty of script error messages, which are found in the jquery file.
And my script won't work either because of the not working jquery.
So I guess it would work, but not with jquery, or I have to fix all errors in the jQuery file.
How to solve this problem?
You should open http://localhost/cut/public/updateFile from a real browser, which will execute the javascript on the page. Requesting this page from a windows form application with a WebRequest will just return the contents of the page, but will not process or execute the javascript on the page because it is not rendered or processed.
I solved it by adding a webbrowser element to my Form, and calling the URL inside of it like this:
webBrowser1.Navigate("http://localhost/cut/public/updateFile");
However, I had to rewrote my javascript to make it work without jQuery, since the C# Webbrowser appears to be an extremly old Internet Explorer with no support for nothing. There were plenty alerts pointing to script errors like the one below:
Now it works as expected. I hope someday somebody will come across with a much better solution than this though.
UPDATE
I was able to change the browser to the latest available by adding this line to my html head section:
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<!-- IE=edge instructs the WebBrowser control to use the latest version of IE it supports -->

C#: .NET based webbrowser doesn't show image

I am new in C# language and I have been trying to automate a website using .NET based webbrowser for ONLY personal use in Visual Studio 2015.
I have done document parsing, used Timer, used DocumentCompleted event properly to wait for the webpage to load completely and then parse the content, tried to make async events to behave like sync events (in order to load HTML content generated by clicking a link in a fully loaded webpage), etc to go through the phases in webpage automation: login -> get trains between stations -> click the Book now link -> go to the next page and fill in the passenger details.
Everything works fine but I am now stuck at the last phase, i.e., "go to the next page and fill in the passenger details" has a captcha image that must be resolved to go to the payment page. Don't get me wrong because I am not trying to get this captcha resolved automatically. The problem here is that I do not see the captch image which turned to be loaded only when this javascript call is invoked $(document).ready.
I thought my project has some buggy code which is stopping to load the captcha and therefore, I created a very basic new project, only added below code and navigated through different phases myself to see if the captcha really loads but unfortunately it would not load.
namespace TestWebBrowser
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
webBrowser1.Navigate("https://www.irctc.co.in/eticketing/loginHome.jsf");
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
}
}
}
Please see below. The highlighted part is where I am expecting a captcha.
I must tell you that I am not a web designer and therefore I only understand very basic of how websites work.
I went through several questions on this forum and nothing helped me.
Internet explorer is also using .NET browser from behind but while using IE, I can see the captcha is getting loaded. So, why is this javascript call $(document).ready is not getting invoked in .NET browser. Please see below:
I have later tried to use CefSharp in a fresh new project and I can see the captcha is getting loaded in its chromium based webbrowser. But I have done so much coding with .NET based webbrowser already and therefore I want to stick to the latter at this moment in order to get this resolved.
Is this happening because .NET webbrowser is using some very old IE version configurations?
Please help me to understand.
UPDATE 1: Adding the javascript
<script type="text/javascript">
$(document).ready(function(){
var isJsBlocked=0;
if (typeof(nlpLoadCaptchaAsync) == 'function'){
nlpLoadCaptchaAsync();
}else{
isJsBlocked=1;
}
setTimeout(function(){
var isNLPCaptcha = document.getElementById('nlpIdentifier');
if(isNLPCaptcha == null || isNLPCaptcha=='' ) {
var nlptrack = new Image();
nlptrack.src="http://irctclive.nlpcaptcha.in/temp_redirect_count/irctc_timeout.php?ref=f2c5d744485b0b4251461454db791111&isJsBlocked="+isJsBlocked+"&dynamicParameter="+Date.now();
nlpCaptchaTimeOut(true);
}
}, 5000 );
});
</script>
The answer shared here: Use latest version of Internet Explorer in the webbrowser control solved my issue.
I basically had to change the version of IE version used by my webbrowser control.
Thanks to Matthias herrmann

Understanding the error: WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'

I have a web form project that I started in VS2010 and I have recently upgraded to VS2013.
However I am now getting the above error. Searching the web the solution states to add the following key in my web.config file.
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
However why am I getting this error in the first place?
I have several pages that work, but it wasn't until I added my Login.aspx file did I start to get this error.
Am I getting this error because this particular page is using ASP validators?
What I don't like is when I add the above web.config key I get a javascript error:
JavaScript critical error at line 3, column 1 in http://localhost:11111/Scripts/jquery-2.2.1.js\n\nSCRIPT1002: Syntax error
If I continue on past the error the page does function correctly.
If I can better understand this error maybe it would be more beneficial for me to address this particular page instead of just turning off stuff in the web.config.
Comments on this post I found in the wild:
Coding Fusion link
Suggest that you can register your jquery script properly in Web Forms by adding this to your page load codebehind:
ScriptManager.ScriptResourceMapping.AddDefinition("jquery", new ScriptResourceDefinition { Path = "~/scripts/...", DebugPath = "~/scripts/..." });"
This may be preferable to turning off settings in your web config.

Origin null is not allowed by Access-Control-Allow-Origin.:1 in android web view?

I am getting this error :
XMLHttpRequest cannot load http://192.168.1.33:8080/ws/target. Origin null is not allowed by Access-Control-Allow-Origin.:1
When i am trying to load a html page on webview .I enter the script tag like that.
<script src="http://192.168.1.33:8080/target/target-script-min.js#anonymous"></script>
Actually This error coming when I am trying to debug my code on weinre . can you please tell how to remove this error ?
is there way to remove this error ?
But when I make phonegap project and load same HTML with same import script line.
<script src="http://192.168.1.33:8080/target/target-script-min.js#anonymous"></script>
with this line
I am able to debug my file on winre.
can you please tell how i will remove this error when I load on webview ?
The issue is occurring because of the CORS policy in your browser. In order to remove the error you normally have to make a change server side to whatever server you happen to be using. You'll have to add the header:
Access-Control-Allow-Origin: *
See here for more info on how to do this for specific back-end framework.
That said since your using cordova you can also override the browser's behavior like so:
if (Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) {
wv.getSettings().setAllowUniversalAccessFromFileURLs(true);
}
if you are using a webview. If you don't want to mess with the webview directly you can also set
<access uri="*" subdomains="true" />
In your res/xml/cordova.xml. See here for more details http://docs.phonegap.com/en/1.9.0/guide_whitelist_index.md.html

Categories