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.
Related
Using DJI Mavic Air
https://developer.dji.com/windows-sdk/documentation/tutorials/index.html
Using this guide i am Integrating DJIVideoParsel, at the end,Build is successful but output is a failure because of an issue shows up.
i have Added the Error Text and The Code, if i need to add something else please do tell. Also the code shows no error until i build it.
Error Text:
$exception {"The specified module could not be found. (Exception from HRESULT: 0x8007007E)":null} System.IO.FileNotFoundException
this {DJIWSDKDemo.MainPage} DJIWSDKDemo.MainPage
type {DJI.WindowsSDK.ResultValue<DJI.WindowsSDK.CameraTypeMsg?>} DJI.WindowsSDK.ResultValue<DJI.WindowsSDK.CameraTypeMsg?>
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using DJI.WindowsSDK;
using DJIVideoParser;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace DJIWSDKDemo
{
///
/// An empty page that can be used on its own or navigated to within a Frame.
///
public sealed partial class MainPage : Page
{
//use videoParser to decode raw data.
private DJIVideoParser.Parser videoParser;
//raw data
void OnVideoPush(VideoFeed sender, byte[] bytes)
{
videoParser.PushVideoData(0, 0, bytes, bytes.Length);
}
//Decode data. Do nothing here. This function would return a bytes array with image data in RGBA format.
async void ReceiveDecodedData(byte[] data, int width, int height)
{
}
//We need to set the camera type of the aircraft to the DJIVideoParser. After setting camera type, DJIVideoParser would correct the distortion of the video automatically.
private void OnCameraTypeChanged(object sender, CameraTypeMsg? value)
{
if (value != null)
{
switch (value.Value.value)
{
case CameraType.MAVIC_2_ZOOM:
this.videoParser.SetCameraSensor(AircraftCameraType.Mavic2Zoom);
break;
case CameraType.MAVIC_2_PRO:
this.videoParser.SetCameraSensor(AircraftCameraType.Mavic2Pro);
break;
default:
this.videoParser.SetCameraSensor(AircraftCameraType.Others);
break;
}
}
}
public MainPage()
{
this.InitializeComponent();
DJISDKManager.Instance.SDKRegistrationStateChanged += Instance_SDKRegistrationEvent;
//Replace with your registered App Key. Make sure your App Key matched your application's package name on DJI developer center.
DJISDKManager.Instance.RegisterApp("bb291a0f01c8567c7c7200fb");
}
//Callback of SDKRegistrationEvent
private async void Instance_SDKRegistrationEvent(SDKRegistrationState state, SDKError resultCode)
{
if (resultCode == SDKError.NO_ERROR)
{
System.Diagnostics.Debug.WriteLine("Register app successfully.");
//Must in UI Thread
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
//Raw data and decoded data listener
if (videoParser == null)
{
videoParser = new DJIVideoParser.Parser();
videoParser.Initialize(delegate (byte[] data)
{
//Note: This function must be called because we need DJI Windows SDK to help us to parse frame data.
return DJISDKManager.Instance.VideoFeeder.ParseAssitantDecodingInfo(0, data);
});
//Set the swapChainPanel to display and set the decoded data callback.
videoParser.SetSurfaceAndVideoCallback(0, 0, swapChainPanel, ReceiveDecodedData);
DJISDKManager.Instance.VideoFeeder.GetPrimaryVideoFeed(0).VideoDataUpdated += OnVideoPush;
}
//get the camera type and observe the CameraTypeChanged event.
DJISDKManager.Instance.ComponentManager.GetCameraHandler(0, 0).CameraTypeChanged += OnCameraTypeChanged;
var type = await DJISDKManager.Instance.ComponentManager.GetCameraHandler(0, 0).GetCameraTypeAsync();
OnCameraTypeChanged(this, type.value);
});
}
else
{
System.Diagnostics.Debug.WriteLine("SDK register failed, the error is: ");
System.Diagnostics.Debug.WriteLine(resultCode.ToString());
}
}
}
}
I need to create an Windows Service that will capture images from camera. After serching the internet, i do not find any similar project. I decided to use Aforge.net but got stuck in how to capture image because the Bitmap is not supported in windows Service.
here is my code so far:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Deployment;
using System.Runtime.InteropServices;
using AForge.Video;
using AForge.Video.DirectShow;
using AForge.Imaging;
namespace PCSecurityCamera
{
partial class PCSecurityCamera : ServiceBase
{
System.Timers.Timer timeDelay;
string pixDrive = "", journalLoc = "", txnDate = "", txnTime = "", txnDate1 = "";
int retVal, timeFrame = 0, count = 0, txn_count = 0, retention = 0;
string picdirectory;
int i = 0;
string[] availableCameras = new string[5];
private FilterInfoCollection VideoCaptureDevices; //stores all available camera
private VideoCaptureDevice FinalVideoSource; //stores camera to be used
public PCSecurityCamera()
{
InitializeComponent();
timeDelay = new System.Timers.Timer();
timeDelay.Elapsed += new System.Timers.ElapsedEventHandler(WorkProcess);
}
public void WorkProcess(object sender, System.Timers.ElapsedEventArgs e)
{
}
protected override void OnStart(string[] args)
{
// TODO: Add code here to start your service.
LogService("PCSecuritycamera Service is Started");
try
{
int camCount = 0;
Array.Clear(availableCameras,0,availableCameras.Length);
VideoCaptureDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach(FilterInfo VideoCaptureDevice in VideoCaptureDevices)
{
availableCameras[camCount] = VideoCaptureDevice.Name.ToString();
LogService(availableCameras[camCount]);
camCount++;
}
if (availableCameras[0] == "")
{
LogService("No Available Camera");
}
else
{
FinalVideoSource = new VideoCaptureDevice(VideoCaptureDevices[0].MonikerString);
LogService("Camera Selected: " + FinalVideoSource.ToString());
FinalVideoSource.NewFrame +=FinalVideoSource_NewFrame;
}
}
catch (Exception e)
{
LogService(e.ToString());
}
timeDelay.Enabled = true;
}
private void FinalVideoSource_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
}
protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
LogService("Service Stoped");
timeDelay.Enabled = false;
}
private void LogService(string content)
{
FileStream fs = new FileStream(#"C:\Users\talatj\Desktop\Me\ServiceLog.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.BaseStream.Seek(0, SeekOrigin.End);
sw.WriteLine(content);
sw.Flush();
sw.Close();
}
}
}
my problem is how to capture the image in windows service.
Please help
System.Drawing Namespace
Classes within the System.Drawing namespace are not supported for use
within a Windows or ASP.NET service. Attempting to use these classes
from within one of these application types may produce unexpected
problems, such as diminished service performance and run-time
exceptions. For a supported alternative, see Windows Imaging
Components.
GDI+
GDI+ functions and classes are not supported for use within a Windows
service. Attempting to use these functions and classes from a Windows
service may produce unexpected problems, such as diminished service
performance and run-time exceptions or errors
HOWEVER!
System.Drawing does work in Services, it's just not supported. There can be issues with high load (running out of unmanaged resources), memory or resource leaks (badly implemented or called dispose patterns)
My suspicions is you have just not referenced the System.Drawing.dll
Note : You will just have to be wary and do this on a trial and error basis, though IMO saving bitmaps should be fine
I have some PDFs which I would like to fill out automatically using C#. I know about iTextSharp, but I am unsure about licensing issues for business use, and would rather find a different solution.
Basically, I would like to open a PDF, specify the field (or give coordinates for a textbox) and be able to insert text (& possibly small images?). Then I need to merge and save the pdf.
Any suggestions for a good way to accomplish this where I don't have to purchase / worry about licenses?
Not sure what the advantages of iTextSharp are, but I found a solution that is working perfectly so far using PDFSharp! As documentation seems to be a little on the light side for PDFSharp, I also found this thread to be very helpful...
If this helps anybody, here is my sample program:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using PdfSharp.Fonts;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using PdfSharp.Pdf.AcroForms;
namespace PDFSharpTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void goButton_Click(object sender, EventArgs e)
{
//TestPDF(); //uncomment this to find out whether acroform will work correctly
//open file
PdfDocument pdf = PdfReader.Open(#"YOURFILEPATHandNAME", PdfDocumentOpenMode.Modify);
//fix some odd setting where filled fields don't always show SetupPDF(pdf);
//find and fill fields
PdfTextField txtEmployerName = (PdfTextField)(pdf.AcroForm.Fields["txtEmployerName"]);
txtEmployerName.Value = new PdfString("My Name");
PdfTextField txtEmployeeTitle = (PdfTextField)(pdf.AcroForm.Fields["txtEmployeeTitle"]);
txtEmployeeTitle.Value = new PdfString("Workin'");
PdfCheckBoxField chxAttached = (PdfCheckBoxField)(pdf.AcroForm.Fields["chxAttached"]);
chxAttached.Checked = true;
//save file
pdf.Save(#"NEWFILEPATHandNAMEHERE");
}
private void SetupPDF(PdfDocument pdf)
{
if (pdf.AcroForm.Elements.ContainsKey("/NeedAppearances") == false)
{
pdf.AcroForm.Elements.Add("/NeedAppearances", new PdfSharp.Pdf.PdfBoolean(true));
}
else
{
pdf.AcroForm.Elements["/NeedAppearances"] = new PdfSharp.Pdf.PdfBoolean(true);
}
}
private void PDFTest()
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
PdfDocument _document = null;
try { _document = PdfReader.Open(ofd.FileName, PdfDocumentOpenMode.Modify); }
catch (Exception ex)
{
MessageBox.Show(ex.Message, "FATAL"); //do any cleanup and return
return;
}
if (_document != null)
{
if (_document.AcroForm != null)
{
MessageBox.Show("Acroform is object", "SUCCEEDED");
//pass acroform to some function for processing
_document.Save(#"C:\temp\newcopy.pdf");
}
else
{
MessageBox.Show("Acroform is null", "FAILED");
}
}
else
{
MessageBox.Show("Unknown error opening document", "FAILED");
}
}
}
}
}
This is a free and open source solution: SharpPDF
But in all honesty iTextSharp is probably the best thing you'll find.
You might try Docotic.Pdf library for your task. The library is not free but probably there is nothing to worry about (licensing wise).
Here are samples available online that might help you:
Fill existing form
Find control by name
Other samples from Forms and Annotations group could also prove to be useful in your case.
Disclaimer: I work for the vendor of the library.
Can I maybe get some help with this? As I am very confused. I copy-pasted an XOR encryption class, and I XOR encrypted the download link to my Minecraft Mod Installer .exe hosted on my website. However when I wrote the following code I always got an error because the text input isn't a proper Uri. Is there a way I can make this work?
SSCCE below
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using System.Net;
private void startButton_Click(object sender, EventArgs e)
{
startButton.Enabled = false;
WebClient client = new WebClient();
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted);
client.DownloadDataAsync(new Uri(EncryptorDecryptor.EncryptDecrypt("8a33b8a537d4e17ec4ac7041df43d892821c16dc15cf84fb33a672ab76c72119126f9c4849cf55423b0112c4b4")), Path.GetTempPath() + "mcmodinstaller.exe");
}
void client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
MessageBox.Show("Successful!",
"Download",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
Process.Start(Path.GetTempPath() + "mcmodinstaller.exe");
startButton.Enabled = true;
}
void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
downloadBar.Maximum = (int)e.TotalBytesToReceive / 100;
downloadBar.Value = (int)e.BytesReceived / 100;
}
public static class EncryptorDecryptor
{
public static int key = 3;
public static string EncryptDecrypt(string textToEncrypt)
{
StringBuilder inSb = new StringBuilder(textToEncrypt);
StringBuilder outSb = new StringBuilder(textToEncrypt.Length);
char c;
for (int i = 0; i < textToEncrypt.Length; i++)
{
c = inSb[i];
c = (char)(c ^ key);
outSb.Append(c);
}
return outSb.ToString();
}
}
}
Thanks in advance, I'm very new to C# and this is my first real project.
Where did you get 8a33b8a537d4e17ec4ac7041df43d892821c16dc15cf84fb33a672ab76c72119126f9c4849cf55423b0112c4b4 from?
Running it through the decoder with the specified key of '3' gives:
;0ab0gf4b47g7g:;22g2;e0b4b41225:7767032`a
Clearly nothing like a valid URI. I've tried a couple of quick things to see if I can get something sensible out (like converting the value from hex to bytes) but nothing reasonable appears.
If you're new to C# and this is your first real project, you should break it down into much easier pieces. Make sure you can take any string, encode it with the EncryptorDecryptor and then decode the result to get the same value. Then, set aside the encryption and make sure you can download any normal file from your site. When you have both working (and understand how they work and more importantly, how they behave when they fail) combine the two.
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.