Add script block after workbook save in C# - c#

I have the below code which will create an aspose excel file to pop up. I need a script block to execute from the javascript immediately after the download happens. The registerstartupscript is not firing in the below code.
what is wrong in this?
workbook.Save(HttpContext.Current.Response, "Template.xls", ContentDisposition.Attachment, new XlsSaveOptions(SaveFormat.Excel97To2003));
Page.RegisterStartupScript("alert", "<script>parent.downloadcomplete()</script>");

Use an instance of ClientScriptManager.
workbook.Save(HttpContext.Current.Response, "Template.xls", ContentDisposition.Attachment, new XlsSaveOptions(SaveFormat.Excel97To2003));
// Page.RegisterStartupScript("alert", "<script>parent.downloadcomplete()</script>");
ClientScriptManager cScript = Page.ClientScript;
if (!cScript.IsStartupScriptRegistered(this.GetType(), "alert"))
{
// Register if not done already
string javascriptCode = "<script type='text/javascript'> alert('Download complete'); </script>";
cScript.RegisterStartupScript(this.GetType(), "alert", javascriptCode);
}

Related

C# Unable to login with WebBrowser

I am newbie to C#. I need help to be able to login the webpage and read some data.
After googling, I tried to find below code and other resources but in all cases, I can only get the html source of the login page but not other pages source data.
I need to traverse to the homepage first.
Then, I need to traverse
to "Port Status" and read some useful data. To inform data is stored in the
frames. How can I read data from the frames ?
Adding more info
1) view-source:http://192.168.0.239/homepage.html, which calls script as shown below
getSubTree('Management');
2) The above call hits the content in java script file (http://192.168.0.239/frame.js)
case "Management":
str += OneNodeLink("lv1", "Switch Information", "/iss/specific/sysInfo.html?Gambit="+GAMBIT);
str += OneNodeLink("lv1", "Port Status", "/iss/specific/port_settings.html?Gambit="+GAMBIT);
document.getElementById("treeFrame").innerHTML = str;
3) The above code executes this file "view-source:http://192.168.0.239/iss/specific/port_settings.html?Gambit=pisfgagehesfhjikojngqcabdfkjeeffmpkhfckm" and gets "Port Status"
My requirement is to read the "Port Status" received which is from the frames data. Hope I am able to make it clear. Let me know if you need more info to help.
Link has screenshots and html source files : https://www.dropbox.com/sh/oml3tk75tf1lu5c/AADuGtbZci3gnyOQ2AE8IYwua?dl=0
Thanks a lot in advance
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace WebBrowserWithoutAForm
{
class Program
{
private static bool completed = false;
private static WebBrowser wb;
[STAThread]
static void Main(string[] args)
{
wb = new WebBrowser();
wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);
string postData = string.Format("LoginPassword={0}&login=Login", "password");
ASCIIEncoding enc = new ASCIIEncoding();
wb.Navigate("http://192.168.0.239", "", enc.GetBytes(postData), "Content-Type: application/x-www-form-urlencoded\r\n");
//wb.Navigate("http://192.168.0.239");
while (!completed)
{
Application.DoEvents();
Thread.Sleep(100);
}
Console.Write("\n\nDone with it!\n\n");
Console.ReadLine();
}
static void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
//Console.WriteLine(wb.Document.Body.InnerHtml);
completed = true;
Thread.Sleep(1000);
//*******HERE I NEED TO TRAVERSE TO THE HOME PAGE AND GET ITS SOURCE ******
wb.Navigate("http://192.168.0.239/homepage.html");
Console.WriteLine(wb.DocumentText);
}
}
}
I suggest you use selenium - my sample code of using Selenium to login facebook
I'm not gonna code for you but you could copy some part of my code though.
For the login page, I would do a GetElementById on the input for the login, and then set the value attribute. Then for the login button, if it's actually a button, I would trigger the click() event, otherwise if it is a form, then I would do a submit.
For port Status, you would again need to know the html of the home page and do a GetElementById on it and then trigger a click() event.
To put some code to these words it would look something like this:
var portStatus = this.webBrowser1.Document.GetElementById("portStatus");
portStatus.InvokeMember("click");
//this should give you access to DOM of the first frame on the page.
//if you have more than 1 then you will need to know which one.
var frameDoc= this.webBrowser1.Document.Window.Frames[0].Document;
//or
var frameDoc= this.webBrowser1.Document.Window.Frames["iframeid"].Document;;
var login = this.webBrowser1.Document.GetElementById("Login");
login.SetAttribute("Value", "password");
var loginButton = this.webBrowser1.Document.GetElementById("LoginButton");
loginButton.InvokeMember("click");
//or if the login button is a form then submit the form
HtmlElement form = webBrowser1.Document.GetElementById("FormID");
if (form != null)
form.InvokeMember("submit");
Since you didn't provide the HTML of the homepage, The Id's used here would have to be replaced by the actual Ids of the page. And you would replace "password" with whatever your actual password is here.
I hope this helps, if you need some explanation let me know.
Also see this for working with frames

Alert show when extension of FileUpLoads are not allowed

I have a asp FileUpload control in my aspx page.
And the code behind to check file's extension and then insert them into database:
private string Write(HttpPostedFile file, string table)
{
string fileNameMain = Path.GetFileName(file.FileName);
// check for the valid file extension
string fileExtension = Path.GetExtension(fileNameMain).ToLower();
if (fileExtension.Equals(".pdf") || fileExtension.Equals(".doc"))
{
...insert fileupload into database
}
else
{
LabelError.Text = "Extension of files are not allowed.";
return null;
}
}
With the code above, it checks the extension and then show the message "Extension of files are not allowed." in a LabelError if the fileupload is not allowed.
Now, I'm required to do the "check-extension" in the other way: at the moment the client click and choose FileUpload, an alert show "Extension of files are not allowed.".
I need a way to make an alert show at the momment the FileUpload choosed in browser. Help!!!!
Hi but if you want an Alert (JavaScript) but first you need an postback action to execute code vb and the alert for example you could use a button to execute this method. You can show alert with this code
string script = "alert('Extension of files are not allowed');";
ScriptManager.RegisterStartupScript(this, typeof(Page), "alert", script , true);

SSRS report won't launch if multiple parameters in URL

I am trying to pass parameters to my SSRS report from an .NET application.
I have 3 parameters to pass: instanceID, EL and OL.
In my code-behind, I have codes as below:
string params = Session["instanceID"].ToString() + "&EL=unhide&OL=unhide";
string script = "<SCRIPT LANGUAGE='JavaScript'> ";
script += "OpenLink1(" + params + ");";
script += "</SCRIPT>";
Page.RegisterStartupScript("ClientScript", script);
My javascript code is as below:
function OpenLink1(params ) {
var str = "http://server/ReportServer/Pages/ReportViewer.aspx?%2f<path>%2f<report name>%2<report name>&rs:Command=Render&instanceID=" + params;
window.open(str, "List", "scrollbars=yes,resizable=yes,width=800,height=600");
return false;
}
No matter what I do, the report just won't launch (pop up).
The EL and OL parameters are supposed to hide tables in the SSRS report.
e.g. =IIF(Parameters!EL.Value = "hide", false, true)
If I remove these 2 parameters from the report and take away the parameter in the URL in code behind, the SSRS report launches without any problems.
What confuses me is that if I directly enter the URL in the browser, the report works fine - which lead me to believe that something to do with my coding and passing the parameters is wrong?
Any ideas?!
The issue is in the javascript that you're generating in your code behind. You need to put single quotes around the params variable when you're creating your function call in the generated javascript.
script += "OpenLink1('" + params + "');";

message script does't show in asp.net webpage

Am using the below code to display the message details. Its work in all pages and it doesn't work in some places. The below script does't work when am using calendar render event.Please help me to fix this error..
My partial code is here:
finally
{
if (message != "")
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "temp", "<script language='javascript'>alert('List : \\n" + message + "');</script>", false);
}
}
i think its may be because of no value in you 'message' variable. please try once by commenting the 'if' block/condition.

Getting the new filename of a file saved with ajax AsyncFileUpload?

I'm saving a file with the asyncfileupload ajax plugin from the ajax toolkit and when I save it I'm changing the filename (to avoid multiple files with the same name).
After the file is uploaded, the user needs to know what the file has been named so I'm using this javascript code on the onclientuploadcomplete event.
function UploadComplete(sender, args) {
alert(args.get_fileName());
}
This works except it gets the old name, not the new name (which is determined server-side). Is there any way to get it to return the new name rather than the old name? Or any work around to achieve this?
This is my code in the code behind the get the new filename:
string filename = DateTime.Now.ToString("dMyHmsf") + e.filename;
string strPath = MapPath("~/SavedImages/") + filename;
AsyncFileUpload1.SaveAs(strPath);
I got the answer from http://forums.asp.net/post/4139037.aspx It works for me...
copied code from there:
<asp:ToolkitScriptManager runat="server">
</asp:ToolkitScriptManager>
<!--This script snippet must be located below the ScriptManager-->
<script type="text/javascript">
Sys.Extended.UI.AsyncFileUpload.prototype.newFileName = null; //I did not use this line
function uploadcomplete(sender, e) {
alert(sender.newFileName);
}
</script>
<asp:AsyncFileUpload ID="AsyncFileUpload1" OnClientUploadComplete="uploadcomplete"
runat="server" OnUploadedComplete="AsyncFileUpload1_UploadedComplete1" />
the code behind:
protected void AsyncFileUpload1_UploadedComplete1(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this,
this.GetType(), "newfile",
"window.parent.$find('" + AsyncFileUpload1.ClientID + "').newFileName='newfile.jpg';", true);
}
How about writing the filename to a hiddenfield in the codebehind and the reading that value in your clientside code?

Categories

Resources