window.focus() of JavaScript not working on IE9 - c#

This is my code
protected void LoginButton_Click(object sender, EventArgs e)
{
if (DAL.DAOKullanici.Login(KullaniciTextBox.Text,SifreTextBox.Text))
{
VeriyazPROTicari.Sessionlar.Variables.loginkontrol = true;
Session["kullaniciAdi"] = KullaniciTextBox.Text;
Session["kullaniciId"] = DAL.DAOKullanici.GetEntity(DAL.DAOKullanici.KullaniciAdiIleKullaniciIdCek(KullaniciTextBox.Text)).ID;
bool main_window_open = false;
if (!main_window_open)
{
Page.RegisterClientScriptBlock("Main_Window", "<script>" +
"var newwindow; " +
"newwindow = window.open('" + "/dashboard/dashboard.aspx" + "', 'main_app_window', ' toolbar=0,location=0,directories=0,status=1,menubar=0,left=1,top=1,scrollbars=" + "1" + ",resizable=1,width=" + "1280" + ",height=" + "800" + "'); " +
"if (window.focus) " +
"{newwindow.focus();} "
+ "</script>");
main_window_open = true;
}
HataLabel.Text = "";
}
else
{
HataLabel.Text="Hatalı Giriş";
}
}
I have no problem with it except the JavaScript part.
What I am trying to is after LoginButton is clicked opening dashboard.aspx and setting focus on it.And this code opens dashboard.aspx and sets focus in Google Chrome and Mozilla Firefox 4.However,when I try it on IE9 dashboard.aspx is opened but focus does not work and dashboard.aspx remains under the login page.
How can I set focus on a new window on IE9?

I have had a similar problem to this and it seemed to happen because in IE9 (and any IE) that the focus() method is run before the window is rendered.
To get round this there are two ways that I can see that will fix this:
Set a timer to load the focus after a small amount of time.
Defer the JavaScript from being read until the window is fully rendered.
The timer method to me is not my preferred choice as in my personal opinion it is messy and if the page takes longer to load than the timer you are stuck with the same problem. To implement the timer you could use something like:
Page.RegisterClientScriptBlock("Main_Window", "<script>" +
"setTimeout(function() { " +
"var newwindow; " +
"newwindow = window.open('" + "/dashboard/dashboard.aspx" + "', 'main_app_window', ' toolbar=0,location=0,directories=0,status=1,menubar=0,left=1,top=1,scrollbars=" + "1" + ",resizable=1,width=" + "1280" + ",height=" + "800" + "'); " +
"if (window.focus) " +
"{newwindow.focus();} " +
"}, 5);" +
"</script>");
I have set a delay of 5 seconds, which may be overkill.
The defer method is my preferred choice as I feel it is cleaner and simpler, but it may or may not work:
Page.RegisterClientScriptBlock("Main_Window", "<script type="text/javascript" defer="defer">" +
"var newwindow; " +
"newwindow = window.open('" + "/dashboard/dashboard.aspx" + "', 'main_app_window', ' toolbar=0,location=0,directories=0,status=1,menubar=0,left=1,top=1,scrollbars=" + "1" + ",resizable=1,width=" + "1280" + ",height=" + "800" + "'); " +
"if (window.focus) " +
"{newwindow.focus();} "
+ "</script>");

After what seemed like an eternity, my colleague figured out a way to make it work for us.
There are other references to the issue itself, http://social.msdn.microsoft.com/Forums/en-US/iewebdevelopment/thread/a250c431-9f09-441c-9b78-af067233ed78 http://support.microsoft.com/kb/979954
That said, we simply put the window.focus() in the body tag of the new (pop-up) page.
<body onload="FocusWindow()">
Defined FocusWindow() in a separate .js file as follows,
function FocusWindow() {
window.focus();
}

Related

File is created but information wont save in it

Ok, so I'm new to C# and don't know what I'm doing wrong.
At the top of the button click event I have this variable:
InformationDump infodump;
infodump = new InformationDump();
After that I have the rest of the code which is meant to path to the user desktop and save whatever is filled out in the textbox's into a separate window (part of the same program):
infodump.richTextBox1.Text = textBox1.Text + ", " + textBox2.Text + ", " + textBox3.Text + ", " + textBox4.Text + ", " + comboBox1.SelectedItem;
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string filename = path + "\\" + DateTime.Now.ToString("HH.mm.ss") + System.Environment.UserName + ".txt";
infodump.richTextBox1.SaveFile(filename, RichTextBoxStreamType.RichText);
Thanks in advance.
This is happening because you are creating an instance of the form (InformationDump) then try to use the RichTextBox instance but the form then will not go through the standard loading and initialization process therefore as I reproduced, the file will be created but will be empty.
It is very interesting, but if you do repeated save it works!
infodump.richTextBox1.SaveFile(filename, RichTextBoxStreamType.RichText);
// zero bytes
infodump.richTextBox1.SaveFile(filename, RichTextBoxStreamType.RichText);
// works!

Setting up width for Jquery modal pop up div from code behind c#

I am calling jQuery Modal Pop up with some dynamic information, How I can set width of modal popup div from my c# Code.
Here is my current call from c#
string jqmsg = " Dear Applicant,</br> <p>Your enquiry registered, The Email verification link has been sent to you registred Email ID " + txtEmail.Text + " and your registration reference ID is <Strong> " + Session["REGID"].ToString() + " </Strong></p>";
ClientScript.RegisterStartupScript(this.GetType(),"Popup", "ShowPopup('" + jqmsg + "');", true);
Thanks in advance.
I thought I would answer the comment I made above with an answer so I could more easily show code. This is what I mean:
c#
var width = 400;
string jqmsg = " Dear Applicant,</br> <p>Your enquiry registered, The Email verification link has been sent to you registred Email ID " + txtEmail.Text + " and your registration reference ID is <Strong> " + Session["REGID"].ToString() + " </Strong></p>";
ClientScript.RegisterStartupScript(this.GetType(),"Popup", "ShowPopup('" + jqmsg + "', " + width + ");", true);
javascript
function ShowPopup(message, width) {
// other ShowPopupCode
document.getElementById("modalDivId").style.width = width + 'px';
}
Would that work for you?

c# replace timestamp value string of text in textfield

i currently have a textbox field, everytime a change is made, i add who it was updated by and what time
right now it keep appending that text
how can i find the line that says "LastEdited: ", and only replace the time stamp value?
this is what i do now
maybe someone can post me example of code how to grab the timestamp and replace it?
if (txtMemberNotesOriginally != txtMemberNotesChanged) {
txtMemberNotes.AppendText("LastEdited: " + DateTime.Now.ToString() + " By: " + MyProgramName.Username + Environment.NewLine);
i am not an expert, so an example of code would bevery useful
i do use this textbox to save other notes as well (which i wouldn't wanna loose)
can i do this
foreach (var line in txtMemberNotes.Lines) {
if (line.StartsWith("Last Edited: "))
{
txtMemberNotes.Text = txtMemberNotes.Text.Replace(line, "Last Edited: " + DateTime.Now.ToString() + " By: " + MyProgramName.Username + Environment.NewLine);
}
else
{
txtMemberNotes.AppendText("Last Edited: " + DateTime.Now.ToString() + " By: " + MyProgramName.Username + Environment.NewLine);
}
}
The easiest way to solve your problem seems to stop appending text and just set the text value. No parsing is necessary, just overwrite the exiting values with your newer value.
if (txtMemberNotesOriginally != txtMemberNotesChanged) {
txtMemberNotes.Text = "LastEdited: " + DateTime.Now.ToString() + " By: " + MyProgramName.Username + Environment.NewLine;
I guess theres always Regex if you really wanted:
string s = #"Some notes here etc etc..
Last edited: 12/12/2012 12:00:00 AM";
Console.Write(Regex.Replace(s, #"Last edited: .*$", "Lasted edited: " + DateTime.Now.ToString()));
Or more specifically using your code:
txtMemberNotes.Text = Regex.Replace(txtMemberNotes.Text, #"Last edited: .*$", "Lasted edited: " + DateTime.Now.ToString());

How to know click (Ok or Cancel) event from print pop-up of web browser

In my application I am printing some data through a pop-up window. On loading the pop-up, the user will be prompted for to either print or cancel. I want to know which button is clicked (print or cancel) so that I can take some action based on the button clicked. The code and screenshot are given below.
public void Print(int Id)
{
StringBuilder sb = BadgeHelper.preparePrintableString(Id);
string printWindowFunc = "function printWindow() {\n" +
"var z = window.print();\n alert('Return: ' + z);\n" +
"checkDocumentState();\n" +
"}";
string checkDocumentStateFunc = "function checkDocumentState() {\n" +
"if (document.readyState == 'complete') {\n" +
"window.close();\n" +
"}\n" +
"else {\n alert('Else');\n" +
"setTimeout('checkDocumentState()', 2000);\n" +
"}\n"+
"}\n";
string startingHTMLCode = "<html>\n" +
"<head>\n" +
"<script type='text/javascript'>\n " +
checkDocumentStateFunc +
"\n" +
printWindowFunc +
"</script>\n " +
"</head>\n" +
"<body onload='printWindow();'>\n";
sb.Insert(0, startingHTMLCode);
sb.Append("\n</body>\n</html>");
Response.Write(sb.ToString());
}

WP7 Webbrowser InvokeScript errors

WebBrowser control's invoke script is always giving me errors. This html script is validated from http://validator.w3.org. I wrote the code such that on clicking "button1" webBrowser1 invokes the function "setCredentials". I am not sure why this is giving an error like
"An unknown error has occurred. Error: 80020006."
public TestInvokeScript()
{
InitializeComponent();
LoadHtml();
webBrowser1.IsScriptEnabled = true;
webBrowser1.NavigateToString(_html);
button1.Content = "Set Credentials";
}
private void LoadHtml()
{
_html = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"" +
" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" +
"<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">" +
"<head>" + "<meta name=\"generator\" content=\"HTML Tidy for Linux (vers 6 November 2007), see www.w3.org\" />" +
"<script type=\"text/javascript\">" +
"//<![CDATA[" +
" function setCredentials()" +
" {" +
" document.getElementById(\"email\").value = \"test#gmail.com\";" +
" }" +
"//]]>" +
"</script>" +
"<title></title>" +
"</head>" +
"<body>" +
"<form action=\"https://cloudmagic.com/k/login/send\" method=\"post\">" +
"<input id=\"email\" type=\"text\" value=\"\" /> " +
"<input id=\"password\" type=\"password\" />" +
" <button type=\"submit\" id=\"login_send\">Login</button>" +
" </form>" +
"</body>" +
"</html>";
}
private void button1_Click(object sender, RoutedEventArgs e)
{
var obj = webBrowser1.InvokeScript("setCredentials");
}
What is the mistake I am doing.?
A couple of possibilities:
1. Make sure you call it after PageLoaded or NavigateComplete fires.
2. Try this one:
Dispatcher.BeginInvoke(() =>
{
var result = webBrowser.InvokeScript("javascrpitMethod", param1, param2);
});
I was passing the html in string form. Unknowingly, I used a double slash(//)
and that commented the rest of the string since there are no newLine characters. It took me almost a day to figure this out. Remove the double slashes and CData tag.

Categories

Resources