There is a link behind button with PDF file on web page that I would like to access. PDF link has API key and can't be accessed directly. Button has ID company_report_link.
If I do reportDownloadButton.Click(); PDF gets opened in separate tab of browser but I can't figure out how to download it.
I have tried right click the button and select Save As? I am able to open Chrome Context menu with this one, but can't select Save link As..
// click the link to download
var reportDownloadButton = driver.FindElementById("company_report_link");
// reportDownloadButton.Click();
// if clicking does not work, get href attribute and call GoToUrl() -- this may trigger download
// var href = reportDownloadButton.GetAttribute("href");
// driver.Navigate().GoToUrl(href);
InputSimulator s = new InputSimulator();
Actions action1 = new Actions(driver);
action1.ContextClick(reportDownloadButton);
s.Keyboard.KeyPress(VirtualKeyCode.DOWN);
Thread.Sleep(2000);
s.Keyboard.KeyPress(VirtualKeyCode.DOWN);
Thread.Sleep(2000);
s.Keyboard.KeyPress(VirtualKeyCode.DOWN);
Thread.Sleep(2000);
s.Keyboard.KeyPress(VirtualKeyCode.DOWN);
Thread.Sleep(2000);
s.Keyboard.KeyPress(VirtualKeyCode.RETURN);
I have tried to do the trick with WebClient
var reportDownloadButton = driver.FindElementById("company_report_link");
var text = reportDownloadButton.GetAttribute("href");
// driver.Manage().Timeouts().ImplicitWait = System.TimeSpan.FromSeconds(15);
WebClient client = new WebClient();
// Save the file to desktop for debugging
var desktop = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop);
string fileName = desktop + "\\myfile.pdf";
client.DownloadFile(text, fileName);
but it does not work because of API. Web site is giving:
System.Net.WebException: 'The remote server returned an error: (401)
Unauthorized.'
Related
I've created an VSTO-Add-In for Outlook, which imports several data from an pdf-file and saves the data as an MS-Excel-File. After successfully process i start a Toastnotification ,which enables an fast opening of this Excel-file by clicking on the notification in the info-center. The problem: clicking on the notification of other incoming e-mails (Outlook) doesn't work anymore. Nothing happens. How can i solve this problem?
public Ribbon1()
{
Initialize();
}
private async Task Initialize()
{
await Task.Run(() =>
{
ToastNotificationManagerCompat.OnActivated += async toastArgs =>
{
ToastArguments args = ToastArguments.Parse(toastArgs.Argument);
await Task.Run(() =>
{
if (!string.IsNullOrEmpty(toastArgs.Argument) && !toastArgs.Argument.Contains("idEPST=ignore") && toastArgs.Argument.Contains("idEPST="))
{
string datei = toastArgs.Argument.ToLower().Replace("idEPST=", String.Empty).Trim().Replace(".xls", "");
ProcessStartInfo si = new ProcessStartInfo();
si.FileName = "excel.exe";
si.Arguments = $"\"C:\\folder\\file.xls\" /{datei}";
Process.Start(si);
}
});
};
});
}
}
//and later
new ToastContentBuilder()
.AddAudio(null, silent: true)
.AddArgument("idEPST", filename)
.AddHeader("identifier", "My Excel App Name", String.Empty)
.AddText($"{name}, {firstname}", hintMaxLines: 1)
.AddText("... sucessfully saved.")
.Show();
After deinstalling the VSTO-Add-In: On clicking on a e-mail-notification results in an error message:
"Cannot Start Microsoft Outlook. The Command Line Argument Is Not Valid..."
It seems there are some problems with windows registry keys, especially with .msg file associations. Because when you click on a toast notification in Outlook a corresponding item is displayed/opened.
Re-associate the .msg file by following the steps and verify the results.
Click on Start and then Default Programs.
Click on Associate a file type protocol with a program option.
Select .msg from the Name list and then click on Change Program.
Now click to select Microsoft Office Outlook and then click on OK.
Restart the computer and then try opening emails saved on the Computer.
See Error: The command line argument is not valid. Verify the switch you are using. for more information.
I'm creating a simple news feed, it i want it can open the browser to show the details of the news, but i don't know how to close the browser , here is the code of how I open the browser,anyone can teach me how to off the browser using uwp? '
public async void test()
{
RootObject mynews = await NewsProxy.GetNews();
string website = mynews.articles[i].url;
var uriWeb = new Uri(websites);
var success = await Windows.System.Launcher.LaunchUriAsync(uriWeb);
if (success)
{
//Uri launched
}
else
{
// uri launch failed
}
}
var success = await Windows.System.Launcher.LaunchUriAsync(uriWeb);
Your code is actually telling the OS to Launch the given url and the OS in turn launches the default browser with the given URL. So you are not actually launching the browser.
In order to have full control over the browser behavior you can implement your own WebView and then use the url to navigate your WebView.
webView1.Navigate("http://www.contoso.com");
(MSDN Documentation for WebView)
How can I perform the save this page directly in pdf? I know that selenium is not able to control the chrome dialog box ... is there another way?
Page to save in pdf:
This below code will help to save page as pdf in Selenium c#.
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
protected void PDFconversion(ChromeDriver driver, string root, string rootTemp)
{
//Grid.Rows.Add(TxtBxName.Text, TxtBxAddress.Text);
try
{
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
Thread.Sleep(500);
js.ExecuteScript("setTimeout(function() { window.print(); }, 0);");
Thread.Sleep(500);
driver.SwitchTo().Window(driver.WindowHandles.Last());
Thread.Sleep(500);
string JSPath = "document.querySelector('body>print-preview-app').shadowRoot.querySelector('#sidebar').shadowRoot.querySelector('#destinationSettings').shadowRoot.querySelector('#destinationSelect').shadowRoot.querySelector('print-preview-settings-section:nth-child(9)>div>select>option:nth-child(3)')";
Thread.Sleep(500);
IWebElement PrintBtn = (IWebElement)js.ExecuteScript($"return {JSPath}");
Thread.Sleep(500);
PrintBtn.Click();
string JSPath1 = "document.querySelector('body>print-preview-app').shadowRoot.querySelector('#sidebar').shadowRoot.querySelector('print-preview-button-strip').shadowRoot.querySelector('cr-button.action-button')";
Thread.Sleep(1000);
IWebElement PrintBtn1 = (IWebElement)js.ExecuteScript($"return {JSPath1}");
PrintBtn1.Click();
Thread.Sleep(1000);
SendKeys.Send("{HOME}");
SendKeys.Send(rootTemp + "\\" + "result.pdf"); // Path
SendKeys.Send("{TAB}");
SendKeys.Send("{TAB}");
SendKeys.Send("{TAB}");
SendKeys.Send("{ENTER}");
Thread.Sleep(1000);
}
catch (Exception ex)
{
}
}
Another way to save is by commanding to the Chrome to save to the disk instead opening to the Page.
Below is the way to do:
ChromeOptions chromeOptions = new ChromeOptions();
// this will make automatically download to the default folder.
chromeOptions.AddUserProfilePreference("plugins.always_open_pdf_externally", true);
ChromeDriverService chromeDriverService = ChromeDriverService.CreateDefaultService();
chromeDriver = new ChromeDriver(chromeDriverService, chromeOptions);
var downloadsPath = KnownFolders.Downloads.Path;
var generatedFilePngs = Directory.GetFiles(downloadsPath, string.Format("{0}*.pdf", "TheNameOfYourPDF"));
You can directly send the request to the url without Selenium involved and get the byte array with content of PDF file. After that you can read file content using some PDF library (looks like ITextSharp is popular).
Inside Chrome browser all the dialog popups are html pages so you can click on them using Selenium.
In your case you can navigate to a page, simulate Ctrl + P keyboard button press, switch to print dialog window, click Change button to change the printer, click Save to PDF, click Save button and when "Save As" box is shown - simulate Enter keyboard button press to actually save the file.
I don't do C#, but here is how that looks like in Java, in fact I have tested it and it actually works:
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_P);
robot.keyRelease(KeyEvent.VK_P);
robot.keyRelease(KeyEvent.VK_CONTROL);
// get current browser window handles and switch to window with handle that is last in the list
Set<String> windowHandles = driver.getWindowHandles();
for (String handle : windowHandles) {
driver.switchTo().window(handle);
}
driver.findElement(By.xpath("//button[contains(text(), 'Change')]")).click();
driver.findElement(By.xpath("//span[contains(text(), 'Save as PDF')]")).click();
driver.findElement(By.xpath("//button[contains(text(), 'Save')]")).click();
// you might need to add waiter here that waits a second, since script is too fast
// and needs to wait for save dialog box to be shown
robot.keyPress(KeyEvent.VK_ENTER);
I wanted to get the name of the URL which user Opens in IE and wanted to save it to a File.I am ruuning a console application in which i wanted to get notify that new Url is open in IE and then Get that URL and save it to a File.Please Provide me some code snippet to do that .
Currently i am using this code which get the name of all URL opens but problem is that when i opens a new Url IN IE it doesnot get any new URL in my Console application.
static void Main(string[] args)
{
foreach (SHDocVw.InternetExplorer ie in new ShellWindows())
{
string filename = Path.GetFileNameWithoutExtension(ie.FullName).ToLower();
if (filename == "iexplore")
{
Console.WriteLine(ie.LocationURL);
StreamWriter _objStreamWriter = new StreamWriter(#"c:\file.txt", true);
_objStreamWriter.WriteLine(ie.LocationURL);
_objStreamWriter.Close();
}
}
Console.ReadKey();
}
I am new to Telerik controls, in my code I am trying to Upload excel file using RadAsync upload.
Code is working fine, but when user is trying to upload a file which is already opened in the background- I am getting javascript exception.
Is there is any way by which I can alert user in case file is already opened?
You can use OnClientFileUploadFailed event of Telerik RadAsync Upload.
Something like
function OnClientFileUploadFailed(sender, args) {
var upload = $find("<%= RadUpload.ClientID %>");
var errormsg = args.get_message();
var displaymsg = new String();
sender.deleteFileInputAt(0);
if (errormsg.search("[IO.IO_SharingViolation_File]") != -1) {
displaymsg = "File: is currently in use. Please close the file and try again.";
}
else {
displaymsg = "The file you selected is currently in use. Please close the file and try again.";
}
alert(displaymsg);
args.set_handled(true);
}