Start with the simplest task of capturing the URL in Firefox from a C# application. It appears using user32.dll Windows API functions will not work as is the approach for capturing the URL within IE.
Should I need to do a capture of the URL with AutoHotkey, for example, I would send Ctrl+L (put focus in address bar and highlight content) and Ctrl+C (copy selection to clipboard). Then you just read the clipboard to get the info.
For more complex tasks, I would use Greasemonkey or iMacros extensions, perhaps triggered by similar keyboard shortcuts.
WatiN has support for Firefox.
WebAii can automate FireFox, including setting and retrieving the URL
It appears to be very beta-ey, but someone built a .net connector for mozrepl. Actually, the mozrepl codebase just moved to github. But mozrepl lets you issue commands to the Firefox's XUL environment.
Try Selenium (the Google testing engine - http://seleniumhq.org/) You can record task (Webpages UI related) done in Firefox and the convert the recording into a C# source :)
You can use Selenium WebDriver for C #.
This is a cross-platform API that allows you to control various browsers using APIs for Java, C#, among others.
Attachment of a code C # with Selenium WebDriver tests.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Interactions.Internal;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.IE;
using NUnit.Framework;
using System.Text.RegularExpressions;
namespace sae_test
{ class Program
{ private static string baseURL;
private static StringBuilder verificationErrors;
static void Main(string[] args)
{ // test with firefox
IWebDriver driver = new OpenQA.Selenium.Firefox.FirefoxDriver();
// test with IE
//InternetExplorerOptions options = new InternetExplorerOptions();
//options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
//IWebDriver driver = new OpenQA.Selenium.IE.InternetExplorerDriver(options);
SetupTest();
driver.Navigate().GoToUrl(baseURL + "Account/Login.aspx");
IWebElement inputTextUser = driver.FindElement(By.Id("MainContent_LoginUser_UserName"));
inputTextUser.Clear();
driver.FindElement(By.Id("MainContent_LoginUser_UserName")).Clear();
driver.FindElement(By.Id("MainContent_LoginUser_UserName")).SendKeys("usuario");
driver.FindElement(By.Id("MainContent_LoginUser_Password")).Clear();
driver.FindElement(By.Id("MainContent_LoginUser_Password")).SendKeys("123");
driver.FindElement(By.Id("MainContent_LoginUser_LoginButton")).Click();
driver.Navigate().GoToUrl(baseURL + "finanzas/consulta.aspx");
// view combo element
IWebElement comboBoxSistema = driver.FindElement(By.Id("MainContent_rcbSistema_Arrow"));
//Then click when menu option is visible
comboBoxSistema.Click();
System.Threading.Thread.Sleep(500);
// container of elements systems combo
IWebElement listaDesplegableComboSistemas = driver.FindElement(By.Id("MainContent_rcbSistema_DropDown"));
listaDesplegableComboSistemas.FindElement(By.XPath("//li[text()='BOMBEO MECANICO']")).Click();
System.Threading.Thread.Sleep(500);
IWebElement comboBoxEquipo = driver.FindElement(By.Id("MainContent_rcbEquipo_Arrow"));
//Then click when menu option is visible
comboBoxEquipo.Click();
System.Threading.Thread.Sleep(500);
// container of elements equipment combo
IWebElement listaDesplegableComboEquipos = driver.FindElement(By.Id("MainContent_rcbEquipo_DropDown"));
listaDesplegableComboEquipos.FindElement(By.XPath("//li[text()='MINI-V']")).Click();
System.Threading.Thread.Sleep(500);
driver.FindElement(By.Id("MainContent_Button1")).Click();
try
{ Assert.AreEqual("BOMBEO MECANICO_22", driver.FindElement(By.XPath("//*[#id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_LabelSistema\"]")).Text);
}
catch (AssertionException e)
{ verificationErrors.Append(e.Message);
}
// verify coin format $1,234,567.89 usd
try
{ Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath("//*[#id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelInversionInicial\"]")).Text, "\\$((,)*[0-9]*[0-9]*[0-9]+)+(\\.[0-9]{2})? usd"));
}
catch (AssertionException e)
{ verificationErrors.Append(e.Message);
}
try
{ Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath("//*[#id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelCostoOpMantto\"]")).Text, "\\$((,)*[0-9]*[0-9]*[0-9]+)+(\\.[0-9]{2})? usd"));
}
catch (AssertionException e)
{ verificationErrors.Append(e.Message);
}
try
{ Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath("//*[#id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelCostoEnergia\"]")).Text, "\\$((,)*[0-9]*[0-9]*[0-9]+)+(\\.[0-9]{2})? usd"));
}
catch (AssertionException e)
{ verificationErrors.Append(e.Message);
}
try
{ Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath("//*[#id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelcostoUnitarioEnergia\"]")).Text, "\\$((,)*[0-9]*[0-9]*[0-9]+)+(\\.[0-9]{2})? usd"));
}
catch (AssertionException e)
{ verificationErrors.Append(e.Message);
}
// verify number format 1,234,567.89
try
{ Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath("//*[#id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelConsumo\"]")).Text, "((,)*[0-9]*[0-9]*[0-9]+)+(\\.[0-9]{2})?"));
}
catch (AssertionException e)
{ verificationErrors.Append(e.Message);
}
System.Console.WriteLine("errores: " + verificationErrors);
System.Threading.Thread.Sleep(20000);
driver.Quit();
}
public static void SetupTest()
{ baseURL = "http://127.0.0.1:8081/ver.rel.1.2/";
verificationErrors = new StringBuilder();
}
protected static void mouseOver(IWebDriver driver, IWebElement element)
{ Actions builder = new Actions(driver);
builder.MoveToElement(element);
builder.Perform();
}
public static void highlightElement(IWebDriver driver, IWebElement element)
{ for (int i = 0; i < 2; i++)
{ IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("arguments[0].setAttribute('style', arguments[1]);",
element, "color: yellow; border: 2px solid yellow;");
js.ExecuteScript("arguments[0].setAttribute('style', arguments[1]);",
element, "");
}
}
}
}
One Microsoft tool I ran into:
UI Automation, as part of .NET 3.5
http://msdn.microsoft.com/en-us/library/aa348551.aspx
Here's an example:
http://msdn.microsoft.com/en-us/library/ms771286.aspx
I don't have UI Spy on my pc to interrogate Firefox, so I don't know if this will help out with your user32.dll problem.
Related
Problem: LeanFT in C# doesn't have a way to open the browser in incognito mode unfortunately. I am unable to add -incognito to path as I don't have admin rights. What can I do? I was thinking Sendkeys(ā^+Nā); but not sure how to do that via keyboard or if it would work as browser is already instantiated.
Has anyone else run into this problem? It's really cumbersome like I said since LeanFT doesn't allow incognito mode to be runned automatically.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using HP.LFT.SDK;
using HP.LFT.Verifications;
using System.Diagnostics;
using System.Threading;
using HP.LFT.SDK.Web;
using HP.LFT.Report;
using System.Drawing;
namespace Xpathtest
{
[TestClass]
public class LeanFtTest : UnitTestClassBase<LeanFtTest>
{
//The Browser object on which the test will be run
IBrowser browser;
[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
GlobalSetup(context);
}
[TestInitialize]
public void TestInitialize()
{
browser = BrowserFactory.Launch(BrowserType.Chrome);
}
[TestMethod]
public void TestMethod1()
{
try
{
// Navigate to Rally
browser.Navigate("-incognito https://rally1.rallydev.com/");
browser.Sync();
Thread.Sleep(3000);
browser.Refresh();
// Find Username edit box using Xpath
IEditField userName = browser.Describe<IEditField>(new EditFieldDescription
{
XPath = "//input[#id='j_username']"
});
userName.SetValue("TEST");
Thread.Sleep(3000);
// Find password edit box using Xpath
IEditField password = browser.Describe<IEditField>(new EditFieldDescription
{
XPath = "//input[#id='j_password']"
});
password.SetValue("TEST");
Thread.Sleep(3000);
IButton submit = browser.Describe<IButton>(new ButtonDescription
{
XPath = "//*[#id='login-button']"
});
submit.Click();
browser.FullScreen();
Image img = browser.GetSnapshot();
Reporter.ReportEvent("Screenshot of failure", "", Status.Passed, img);
Thread.Sleep(3000);
}
catch (Exception e)
{
Assert.Fail("Unexpected Error Occurred while= " + e.Message);
}
}
[TestCleanup]
public void TestCleanup()
{
browser.Close();
}
[ClassCleanup]
public static void ClassCleanup()
{
GlobalTearDown();
}
}
}
You should use process.Start to start Chrome, and browser.Attach to a description to attach to the opened browser.
Here's the idea roughly:
using System.Diagnostics;
...
Process process = new Process();
// Configure the process using the StartInfo properties.
process.StartInfo.FileName = "chrome";
process.StartInfo.Arguments = "-incognito www.somesite.com";
process.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
process.Start();
BrowserFactory.Attach(new BrowserDescription
{
Url = "www.somesite.com"
});
...
But as Motti said in the comments, Attach will not work without the LeanFT extension enabled - which is disabled in incognito
I manage to open a firefox browser, go to http://www.google.com/ search for "Bath Fitter". When i see a bunch of links, i want to in fact click on an item of the top menu provided by Google, Images. Images is located next to Map Videos News...
How can i have it click on Images?
Below is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace SeleniumHelloWorld
{
class Program
{
static void Main(string[] args)
{
IWebDriver driver = null;
try
{
driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://www.google.com/");
driver.Manage().Window.Maximize();
IWebElement searchInput = driver.FindElement(By.Id("gbqfq"));
searchInput.SendKeys("Bath Fitter");
searchInput.SendKeys(Keys.Enter);
searchInput.FindElement(By.Name("Images"));
searchInput.Click();
driver.Close();
}
catch (Exception e)
{
Console.WriteLine("Exception ****" + e.ToString());
}
}
}
}
More specifically you can also write your selector pointing from Top Navigation. This is the XPath.
.//*[#id='hdtb_msb']//a[.='Images']
try this;
driver.FindElement(By.XPath(".//*[#id='hdtb_msb']//a[.='Images']"));
EDIT:
Even though the selectors above were correct your code was not working because of the second page was taking too long to load. There you need to wait for the the element to be in ready state and an implicit wait is needed. Change the code in your try block and replace with mine and try
driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://www.google.com/");
driver.Manage().Window.Maximize();
IWebElement searchInput = driver.FindElement(By.Id("gbqfq"));
searchInput.SendKeys("Bath Fitter");
searchInput.SendKeys(Keys.Enter);
//this is the magic
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
By byImage = By.XPath(".//*[#id='top_nav']//a[.='Images']");
IWebElement imagElement =
new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementExists(byImage));
imagElement.Click();
Try something like this...
IList<IWebElement> links = driver.FindElements(By.TagName("a"));
links.First(element => element.Text == "Images").Click();
I'm trying to generate a screenshot from a html page on windows Azure.
This is the code I was using on my personal IIS and I know it works on every test machine.
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
class Program
{
static void Main(string[] args)
{
new WebsiteToImage("http://www.google.com", "C:\\screenshot.jpg");
}
// Define other methods and classes here
public class WebsiteToImage
{
internal string _url;
internal string _fileName;
public WebsiteToImage(string url, string fileName)
{
_url = url;
_fileName = fileName;
// Thread
var thread = new Thread(Generate);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
}
private void Generate()
{
using (var browser = new WebBrowser { ScrollBarsEnabled = false })
{
browser.Navigate(_url);
browser.DocumentCompleted += WebBrowser_DocumentCompleted;
while (browser.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
browser.Dispose();
}
}
private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
// Capture
using (var bmp = new Bitmap(1280, 800))
{
var browser = (WebBrowser)sender;
browser.ClientSize = new Size(1280, 800);
browser.ScrollBarsEnabled = false;
browser.BringToFront();
browser.DrawToBitmap(bmp, browser.Bounds);
var encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
bmp.Save(_fileName, ImageCodecInfo.GetImageDecoders().FirstOrDefault(c => c.FormatID.Equals(ImageFormat.Jpeg.Guid)), encoderParameters);
}
}
}
}
Now, on Azure I know I can't use GDI+ and I'm pretty sure I can't also use WebBrowser.
Any idea or alternative solution? Even third part component.
You haven't said whether you're using Azure Web Sites or Azure Cloud Services, but from what you say about not being able to use GDI+, I'm guessing Web Sites?
You should certainly be able to run your code in a Cloud Service, either a Web or Worker role. If the code is part of a web application hosted on Web Sites, you can use an Azure Storage Queue to add the URL to be snap-shotted, then poll that queue on a worker role, run your code, and store the resulting file into Blob storage.
If your expected load on the screen-shot server is low, you could probably get away with an Extra-Small instance, which would cost very little.
Update: Awesomium should be an option in this case.
I found Is there a webservice/API to grab a screenshot of another website? and from there this service that do the task with an open source code. For the light use we're planning to do, this is better than a custom implemented solution.
I'm trying to use the Bing Search API to find images as backgrounds to the tiles inside of my app. I've included the BingSearchContainer.cs in my Project but I can't make it work with the sample code provided here.
Any guidelines for how to use the Bing Search API inside of my Windows Phone 8 app would be appriciated!
Thanks for any answer.
I expect that you already have a AccountKey so I wont tell you have to get one.
Implementation
First of all, add the BingSearchContainer.cs to your project
Implement the sample C# code found in the Bing API Quick Start & Code
Thereafter, right-click References and choose Manage NuGet Packages... and search for, and install, Microsoft.Data.Services.Client.WindowsP.
Modify the sample code so that it work with Windows Phone:
using Bing;
using System;
using System.Data.Services.Client;
using System.Linq;
using System.Net;
namespace StackOverflow.Samples.BingSearch
{
public class Finder
{
public void FindImageUrlsFor(string searchQuery)
{
// Create a Bing container.
string rootUri = "https://api.datamarket.azure.com/Bing/Search";
var bingContainer = new Bing.BingSearchContainer(new Uri(rootUri));
bingContainer.UseDefaultCredentials = false;
// Replace this value with your account key.
var accountKey = "YourAccountKey";
// Configure bingContainer to use your credentials.
bingContainer.Credentials = new NetworkCredential(accountKey, accountKey);
// Build the query.
var imageQuery = bingContainer.Image(query, null, null, null, null, null, null);
imageQuery.BeginExecute(_onImageQueryComplete, imageQuery);
}
// Handle the query callback.
private void _onImageQueryComplete(IAsyncResult imageResults)
{
// Get the original query from the imageResults.
DataServiceQuery<Bing.ImageResult> query =
imageResults.AsyncState as DataServiceQuery<Bing.ImageResult>;
var resultList = new List<string>();
foreach (var result in query.EndExecute(imageResults))
resultList.Add(result.MediaUrl);
FindImageCompleted(this, resultList);
}
public event FindImageUrlsForEventHandler FindImageUrlsForCompleted;
public delegate void FindImageUrlsForEventHandler(object sender, List<string> result);
}
}
Example
And now, let's use the code I provided you with:
using Bing;
using System;
using System.Data.Services.Client;
using System.Linq;
using System.Net;
namespace StackOverflow.Samples.BingSearch
{
public class MyPage
{
private void Button_Click_1(object sender, RoutedEventArgs e)
{
var finder = new Finder();
finder.FindImageUrlsForCompleted += finder_FindImageUrlsForCompleted;
finder.FindImageUrlsFor("candy");
}
void finder_FindImageUrlsForCompleted(object sender, List<string> result)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
foreach (var s in result)
MyTextBox.Text += s + "\n";
});
}
}
}
I'm researching Selenium and have a seminar for my group...
I meet many troubles with this
I use C# language and write a demo SeleniumExample.dll Then I start
selenium RC and NUnit and run it with NUnit to see the test report.
I read testdata from XML.
Here's the SeleniumExample.dll: using System;
using System.Xml;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using NUnit.Framework;
using Selenium;
namespace SeleniumExample
{
public class Success_Login
{
//User defined
private string strURL = "http://newtours.demoaut.com/
mercurywelcome.php";
private string[] strBrowser = new string[3] { "*iehta",
"*firefox", "*safari" };
// System defined
private ISelenium selenium;
private StringBuilder verificationErrors ;
[SetUp]
public void SetupTest()
{
selenium = new DefaultSelenium("localhost", 4444,
this.strBrowser[0], this.strURL);
selenium.Start();
verificationErrors = new StringBuilder();
}
[TearDown]
public void TeardownTest()
{
try
{
selenium.Stop();
}
catch (Exception)
{
// Ignore errors if unable to close the browser
}
Assert.AreEqual("", verificationErrors.ToString());
}
[Test]
public void Success_LoginTest()
{
try
{
XmlDocument doc = new XmlDocument();
XmlNode docNode;
doc.Load("XMLFile1.xml");
docNode = doc["TestCase"];
foreach (XmlNode node in docNode)
{
selenium.Open("/");
selenium.Type("userName",
node["username"].InnerText);
selenium.Type("password",
node["password"].InnerText);
selenium.Click("login");
selenium.WaitForPageToLoad("30000");
Assert.AreEqual("Find a Flight: Mercury Tours:",
selenium.GetTitle());
}
}
catch (AssertionException e)
{
verificationErrors.Append(e.Message);
}
}
}
}
Now I want to have a demo that using Selenium Grid (SG) but I don't know
how to do. I read document and understand the way SG works. I install
SG and install Ant1.8. The tests will communicate with Selenium Hub.
Actually, I just understand the theory I don't know how to make the
tests communicate with Selenium Hub and how to make Selenium Hub
control Selenium RC.
I am a new for Selenium. If anyone know this, please help me. I
appreciate it so much.
THANKS,
Hoang
In reality there is no major difference between Selenium RC and Selenium Grid. The only difference is that with Grid you don't have to know where the RC nodes are but if you use Selenium RC you will have to.
string hubAddress = "machineNameWithSeleniumGridHub"
[SetUp]
public void SetupTest()
{
selenium = new DefaultSelenium(hubAddress, 4444,this.strBrowser[0], this.strURL);
selenium.Start();
verificationErrors = new StringBuilder();
}
When your tests run they will speak to the hub which will then push the commands out to the first available RC. I have a Selenium Tutorial on my site. It uses C# and should get you going.