RequestNavigate to Hyperlink with page anchor - c#

I need to open a local .HTM file and navigate to a specific anchor name.
In this case it is an alarm information file with over 1,000 alarms / anchors.
In my test example (full code below) the Uri Fragment doesn't make it into the browser.
I have tried other ways of creating the hyperlink but this is as close as I could get.
The Test App:
Result:
MainWindow.xaml
<Window x:Class="HyperlinkWithPageAnchor.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="100" Width="200">
<Grid>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center">
<Hyperlink NavigateUri="{Binding HyperlinkNavUri}" RequestNavigate="Hyperlink_RequestNavigate">
<TextBlock Text="Link Text"/>
</Hyperlink>
</TextBlock>
</Grid>
</Window>
MainWindow.xaml.cs
namespace HyperlinkWithPageAnchor
{
using System;
using System.Windows;
using System.ComponentModel;
using System.Windows.Navigation;
public partial class MainWindow : Window, INotifyPropertyChanged
{
private Uri _hyperlinkNavUri;
public Uri HyperlinkNavUri
{
get { return _hyperlinkNavUri; }
set { _hyperlinkNavUri = value; OnPropertyChanged(nameof(HyperlinkNavUri)); }
}
public MainWindow()
{
InitializeComponent(); DataContext = this;
// Desired Address: file:///C:/OSP-P/P-MANUAL/MPA/ENG/ALARM-A.HTM#1101
UriBuilder uBuild = new UriBuilder(new Uri("file://"));
uBuild.Path = #"C:\OSP-P\P-MANUAL\MPA\ENG\ALARM-A.HTM";
uBuild.Fragment = "1101";
HyperlinkNavUri = uBuild.Uri;
}
private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
try { string link = e.Uri.ToString(); MessageBox.Show(link); System.Diagnostics.Process.Start(link); }
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string name) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); }
}
}

It seems that if you let the OS identify the default browser itself, it will remove the anchor from the URI.
You need to use the following overload of Process.Start which allows to specify the executable and the parameters:
ProcessStartInfo processStartInfo = new ProcessStartInfo();
processStartInfo.FileName = #"C:\Program Files\Internet Explorer\iexplore.exe";
processStartInfo.Arguments = "file:///C:/OSP-P/P-MANUAL/MPA/ENG/ALARM-A.HTM#1101";
Process.Start(processStartInfo);
If you want to use browser defined by the user instead of an hard-coded one, you will have to query the Windows Registry in order to retrieve it.
For example on old version of windows (before Vista I think), you have to use the following registry key: HKEY_CLASSES_ROOT\http\shell\open\command. On later release, this key contains the default browser (if the browser does not made any change).
private string GetDefaultBrowser()
{
string regKey = #"HTTP\shell\open\command";
using (RegistryKey registrykey = Registry.ClassesRoot.OpenSubKey(regKey, false))
{
return ((string)registrykey.GetValue(null, null)).Split('"')[1];
}
}
On Windows 10, it is a bit more complex due to the application launcher that allows to select the default application. To retrieve the browser chosen by the user, you have to query the following registry key: HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.html\UserChoice. It the key does not exist you have to fallback on the previously mentioned key: HKEY_CLASSES_ROOT\http\shell\open\command.
private string GetDefaultBrowserOnWin10()
{
string execPath;
try
{
string extension = ".htm"; // either .htm or .html
RegistryKey propertyBag = Registry.CurrentUser.OpenSubKey($#"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{extension}\UserChoice", false);
var browserProgId = propertyBag.GetValue("ProgId").ToString(); ;
using (RegistryKey execCommandKey = Registry.ClassesRoot.OpenSubKey(browserProgId + #"\shell\open\command", false))
{
execPath = execCommandKey.GetValue(null).ToString().ToLower().Replace("\"", "");
if (IsDefaultLauncherApp(execPath))
{
System.Diagnostics.Debug.WriteLine("No user-defined browser or IE selected; anchor will be lost.");
}
}
if (!execPath.EndsWith("exe"))
{
execPath = execPath.Substring(0, execPath.LastIndexOf(".exe") + 4);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
execPath = GetDefaultBrowser();
}
return execPath;
}
private bool IsDefaultLauncherApp(string appPath)
{
return appPath.Contains("launchwinapp.exe");
}
This will work for all browsers except Microsoft Edge, which do not allow that at the moment.
You can use in you program like this:
private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
try {
string link = e.Uri.ToString();
System.Diagnostics.ProcessStartInfo processStartInfo = new System.Diagnostics.ProcessStartInfo();
processStartInfo.FileName = GetDefaultBrowserOnWin10();
processStartInfo.Arguments = link;
System.Diagnostics.Process.Start(processStartInfo);
} catch (Exception ex) {
MessageBox.Show(ex.Message);
}
}
Some additional answers:
How to find default web browser using C#?

Related

VS for Mac extension - null Editor in ActiveWindow

I'm trying to get into developing an extension for Visual Studio for Mac. I'm using this tutorial. Everything had been going well until I tried to run my extension. In my case "Insert date" in Edit submenu is disabled. While debugging I've noticed that IdeApp.Workbench.ActiveDocument.Editor is null despite I have an open document. Here's my code
using System;
using MonoDevelop.Components.Commands;
using MonoDevelop.Ide;
namespace ExampleIDEExtension
{
public class InsertDateHandler : CommandHandler
{
protected override void Run()
{
var editor = IdeApp.Workbench.ActiveDocument.Editor;
var currentTime = DateTime.Now.ToString();
editor.InsertAtCaret(currentTime);
}
protected override void Update(CommandInfo info)
{
info.Enabled = IdeApp.Workbench.ActiveDocument.Editor != null;
}
}
}
I have no idea why Editor is null despite having an open document.
The editor is null, as Monodevelop is using Microsoft.VisualStudio.Text.Editor and it mentions that the API has been obsolete in the below link.
https://github.com/mono/monodevelop/blob/50fbe0a7e65c5439e3313c6b50e7ef927f5f1fe9/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Editor/TextEditor.cs
Anyways, to answer your question, this is what I had to do to achieve the insert date handler demo addin
protected override void Run()
{
var textBuffer = IdeApp.Workbench.ActiveDocument.GetContent<ITextBuffer>();
var date = DateTime.Now.ToString();
var textView = IdeApp.Workbench.ActiveDocument.GetContent<ITextView>();
var caretPosition = textView.Caret.Position;
textBuffer.Insert(caretPosition.BufferPosition.Position,date);
}
protected override void Update(CommandInfo info)
{
var textBuffer = IdeApp.Workbench.ActiveDocument.GetContent<ITextBuffer>();
if (textBuffer != null && textBuffer.AsTextContainer() is SourceTextContainer container)
{
var document = container.GetTextBuffer();
if (document != null)
{
info.Enabled = true;
}
}
}
Just to embellish vin's answer for others still struggling with creating extensions on Visual Studio for Mac it needs to look like this in InsertDateHandler.cs:
using System;
using MonoDevelop.Components.Commands;
using MonoDevelop.Ide;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.CodeAnalysis.Text;
namespace DateInserter
{
class InsertDateHandler : CommandHandler
{
protected override void Run()
{
var textBuffer = IdeApp.Workbench.ActiveDocument.GetContent<ITextBuffer>();
var date = DateTime.Now.ToString();
var textView = IdeApp.Workbench.ActiveDocument.GetContent<ITextView>();
var caretPosition = textView.Caret.Position;
textBuffer.Insert(caretPosition.BufferPosition.Position, date);
}
protected override void Update(CommandInfo info)
{
var textBuffer = IdeApp.Workbench.ActiveDocument.GetContent<ITextBuffer>();
if (textBuffer != null && textBuffer.AsTextContainer() is SourceTextContainer container)
{
var document = container.GetTextBuffer();
if (document != null)
{
info.Enabled = true;
}
}
}
}
}
The next piece of the puzzle that seems to be missing everywhere is just exactly how to package up the extension so you can both install it yourself in your version if Visual studio for mac and how to share the extension for others.
Here is how I do it:
Open Terminal on the Mac, navigate to the .dll you just created when you build the extension for example:
/volumes/ssd1/Myapps/VSCodeextensions/dateinserter/dateinserter/bin/debug/net472
Then create a .mpack file by doing this:-
% mono /Applications/"Visual Studio.app"/Contents/Resources/lib/monodevelop/bin/vstool.exe setup pack DateInserter.dll

LeanFT Opening Browser in Incognito Mode

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

Print a ReportViewer Without Preview

I'm using Visual Studio 2010 C# Windows Forms Application + MySql
I have a Report Viewer that is working 100% . The reportviewer is filled with data of my database, it shows up I click on the button to print and it prints... BUT, my client does not want to click on this button, he wants to print automatically. When I Call the ReportViewer it print by itself without need to click on a button to do that. Could anyone tell me how I do that ?
I tryed reportviewer1.print and the PrintDocument from the toolbox. But I do not know how to use these correctly.
Thanks the attention !
I had just the same issue this is the code i use and works like a charm!
using System;
using System.IO;
using System.Text;
using System.Globalization;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using Microsoft.Reporting.WinForms;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace NewLabelPrinter
{
/// <summary>
/// The ReportPrintDocument will print all of the pages of a ServerReport or LocalReport.
/// The pages are rendered when the print document is constructed. Once constructed,
/// call Print() on this class to begin printing.
/// </summary>
class AutoPrintCls : PrintDocument
{
private PageSettings m_pageSettings;
private int m_currentPage;
private List<Stream> m_pages = new List<Stream>();
public AutoPrintCls(ServerReport serverReport)
: this((Report)serverReport)
{
RenderAllServerReportPages(serverReport);
}
public AutoPrintCls(LocalReport localReport)
: this((Report)localReport)
{
RenderAllLocalReportPages(localReport);
}
private AutoPrintCls(Report report)
{
// Set the page settings to the default defined in the report
ReportPageSettings reportPageSettings = report.GetDefaultPageSettings();
// The page settings object will use the default printer unless
// PageSettings.PrinterSettings is changed. This assumes there
// is a default printer.
m_pageSettings = new PageSettings();
m_pageSettings.PaperSize = reportPageSettings.PaperSize;
m_pageSettings.Margins = reportPageSettings.Margins;
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
foreach (Stream s in m_pages)
{
s.Dispose();
}
m_pages.Clear();
}
}
protected override void OnBeginPrint(PrintEventArgs e)
{
base.OnBeginPrint(e);
m_currentPage = 0;
}
protected override void OnPrintPage(PrintPageEventArgs e)
{
base.OnPrintPage(e);
Stream pageToPrint = m_pages[m_currentPage];
pageToPrint.Position = 0;
// Load each page into a Metafile to draw it.
using (Metafile pageMetaFile = new Metafile(pageToPrint))
{
Rectangle adjustedRect = new Rectangle(
e.PageBounds.Left - (int)e.PageSettings.HardMarginX,
e.PageBounds.Top - (int)e.PageSettings.HardMarginY,
e.PageBounds.Width,
e.PageBounds.Height);
// Draw a white background for the report
e.Graphics.FillRectangle(Brushes.White, adjustedRect);
// Draw the report content
e.Graphics.DrawImage(pageMetaFile, adjustedRect);
// Prepare for next page. Make sure we haven't hit the end.
m_currentPage++;
e.HasMorePages = m_currentPage < m_pages.Count;
}
}
protected override void OnQueryPageSettings(QueryPageSettingsEventArgs e)
{
e.PageSettings = (PageSettings)m_pageSettings.Clone();
}
private void RenderAllServerReportPages(ServerReport serverReport)
{
try
{
string deviceInfo = CreateEMFDeviceInfo();
// Generating Image renderer pages one at a time can be expensive. In order
// to generate page 2, the server would need to recalculate page 1 and throw it
// away. Using PersistStreams causes the server to generate all the pages in
// the background but return as soon as page 1 is complete.
NameValueCollection firstPageParameters = new NameValueCollection();
firstPageParameters.Add("rs:PersistStreams", "True");
// GetNextStream returns the next page in the sequence from the background process
// started by PersistStreams.
NameValueCollection nonFirstPageParameters = new NameValueCollection();
nonFirstPageParameters.Add("rs:GetNextStream", "True");
string mimeType;
string fileExtension;
Stream pageStream = serverReport.Render("IMAGE", deviceInfo, firstPageParameters, out mimeType, out fileExtension);
// The server returns an empty stream when moving beyond the last page.
while (pageStream.Length > 0)
{
m_pages.Add(pageStream);
pageStream = serverReport.Render("IMAGE", deviceInfo, nonFirstPageParameters, out mimeType, out fileExtension);
}
}
catch (Exception e)
{
MessageBox.Show("possible missing information :: " + e);
}
}
private void RenderAllLocalReportPages(LocalReport localReport)
{
try
{
string deviceInfo = CreateEMFDeviceInfo();
Warning[] warnings;
localReport.Render("IMAGE", deviceInfo, LocalReportCreateStreamCallback, out warnings);
}
catch (Exception e)
{
MessageBox.Show("error :: " + e);
}
}
private Stream LocalReportCreateStreamCallback(
string name,
string extension,
Encoding encoding,
string mimeType,
bool willSeek)
{
MemoryStream stream = new MemoryStream();
m_pages.Add(stream);
return stream;
}
private string CreateEMFDeviceInfo()
{
PaperSize paperSize = m_pageSettings.PaperSize;
Margins margins = m_pageSettings.Margins;
// The device info string defines the page range to print as well as the size of the page.
// A start and end page of 0 means generate all pages.
return string.Format(
CultureInfo.InvariantCulture,
"<DeviceInfo><OutputFormat>emf</OutputFormat><StartPage>0</StartPage><EndPage>0</EndPage><MarginTop>{0}</MarginTop><MarginLeft>{1}</MarginLeft><MarginRight>{2}</MarginRight><MarginBottom>{3}</MarginBottom><PageHeight>{4}</PageHeight><PageWidth>{5}</PageWidth></DeviceInfo>",
ToInches(margins.Top),
ToInches(margins.Left),
ToInches(margins.Right),
ToInches(margins.Bottom),
ToInches(paperSize.Height),
ToInches(paperSize.Width));
}
private static string ToInches(int hundrethsOfInch)
{
double inches = hundrethsOfInch / 100.0;
return inches.ToString(CultureInfo.InvariantCulture) + "in";
}
}
}
This class has the set up perfect for what you need then all you need to do is:
private void AutoPrint()
{
AutoPrintCls autoprintme = new AutoPrintCls(reportViewer1.LocalReport);
autoprintme.Print();
}
and hey presto it prints. Just attach this to A method in your code(maybe after the report Loads.) and your setup nicely!
option: (not tested)
As spotted this prints out to the default printer, to change the printer you could do the following:
if (printDialog.ShowDialog() == DialogResult.OK)
{
m_pageSettings .PrinterSettings.PrinterName = printDialog.PrinterSettings.PrinterName;
}
not tested though as i no longer have any source code to test this out
If my Crystal Report answer doesn't work for you, you can also try this page. Again, I haven't tested it, and can't be sure that it works, but it looks like an entirely different approach which might work. If not, then I'm not going to be any help, unfortunately.
This is how we do it with Crystal Reports.
ReportDocument rd = new ReportDocument();
// Insert code to run the report here
// This gets the user's default printer to print to.
PrintDialog prt = new PrintDialog();
rd.PrintOptions.PrinterName = prt.PrinterSettings.PrinterName;
// This does the printing.
rd.PrintToPrinter(copies, true, 1, 1000);
I think the equivalent to PrintOptions.PrinterName for you would be ReportViewer.PrinterSettings, but I suspect what you really need is the equivalent to PrintToPrinter(), which I don't see in my brief look.

Opening mp3 by not-default program C sharp

How can I open mp3 file with RealPlayer while the default is MediaPlayer
I know Process and ProcessStartInfo method, but I would like to know how to "open program with..."
Can you help me, plz?
Okay, so thought I'd make this possible for you before I clock off for the night. I have thrown together a working console application which loads (known) installed programs from the registry's App Path key. The solution is far from perfect, won't be the safest, fastest, or most reliable solution, and it certainly shouldn't be seen amongst any production code, but it is more than enough to aid you, hopefully, in developing what it is you need:
So, here is the code, minus the namespace...
using System;
using System.IO;
using Microsoft.Win32;
using System.Diagnostics;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
if (args.Length >= 0 && !string.IsNullOrEmpty(args[0]) && File.Exists(args[0]))
{
var programs = new InstalledPrograms();
var programKey = "RealPlay.exe".ToLowerInvariant();
if (programs.ContainsKey(programKey))
{
var programPath = programs[programKey];
if (!string.IsNullOrEmpty(programPath) && File.Exists(programPath))
{
var process = new Process();
process.StartInfo = new ProcessStartInfo(programPath);
process.StartInfo.Arguments = args[0];
if (process.Start())
{
Console.WriteLine("That was easy!");
}
else
{
Console.WriteLine("Hell's bells and buckets of blood, we seem to have hit a snag!");
}
}
}
}
else
{
Console.WriteLine("Specify a file as an argument, silly!");
}
Console.WriteLine();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
class InstalledPrograms : Dictionary<string, string>
{
static string PathKeyName = "Path";
static string RegistryKeyToAppPaths = #"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths";
public InstalledPrograms()
{
Refresh();
}
public void Refresh()
{
Clear();
using (var registryKey = Registry.LocalMachine.OpenSubKey(RegistryKeyToAppPaths))
{
var executableFullPath = string.Empty;
foreach (var registrySubKeyName in registryKey.GetSubKeyNames())
{
using (var registrySubKey = registryKey.OpenSubKey(registrySubKeyName))
{
executableFullPath = registrySubKey.GetValue(string.Empty) as string;
Add(registrySubKeyName.ToLowerInvariant(), executableFullPath);
}
}
}
}
}
}
Though we check for file existence, and other minor but necessary checks are made, you would still need to tighten this up further when plugged into the environment of your own code, including, among other things, exception handling for, but not limited to, registry access issues.

How can you automate Firefox from C# application?

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.

Categories