Injecting JS into Literal and firing after page load - javascript

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);
}

Related

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

Display ReportViewer (ReportViewer1.ServerReport.ReportServerCredentials) in a separate, dragable window

I have an SSRS report displaying fine in my .aspx page, except that it needs to display in its own window. Now, I can form a url to the report server and open it easily like this, but it is not what I need to do in this case.
string url = "http://testserver/ReportServer/Pages/ReportViewer.aspx? %2fSQLReports%2fTestReport&rc:Parameters=Collapsed&ID=" + ID.ToString() + "";
string script = "window.open('" + url + "','')";
if (!ClientScript.IsClientScriptBlockRegistered("NewWindow"))
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "NewWindow", script, true);
}
What I need to do is from code-behind, open the way we are now forming the reportview on the aspx page having it's parameters passed along with it:
(ReportViewer1.ServerReport.ReportServerCredentials)
I have researched this for quite some time and cannot seem to find a definitive answer to a solution for this. I've tried the following:
ajaxToolkit:ModalPopupExtender (there is a way to make this
draggable but this breaks in IE10 due to a known bug). Patch is not
an option because these are on end-user client machines.
JavaScript popup
Server.Redirect or Transfer to a separate page, passing the parameter values along in session variables.
This is a report spanning several pages so on postback you will need to not reload the report.

Never Show Window On Page Launch

I am using C# and asp.net to launch a webpage that I am passing parameters to. That works well! I come from a Windows.Forms background so please forgive me if I am trying to achieve the impossible. What I would like is set the Visibility property of the program (either IE or chrome) to false so the user never sees that a webpage is being launched. I have been using this JS function to close the page, but it seems that the page must completely load before closing which sometimes can take a few seconds.
Does asp.net have the capability to achieve such? And this is my JS code I have been using
string close = #"<script type = 'text/javascript'>
window.returnValue = true;
window.close();
</script>";
base.Response.Write(close);
If you don't want the User to see the page, I assume you just want to post some information to the page. In that case, make an HTTP request via c# code, instead of opening the webpage up in a browser.
On the Project Properties page, Web tab, Start Action section, click the radio button for "Don't open a page. Wait for a request from an external application".

Add Script Reference (JavaScript) to Script Manager on Microsoft AJAX Partial Postback

I am trying to add a script reference to the script manager in the event of a Microsoft AJAX Partial Postback, ie a user clicks on a link in an Update Panel.
ScriptManager.RegisterClientScriptInclude(Page, Page.GetType(), "UniqueName",
Page.ResolveUrl(scriptPath));
Doesn't work and either does
ScriptReference script = new ScriptReference(scriptPath);
MyScriptManager.Scripts.Add(script);
From what I have read on the net, RegisterClientScriptInclude should work even in a partial postback.
http://www.codeproject.com/KB/ajax/addingCssJsAjaxPartialPos.aspx
Can anyone give any ideas why these don't work, or another way to do it?
EDIT: Additional information.
I am working with a very large legacy code base that has the forms and script manager in each page rather than in the master page. I would like to place the code into a class and use the following call to add the javascript effect.
ClientSideScripts.BackgroundColourFade(Page, ScriptManager, Control);
The reasons I want to include the script in the method call is
Consumes of the method don't have to remember to include the script
Changing the script used only requires a change in one place
Only include the javascript when needed to keep the load time of the page down
Have a look at this SO-Question because it answers your question:
ScriptManager.RegisterClientScriptInclude does not work in UpdatePanel
function dynamic() {
alert('dynamic');
$('#divDyn').text('Dynamic!');
}
// notify that the script has been loaded <-- new!
if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

Categories