Good Day Every one here is my code
if (type.Contains("Loan Date"))
{
prenda.LoanMonth = year.ToString() + "/" + month.ToString();
string a = servs.CheckLM(prenda);
if (Convert.ToInt32 (a) != 0)
{
Page.ClientScript.RegisterStartupScript(Page.GetType(), "key", "myFunction();", true);
//create a popup if yes process if no exit
//if yes
prenda.LoanMonth = year.ToString() + "/" + month.ToString();
servs.DeletePrendaLM(prenda);
foreach (DataRow row1 in table.Rows)
{
prenda.Bcode = row1["Bcode"].ToString();
prenda.Jprincipal = Convert.ToDecimal(row1["JPrincipal"].ToString());
prenda.Aprincipal = Convert.ToDecimal(row1["APrincipal"].ToString());
prenda.Cprincipal = Convert.ToDecimal(row1["CPrincipal"].ToString());
prenda.LoanMonth = year.ToString() + "/" + month.ToString();
user.UserID = Session["UserID"].ToString();
servs.UploadPrendaLM(prenda, user);
}
}
the porblem is that the Page.ClientScript.RegisterStartupScript(Page.GetType(), "key", "myFunction();", true); doesnt execute as soon as the process pass over it, it executes myFunction() after finishing the button click proceses, i cant create a if clause below it because it finishes first all of the process before i can use the myFunction() i need that process first before continuing the proceses below //
so can you help me find a work around?
Few things that might help
The script block added by the RegisterStartupScript method executes when the page finishes loading but before the page's OnLoad event is raised. >> Where are you adding script in the page (Which event?) try it in OnInit or init complete events.
You can check whether script added or not through IsStartupScriptRegistered method (Page.ClientScript namespace)
Related
I have a database of URLs and the screen will load 9 URLs at once like a table and load another 9 URLs after 5 minutes. I have some script to run after each ULR finished loading using the FrameLoadEnd Event Handler. I keep getting this error when the 19th URL is loading.
unable to execute javascript at this time, scripts can only be executed within a v8context. use the iwebbrowser.canexecutejavascriptinmainframe property to guard against this exception
If there is a mistake, this error should pop up when the 1st URL is loaded but it always pops up when the 19th URL is loaded which is the third round the screen display 9 new URLs.
Here is the Code
wb.FrameLoadEnd += OnBrowserFrameLoadEnd;
private async void OnBrowserFrameLoadEnd(object sender, FrameLoadEndEventArgs e)
{
ChromiumWebBrowser wb = (ChromiumWebBrowser)sender;
await wb.EvaluateScriptAsync("document.body.style.overflow='hidden';");
int clientHeight = 0;
int clientWidth = 0;
int innerHeight = 0;
int innerWidth = 0;
string clientRecHeightScript = #"function myFunction() {" +
"var rect = document.body.getBoundingClientRect();" +
"ch = rect.height;" +
"var rect = document.body.getBoundingClientRect();" +
"cw = rect.width;" +
"var ih = window.innerHeight;" +
"var iw = window.innerWidth;" +
"const webLength = [ch, cw, ih, iw];" +
"return webLength;" +
"}" +
"myFunction();";
await wb.EvaluateScriptAsync(clientRecHeightScript).ContinueWith(x => //Error occurs here
{
var response = x.Result;
if (response.Result != null)
{
var clientRec = response.Result;
string[] arr = ((System.Collections.IEnumerable)clientRec).Cast<object>()
.Select(y => y.ToString())
.ToArray();
Int32.TryParse(arr[0], out clientHeight);
Int32.TryParse(arr[1], out clientWidth);
Int32.TryParse(arr[2], out innerHeight);
Int32.TryParse(arr[3], out innerWidth);
}
});
}
Is there any error I might have done to cause this error?
Does the webpage have JavaScript on it? If not then it won't have a V8Context.
It's also possible the V8Context hasn't finished loading for the main frame. FrameLoadEnd is called once per frame. Sub frames may finish loading first.
The website failed to load, you can check the http://cefsharp.github.io/api/91.1.x/html/P_CefSharp_FrameLoadEndEventArgs_HttpStatusCode.htm
A navigation has occurred and the V8Context has been freed . If Load is called or the html document navigates internally you the frame for which FrameLoadEnd was called may no longer have a valid V8Context.
You can evaluate JavaScript directly against the frame to avoid the check. The FrameLoadEndEventArgs.Frame property can be used to access the frame. You can then directly call IFrame.EvaluateScriptAsync
Using the code below, I want to compare the UserType, if it is "Student" I want to redirect to student profile, etc.
But it always gets to the last else statement and Writes an Error.
The returnQuery method works well because it returns the value "Student".
String emailID = Session["New"].ToString();
string usertype = returnQuery(
"select userType from Registration where email = '" + lblEmail.Text + "'");
if (usertype.Contains("Student"))
{
Response.Redirect("Profile.aspx?email=" + emailID.ToString());
}
else if (usertype.Contains("Company"))
{
Response.Redirect("CompanyProfile.aspx?email=" + emailID.ToString());
}
else if(usertype.Contains("Admin"))
{
Response.Redirect("AdminProfile.aspx?email=" + emailID.ToString());
}
else
Response.Write("Error");
If usertype="Student" you can use usertype.Equals("Student"); to determine the variable.
Here is the method.
I suspect that you are dealing with a Page Lifecycle issue. lblEmail.Text is likely not what you expect it to be during Postback Event Handling time of the button click.
Verify that you are not modifying the contents of lblEmail.Text at any point before the button click event is processed, and verify the value of lblEmail.Text at the time the click event is processed.
For more information about Page Lifecycle, see this MSDN article:
https://msdn.microsoft.com/en-us/library/ms178472%28v=vs.100%29.aspx
public void PortalLogin()
{
string portalUrl = "URL";
string portalEmail = "email";
string portalPassword = "password";
// Run when page finishes navigating
webBrowser2.DocumentCompleted += (s, e) =>
{
HtmlElement head = webBrowser2.Document.GetElementsByTagName("head")[0];
HtmlElement testScript = webBrowser2.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)testScript.DomElement;
element.text = "function PortalLogin() { document.getElementById('username').value = '" + portalEmail + "'; document.getElementById('password').value = '" + portalPassword + "'; document.getElementById('credentials').submit(); }";
head.AppendChild(testScript);
webBrowser2.Document.InvokeScript("PortalLogin");
};
// Navigate to the portal
webBrowser2.Navigate(portalUrl);
while (this.webBrowser2.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
Thread.Sleep(100);
}
}
I have the code segment above that is supposed to Navigate to a specific URL and then upon Navigate's completion, execute invoke a script to login to the webpage there. Now, because the entire PortalLogin() function is inside of a while loop, I have to include the:
while (this.webBrowser2.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
Thread.Sleep(100);
}
segment so that the while loop doesn't just interrupt the Navigate function a ton. However, the code isn't quite working, the flow seems to be off when I step through it with breakpoints. I think part of the problem is I don't quite understand how the while loop testing ReadState != Complete works. Could someone enlighten me?
Better use WebClient with cookies or HttpWebRequest and HttpWebResponse.
I have the following code in C#:
if (function.Equals("Larger50"))
{
Request req = new Request();
string result = req.doRequest("function=" + function + "&num=" + number, "http://localhost:4000/Handler.ashx");
if (result.Equals("True") || result.Equals("true"))
{
Page.ClientScript.RegisterStartupScript(Page.GetType(), null, "window.open('http://localhost:4000/Larger.aspx?num=" + number + "', '_newtab')", true);
}
if(result.Equals("False") || result.Equals("false"))
{
Page.ClientScript.RegisterStartupScript(Page.GetType(), null, "window.open('http://localhost:4000/Smaller.aspx', '_newtab')", true);
}
if(result.Equals("Error") || result.Equals("error"))
{
Page.ClientScript.RegisterStartupScript(Page.GetType(), null, "window.open('http://localhost:4000/ErrorPage.htm', '_newtab')", true);
}
Session["result"] = result;
Page.ClientScript.RegisterStartupScript(Page.GetType(), null, "window.location.href = 'Results.aspx'", true);
}
The result variable can have any one of three values (if the server responds):
i) true
ii) false
iii) error
The main problem with this code is that the new tab script in each of the three if statements work as they should. However, the last script which opens the Results.aspx page is not executing for some reason or another. The script is written well as it executed perfectly if all the other code is commented out. How should I solve the problem?
I tried replacing it with Response.Redirect("Results.aspx") however then this exeuctes and all the other three scripts never execute.
You should register these all at once, rather than in two separate statements:
if (function.Equals("Larger50"))
{
Request req = new Request();
string result = req.doRequest("function=" + function + "&num=" + number, "http://localhost:4000/Handler.ashx");
string scriptVal = "";
if (result.Equals("True") || result.Equals("true"))
{
scriptVal = "window.open('http://localhost:4000/Larger.aspx?num=" + number + "', '_newtab');";
}
if(result.Equals("False") || result.Equals("false"))
{
scriptVal = "window.open('http://localhost:4000/Smaller.aspx', '_newtab');";
}
if(result.Equals("Error") || result.Equals("error"))
{
scriptVal = "window.open('http://localhost:4000/ErrorPage.htm', '_newtab');";
}
Session["result"] = result;
scriptVal += "window.location.href = 'Results.aspx';";
Page.ClientScript.RegisterStartupScript(Page.GetType(), null, scriptVal, true);
}
See the docs on ClientScriptManager.RegisterStartupScript, specifically:
A startup script is uniquely identified by its key and its type.
Scripts with the same key and type are considered duplicates. Only one
script with a given type and key pair can be registered with the page.
Attempting to register a script that is already registered does not
create a duplicate of the script.
In your case, the type and key are the same in both of the scripts you register.
You could uniquely identify them with a key, and then register them separately. But you have to keep in mind that the order of execution is not guaranteed:
The script blocks are not guaranteed to be output in the order they
are registered.
Can somebody look at the below code and tell me what I am doing wrong.
for(i=0;i<=Request.Files.Count;i++)
{
int percentComplete = (int)Math.Ceiling((double)(i + 1) / (double)Request.Files.Count * 100);
string message = string.Format("{0} of {1} uploaded", i + 1, Request.Files.Count);
ScriptManager.RegisterStartupScript(this, this.GetType(), "progress", #"do_progress("+message+","+percentComplete+");", true);
}
I am trying to update the client with each pass of the loop. On the client (inside of the form tags) I have a function called "do_progress" that takes two parameters: message and percent. My intention is that the client-side method fires with each pass of the loop but nothing happens.
UPDATE
Thanks for your help. Ramiz, your code won't work in my case because it collects all the methods (and progress) inside the loop and then sends them to the client at the same time.
This won't show progress accurately (each loop represents the completion of an uploaded file). I need to be accessing the client function, do_progress, after each unique completion of the server-side loop.
Also, the page has already loaded and the code is fired when a (upload) button is clicked.
Having said that, I am still having problems. I can confirm that I am getting the results I want with the below code by looking at 'selection source':
int percentComplete = (int)Math.Ceiling((double)(i + 1) / (double)Request.Files.Count * 100);
string message = string.Format("{0} of {1} uploaded", i + 1, Request.Files.Count);
ScriptManager.RegisterStartupScript(this, this.GetType(), "progress" + i, #"do_progress('" + message + "','" + percentComplete + "');", true);
But, I am not seeing the results update in real-time on the client. The progress bar isn't moving and the counter (n of n files) isn't doing anything. But, when I look at the innerHTML, the values have updated. Very odd. It is almost like I need to be refreshing the page or something but that should't be necessary.
The client side function I am using, which is placed in the form tags at the end of the page, looks like this:
function do_progress(message,percent)
{
try {
$('progress_status').innerHTML = message;
$('progress_bar').attr("style", percent + "px");
}catch(e){alert(e.message)};
}
message is a string value it should be enclosed in single quote "do_progress('"+message+"',"+percentComplete+");"
percentComplete contains integer so it doesn't require to enclose in single quote as message does.
string methods = string.empty;
for(i=0;i<=Request.Files.Count;i++)
{
int percentComplete = (int)Math.Ceiling((double)(i + 1) / (double)Request.Files.Count * 100);
string message = string.Format("{0} of {1} uploaded", i + 1, Request.Files.Count);
methods += "do_progress('"+message+"','"+percentComplete+"');"
}
Secondly, here, I'm incrementing all methods in a string variable and calling it in window.onload event just make sure the DOM is ready before we call the do_progress function.
ScriptManager.RegisterStartupScript(this, this.GetType(), "progress", #"window.onload = function() {"+ methods +"}", true);
However, this should not require here, call in window.onload as ScriptManager.RegisterStartupScript will call them when DOM gets ready.
I'm not sure what exactly issue at your end but this is my instant review.
try to use this.RegisterStartupScript instead of ScriptManager.RegisterStartupScript
Your client side do_progress function appears to have an error in the jQuery selectors - you're currently looking for elements named progress_status and progress_bar when I suspect you intend to be looking for classes or IDs. If your selector doesn't match anything it doesn't raise any kind of error, it just doesn't do anything.