Save current webpage in Watin - save

I'm trying to save the full content of the current static web page, using the code from Show IE "Save As" dialog using Watin
So here it is:
IE ie = new IE("http://localhost");
// more code
//I expect out.html is the output file
FileDownloadHandler fileDownloadHandler = new FileDownloadHandler("out.html");
//I expect this line to popup the save as dialog box, but nothing happens
ie.AddDialogHandler(fileDownloadHandler);
//the program is blocked at this line, as it can't click anywhere
ie.Link("startDownloadLinkId").Click();
fileDownloadHandler.WaitUntilFileDownloadDialogIsHandled(15);
fileDownloadHandler.WaitUntilDownloadCompleted(200);
I also tried the code below, but it doesn't save all the page:
System.IO.StreamWriter file = new System.IO.StreamWriter("output.html");
file.Write(ie.Html);
Again, I need to save the webpage from Watin, and the result to be the same as saving it manually.
Thanks!

Here is how I do it:
File.WriteAllText("myfile.html",
(myIE.InternetExplorer as SHDocVw.InternetExplorer).Document.documentElement.outerHtml);
Assumes myIE is a WatiN IE element, of course.
If you're ever having difficulty finding how to do something with WatiN, I often find it helpful to google how to do it with an "Internet Explorer COM object". WatiN wraps the object, but it is exposed and able to be accessed!
Cheers!

Try to parse the html with html agility pack and save it, there are additional abilities that you can use...
using HtmlAgilityPack;
var htmldoc = new HtmlDocument();
htmldoc.LoadHtml(ie.Html);
htmldoc.Save(stream);
Link to agility pack

Related

Printing from a Xamarin.Forms app

I'm all new to Xamarin and I'm currently working on a sample or a "prove of concept" app using Xamarin.Forms.
I'm supposed to perform a print task from this app though I'm not at this point sure what to print yet (the screen, content of a label, a file etc.).
Either way, what is the easiest way to print from a Xamarin.Forms app?
(current target is primarily Android 4.4+).
I hope this isn't too complicated :)
EDIT:
Ok let me just update this post as the original text might be a bit ambitious/vague.
I have a Xamarin.Forms project (+ an Android part) and I have some HTML available in the XF part of the project that I need to get into a WebView and print it.
From what I understand, the thing with the WebView has to be done on the Android part of the project due to the fact that this is where the printing will be handled.
I was hoping this could be done from code since I don't really need to display the WebView, just print it's content.
The Android part of the project has only the MainActivity and no layouts or XAML files.
I don't know where to add the WebView or how to access it (other than DependecyService seems to be a buzz word here) so I'm kinda stuck here.
I'm thinking that this task should be rather trivial to someone with a little more Xamarin experience than me.
Every platform XF supports has it's own mechanism for printing. XF does not provide any abstractions for printing in a cross-platform manner. You will need to write printing logic for each layer and expose it to XF using DependencyService (or some other DI engine).
Here is a good example, of course, using dependency service:
https://codemilltech.com/xamarin-forms-e-z-print/
I so wanted to do this but it was too hard. Finally built it into Forms9Patch - a MIT licensed open source project.
Verifying that Printing is available
Before printing, you should verify that printing is available on your device. To do so, call:
if (Forms9Patch.PrintService.CanPrint)
{
// do the printing here
}
Print the contents of a Xamarin.Forms.WebView
using Forms9Patch;
...
var myWebView = new Xamarin.Forms.WebView
myWebView.Source = new HtmlWebViewSource
{
Html = "some HTML text here"
};
...
myWebView.Print("my_print_job_name");
Note that your WebView does not have to be attached to a Layout. This allows you to Print without having to display the WebView in your app’s UI.
Printing an HTML string
using Forms9Patch;
...
var myHtmlString = #"
<!DOCTYPE html>
<html>
<body>
<h1>Convert to PNG</h1>
<p>This html will be converted to a PNG, PDF, or print.</p>
</body>
</html>
";
...
myHtmlString.Print("my_print_job_name");
PLEASE NOTE: iOS sometimes places the page breaks in weird places. I have a StackOverflow Bounty on why this happens and how to fix it.
Using EmbeddedResource as a source for a Xamarin.Forms.WebView
This is sort of an experimental feature I’ve built that I’ve found it useful. As such the documentation is sparse. It allow you to put HTML content in a folder in your app’s EmbeddedResources folder and then use it as a source for a WebView. A much nicer solution than using platform specific approach provided by Xamarin. It also supports putting all of the HTML content into a zip file. Please take a look at the source code to see how it works.
You can handle the printing of lists/ invoices .. with the xfinium pdf component from xamarin componentstore. With that you create your _pdffile and then call the following method which starts the adobereader from where you can select a printer (in my case google cloudprint)
public void printPdfToCloud(string _pdffile)
{
try
{
var saveto = System.IO.Path.Combine(Android.OS.Environment.ExternalStorageDirectory.ToString(), "YourApp/"+_pdffile);
string file_path = saveto;
if (System.IO.File.Exists(file_path))
{
Android.Net.Uri pdfFile = Android.Net.Uri.FromFile(new Java.IO.File(file_path));
Intent pdfIntent = new Intent(Intent.ActionView);
pdfIntent.SetPackage("com.adobe.reader");
pdfIntent.SetDataAndType(pdfFile, "application/pdf");
pdfIntent.SetFlags(ActivityFlags.NoHistory);
StartActivity(pdfIntent);
}else
{
// give a note that the file does not exist
}
}
catch (Exception E)
{
// Do some Error dialog
}
}

Linking a .doc file on a mvc view page

For something which seems so simple I can't find a solution, I have a word .doc file which I want to be linked on one of my pages so that a user can click on a link and open/download it (whichever is easier) and then read it on the machine with MS word.
Right now I have it in my content folder and tried to display it in both an and but no luck.
Is this an issue of IIS or just I'm going about this all wrong?
Present dir setup:-
Solution>Project>Content>File.doc
Solution>Project>Views>Home>NewRecord.cshtml
File location 1st followed by page I'm trying to display file on.
If I understand your problem correctly that you want to make User to Click and he/she will be promoted to download the .doc then.....
You can achieve with submit button which will be styled with CSS as LINK, then you perform the HTTP GET to the server within HTML form tag, Form will target the action on Server, which will return FileContentResult,
public FileContentResult GetWordDocument(string Id)
{
var contentDisposition = new ContentDisposition
{
FileName = "WordDoc.doc",
Inline = false;
};
FileContentResult documentResult= File(secureDoc.SecuredFileBytes,"application/msword", contentDisposition.FileName);
documentResult.ExecuteResult(this.ControllerContext);
return documentResult;
}
Content-Disposition:What are the differences between "inline" and "attachment"?
http://msdn.microsoft.com/en-us/library/system.web.mvc.filecontentresult(v=vs.108).aspx
Hope this will help to resolve.

"document" in mozilla extension js modules?

I am building Firefox extension, that creates single XMPP chat connection, that can be accessed from all tabs and windows, so I figured, that only way to to this, is to create connection in javascript module and include it on every browser window. Correct me if I am wrong...
EDIT: I am building traditional extension with xul overlays, not using sdk, and talking about those modules: https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules
So I copied Strophe.js into js module. Strophe.js uses code like this:
/*_Private_ function that creates a dummy XML DOM document to serve as
* an element and text node generator.
*/
[---]
if (document.implementation.createDocument === undefined) {
doc = this._getIEXmlDom();
doc.appendChild(doc.createElement('strophe'));
} else {
doc = document.implementation
.createDocument('jabber:client', 'strophe', null);
}
and later uses doc.createElement() to create xml(or html?) nodes.
All worked fine, but in module I got error "Error: ReferenceError: document is not defined".
How to get around this?
(Larger piece of exact code: http://pastebin.com/R64gYiKC )
Use the hiddenDOMwindow
Cu.import("resource://gre/modules/Services.jsm");
var doc = Services.appShell.hiddenDOMWindow.document;
It sounds like you might not be correctly attaching your content script to the worker page. Make sure that you're using something like tabs.attach() to attach one or more content scripts to the worker page (see documentation here).
Otherwise you may need to wait for the DOM to load, waiting for the entire page to load
window.onload = function ()
{
Javascript code goes here
}
Should take at least diagnose that issue (even if the above isn't the best method to use in production). But if I had to wager, I'd say that you're not attaching the content script.

Developing a Firefox plugin/addon that invokes "Save As" from FF's own set of functions

I have a basic FF addon that polls for something in the DOM of the page in window.document. When it sees it, it is supposed to save the page. That's the hard part. I don't want to replicate the functionality of "save complete" I just want to call the pre-existing functionality from the plugin/addon at the right moment.
Is this an XPCom thing? Or is it pure JavaScript via the relevant APIs ?
iMacros for Firefox can invoke Save-as (without popping the associated dialog), but I can't see how.
Can anyone advise as to how to call deeper Firefox functions like this?
Thanks, - Paul
PS - I really love Mozilla Archive Format, with MHT and Faithful Save but I think it is replicating functionality again. My alternative is to invoke it's function, but that's as opaque to me as the firefox native one.
You can use nsIWebBrowserPersist.saveDocument() for this:
var persist = Cc["#mozilla.org/embedding/browser/nsWebBrowserPersist;1"].
createInstance(Ci.nsIWebBrowserPersist);
var localPath = Cc["#mozilla.org/file/local;1"].
createInstance(Ci.nsILocalFile);
localPath.initWithPath(pathToLocalDirectory);
var localFile = localPath.clone();
localFile.append("mylocalfile.html");
persist.saveDocument(document, localFile, localPath, null, 0, 0);
The key is the third parameter which specifies where the linked URIs should be stored. See http://mxr.mozilla.org/mozilla2.0/source/embedding/components/webbrowserpersist/public/nsIWebBrowserPersist.idl#256 for complete documentation.

Use WatiN for automation upload file on the website

I need upload file on the website.
But Have a problem, i can't choose file automatic in code. Always browser show me choose file window.
What wrong in my code?
IE ie = new IE("https://www.xxxx.com/WFrmlogin.aspx");
FileUploadDialogHandler uploadHandler = new FileUploadDialogHandler(#"D:\065-6405_URGENT.xls");
ie.WaitForComplete();
ie.TextField(Find.ById("txtUser")).TypeText("login");
ie.TextField(Find.ById("txtPassWord")).TypeText("***");
ie.Button(Find.ById("btnok")).Click();
ie.WaitForComplete();
ie.GoTo("https://www.orientspareparts.com/inq/WFrmUpOption.aspx");
ie.WaitForComplete();
ie.DialogWatcher.Clear();
ie.AddDialogHandler(uploadHandler);
// This code show choose file dialog
ie.FileUpload(Find.ById("FilUpload")).ClickNoWait();
ie.Button(Find.ById("butUpload")).Click();
ie.WaitForComplete();
I had the same problem. I'm using a GMail-like upload process, so I wanted to test actual use-cases. Just setting the Text property on my hidden file input wasn't an option.
I ended up using SendKeys to type the path to my file, then sent "{ENTER}" to submit the dialog.
SetForegroundWindow(browser.hWnd);
SendKeys.SendWait("{ENTER}");
Thread.Sleep(500); // An unfortunate necessity, to give the dialog time to pop up.
SendKeys.SendWait(#"C:\myfile.jpg{ENTER}")
I don't love this solution, especially not the sleep, but it was the best I could do in under 30 mins.
If anyone has a better option, let me know!
Why do you need to select from the Dialog? Try to just set the Text:
ie.FileUpload(Find.ById("profile_file")).Text = "C:/Desktop/image.jpg";
I guess you might talk to the fellow who asked this question:
WatiN File Upload

Resources