Need to click on a button in iFrame page - winforms

I am trying to click on "btnPunch". This button is located in an iFrame. I am unable to make this work. I have used the Selenium IDE to record this button being clicked and created a DLL that also runs this process in NUnit without a problem. Any help would be appreciated after three months of working on this.
Thank you
using System;
using System.IO;
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.Net;
using System.Threading;
using NUnit.Framework;
using Selenium;
using OpenQA.Selenium.IE;
using OpenQA.Selenium;
namespace TimeClockEntry
{
public partial class PNow : Form
{
IWebDriver driver = new InternetExplorerDriver();
//driver = new InternetExplorerDriver();
//private ISelenium selenium;
//private StringBuilder verificationErrors;
//public void SetupTest()
//{
// selenium = new DefaultSelenium("localhost", 4444, "*chrome", "https://ew23.ultipro.com/");
// selenium.Start();
// verificationErrors = new StringBuilder();
//}
int linkcount = 0;
string userName;
string passWord;
public PNow()
{
InitializeComponent();
webBrowser1.Navigate("https://ew23.ultipro.com/login.aspx");
}
private void PNow_Load(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Normal;
userName = Properties.Settings.Default.userName;
passWord = Properties.Settings.Default.passWord;
}
private void PNow_FormClosed(object sender, FormClosedEventArgs e)
{
this.Hide();
welcome f1 = new welcome();
f1.ShowDialog();
this.Close();
}
protected override void OnLostFocus(EventArgs e)
{
base.OnLostFocus(e);
this.Focus();
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
linkcount++;
if (linkcount == 1)
{
webBrowser1.Document.GetElementById("ctl00_Content_Login1_UserName").SetAttribute("value", userName);
webBrowser1.Document.GetElementById("ctl00_Content_Login1_Password").SetAttribute("value", passWord);
webBrowser1.Document.GetElementById("ctl00_Content_Login1_LoginButton").InvokeMember("click");
}
if (linkcount == 2)
{
HtmlElement link = (from HtmlElement elem in webBrowser1.Document.GetElementsByTagName("a")
where elem.InnerHtml == "Time Clock Entry"
select elem).ElementAt(0);
link.InvokeMember("Click");
}
if (linkcount == 3)
{
// driver.FindElement(By.Id("btnPunch")).Click();
webBrowser1.Document.GetElementById("ctl00_Content_lnkLogout").InvokeMember("click");
this.Close();
}
}
}
}

You can try this also:-
if (linkcount == 3)
{
WebElement frameSwitch = driver.findElement(By.xpath("Xpath of iframe")); //Frame Xpath
driver.switchTo().frame(frameSwitch);
driver.FindElement(By.Id("btnPunch")).Click();
webBrowser1.Document.GetElementById("ctl00_Content_lnkLogout").InvokeMember("click");
driver.switchTo().defaultContent();
this.Close();
}

Try this.
if (linkcount == 3)
{
//get back to basic html source.
driver.SwitchTo().DefaultContent();
//switch to new frame
driver.SwitchTo().Frame("<FRAME NAME OR ID>");
driver.FindElement(By.Id("btnPunch")).Click();
}

Related

WinForms: DataGridView with E.F. does not show New Row

I have a simple WinForm with a DataGridView that shows record with Entity Framework.
My problem is that New Row feature appears only if the DataGridView is empty.
How is the problem?
Thank you in advance.
Luis
PS
Here some details of the WinForm class:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using GestioneFormazione;
namespace MpFormazione
{
public partial class MpFormazione : Form
{
public MpFormazione()
{
InitializeComponent();
this.dataGridView1.CellClick += DataGridView1_CellClick;
this.dataGridView1.AllowUserToAddRows = true;
this.dataGridView1.VirtualMode = true;
this.dataGridView1.AutoGenerateColumns = false;
}
private void DataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == this.ButtonColumunIndex)
{
if (e.RowIndex == 0)
{
Cliente cliente = new Cliente();
cliente.ID = Guid.NewGuid();
if (dataGridView1.Rows[0].Cells[1].Value != null)
cliente.Nome = dataGridView1.Rows[0].Cells[1].Value.ToString();
SaveToDb(cliente);
}
}
}
private void SaveToDb(Cliente cliente)
{
using (var context = new MPFORMAZIONEEntities())
{
context.Cliente.Add(cliente);
context.SaveChanges();
}
}
private void clienteBindingSource_CurrentChanged(object sender, EventArgs e)
{
}
private void ClienteBindingSource_AddingNew(object sender, System.ComponentModel.AddingNewEventArgs e)
{
}
private int ButtonColumunIndex
{
get
{
return 2;
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void MpFormazione_Load(object sender, EventArgs e)
{
using (var context = new MPFORMAZIONEEntities())
{
this.dataGridView1.DataSource = context.Cliente.ToList<Cliente>();
}
}
}
}
The page has only this code, and the Entity Framework for "Cliente" and "Dipendente" entities.

How to disable comboBox autoselection attribute when Textupdated

I want a comboBox to autocomplete and I found the below code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace testcomboBox
{
public partial class Form1 : Form
{
List<string> listOnit = new List<string>() { "Stephen_Curry", "Kevin_Durant", "Draymond_Green", "Zaza_Pachulia","Gerald Green" };
List<string> listSearchUpdate = new List<string>();
public Form1()
{
InitializeComponent();
}
private void comboBox1_TextUpdate(object sender, EventArgs e)
{
comboBox1.Items.Clear();
listSearchUpdate.Clear();
foreach (var item in listOnit)
{
if (item.Contains(comboBox1.Text))
{
listSearchUpdate.Add(item);
}
}
comboBox1.Items.AddRange(listSearchUpdate.ToArray());
comboBox1.SelectionStart = comboBox1.Text.Length;
Cursor = Cursors.Default;
comboBox1.DroppedDown = true;
}
}
}
The code has a bug When type letter "G",the comboBox immediately autoselects "Gerald Green" and fills it to the edit control of the comboBox,but if you type "G" again,the edit control just fine to show "G" and pop up list of "Draymond_Green" and "Gerald Green". So how to disable autoselection function when type string in the edit control of the comboBox?
refer to this linkenter link description here
I revised code below and it is ok.
private void comboBox1_TextUpdate(object sender, EventArgs e)
{
comboBox1.Items.Clear();
listSearchUpdate.Clear();
string strTemp = string.Empty;
foreach (var item in listOnit)
{
if (item.Contains(comboBox1.Text))
{
strTemp = comboBox1.Text;
listSearchUpdate.Add(item);
}
}
comboBox1.Items.AddRange(listSearchUpdate.ToArray());
comboBox1.DroppedDown = true;
comboBox1.SelectionStart = strTemp.Length;
Cursor = Cursors.Default;
}

How to write a NUnit test case for windows forms Application?

The following is my Calculator program.How can i write a NUnit test case for add
functionality?
I want create a separate project for as CalculatorTest and there i want access Form1 by creating an object for Form1.
Here i am unable to create an object for Form1 in CalculatorTest.
Note:I have added references of nunit and my calculator namespace.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
namespace Calculater
{
public partial class Form1 : Form
{
double value;
string operator_clicked;
bool isResult = false;
public Form1()
{
InitializeComponent();
txtresult.Text = "0";
}
private void btn1_Click(object sender, EventArgs e)
{
if (txtresult.Text == "0" || isResult)
{
txtresult.Clear();
isResult = false;
}
Button btn = (Button)sender;
txtresult.Text = txtresult.Text + btn.Text;
}
private void btnclr_Click(object sender, EventArgs e)
{
txtresult.Text="0";
value = 0;
}
private void btnequal_Click(object sender, EventArgs e)
{
if(value>=0 && txtresult.Text!=string.Empty)
{
switch(operator_clicked)
{
case "+":
txtresult.Text = (value + double.Parse(txtresult.Text)).ToString();
break;
case "-":
txtresult.Text = (value - double.Parse(txtresult.Text)).ToString();
break;
case "X":
txtresult.Text = (value * double.Parse(txtresult.Text)).ToString();
break;
case "/":
try
{
txtresult.Text = (value / double.Parse(txtresult.Text)).ToString();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
txtresult.Clear();
}
break;
}
txttop.Clear();
isResult = true;
}
}
private void btnOperator_Click(object sender, EventArgs e)
{
if(txtresult.Text!=string.Empty)
{
Button btnOperator = (Button)sender;
txttop.Text = txtresult.Text + btnOperator.Text;
operator_clicked = btnOperator.Text;
value = double.Parse(txtresult.Text);
txtresult.Clear();
}
else
{
MessageBox.Show("Please enter any number");
}
}
}
}

Devexpress: An object reference is required for the non-static field

I keep getting this error in my devexpress code.
Here is the code I have put in:
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Collections;
using System.ComponentModel;
using DevExpress.XtraReports.UI;
using System.Drawing.Printing;
namespace DD
{
public partial class MasterReport : DevExpress.XtraReports.UI.XtraReport
{
//detailReport.catName.Value = ((DataRowView)e.Brick.Value).Row["EcoYear"].ToString();
public MasterReport()
{
InitializeComponent();
}
private void xrLabel1_BeforePrint(object sender, PrintEventArgs e)
{
// XRLabel l = sender as XRLabel;
// l.Tag = GetCurrentRow();
((XRLabel)sender).Tag = GetCurrentRow();
}
private void xrLabel1_PreviewClick(object sender, PreviewMouseEventArgs e)
{
DetailReport detailReport = new DetailReport();
detailReport.CaID.Value = (int)((DataRowView)e.Brick.Value).Row["CaseID"];
detailReport.EYear.Value = (int)((DataRowView)e.Brick.Value).Row["EcoYear"];
detailReport.ShowPreviewDialog();
}
private void xrLabel1_PreviewMouseMove(object sender, PreviewMouseEventArgs e)
{
Cursor.Current = Cursors.Hand;
}
private void xrPictureBox1_BeforePrint(object sender, PrintEventArgs e)
{
((XRLabel)sender).Tag = GetCurrentRow();
}
private void xrPictureBox1_PreviewClick(object sender, PreviewMouseEventArgs e)
{
PW pw = new PW();
PW.CaID.Value = (int)((DataRowView)e.Brick.Value).Row["CaseCaseID"];
PW.ShowPreviewDialog();
}
private void xrPictureBox1_PreviewMouseMove(object sender, PreviewMouseEventArgs e)
{
Cursor.Current = Cursors.Hand;
}
}
}
The PW.CaID.Value and the PW.ShowPreviewDialog(); are the lines that are giving me this error. Perhaps I am doing this the wrong way. What I wanted to do is click an icon (xrPictureBox1) on the main report and have it bring up the subreport (PW). I have done this in the code above for another subreport (detailreport). Thank you in advance for your help.
Your code should read:
PW pw = new PW();
pw.CaID.Value = (int)((DataRowView)e.Brick.Value).Row["CaseCaseID"];
pw.ShowPreviewDialog();
Note the case on PW/pw.

OpenFileDialog in SilverLight?

I have download the code for OpenFileDialog (File Upload function) from Silverlight tutorials website. I am creating a silverlight application using ESRI API and I would like to incorporate the file upload functionality in to it. I have replicated the exact code in to my application there are no errors when I run it, but for some reason my application dosen't execute this line of code "c.OpenWriteAsync(Ub.Uri)"
Edit 2: I notice another thing when I upgraded the general handler (receiver.ashx) which I downloaded it has the following as first line while my generic handler doesn't
<%# WebHandler Language="C#" Class="receiver" %>
I dont know why my code dosent trigger it :(
Here is my Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Markup;
using System.Windows.Shapes;
using System.ComponentModel;
using ESRI.ArcGIS.Client;
using System.Windows.Controls.Primitives;
using System.IO;
using System.IO.IsolatedStorage;
namespace DataTool
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
// HtmlPage.RegisterScriptableObject("SilverlightLearn", this);
}
[ScriptableMember]
private void btnService_Click(object sender, RoutedEventArgs e)
{
}
private void btnUpload_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog Dialog = new OpenFileDialog();
Dialog.Multiselect = false;
Dialog.Filter = "All Files|*.*";
bool? SelFil = Dialog.ShowDialog();
if (SelFil != null && SelFil == true)
{
string selectedfilename = Dialog.File.Name;
UploadFile(selectedfilename, Dialog.File.OpenRead());
}
else
{
//do something else
}
}
private void StoreIso(string fileName, Stream data)
{
}
private void UploadFile(string fileName, System.IO.Stream data)
{
// WebClient Wbc = new WebClient();
UriBuilder Ub = new UriBuilder("http://localhost:63461/DataTool/datareceiver.ashx");
Ub.Query = string.Format("filename={0}", fileName);
WebClient c = new WebClient();
c.OpenWriteCompleted += (sender, e) =>
{
PushData(data, e.Result);
e.Result.Close();
data.Close();
};
c.OpenWriteAsync(Ub.Uri);
}
private void PushData(Stream input, Stream output)
{
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
{
output.Write(buffer, 0, bytesRead);
}
}
}
}
Here is my datareceiver.ashx code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
namespace DataTool.Web
{
/// <summary>
/// Summary description for datareceiver
/// </summary>
public class datareceiver : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string filename = context.Request.QueryString["filename"].ToString();
using (FileStream fs = File.Create(context.Server.MapPath("~/App_Data/" + filename)))
{
SaveFile(context.Request.InputStream, fs);
}
}
public void SaveFile(Stream st, FileStream fs)
{
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = st.Read(buffer, 0, buffer.Length)) != 0)
{
fs.Write(buffer, 0, bytesRead);
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
I have gone through the downloaded sample code and my code STEP BY STEP and found that my code dosent execute the OpenWriteAsync statement. The downloaded code was in .net 3.5 or 3.0 framework and I upgraded it to 4.0.
EDIT:
Please find a sample here https://rapidshare.com/files/459667631/Testing.zip
This is simple , check following code
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Text Files (*.txt)|*.txt";
if (dlg.ShowDialog() == DialogResult.OK)
{
using (StreamReader reader = dlg.SelectedFile.OpenText())
// Store file content in 'text' variable
string text = reader.ReadToEnd();
}
}
C# Example 2: Copy files to the application's isolated storage.
using System.Windows.Controls;
using System.IO;
using System.IO.IsolatedStorage;
...
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "All files (*.*)|*.*";
dlg.EnableMultipleSelection = true;
if (dlg.ShowDialog() == DialogResult.OK) {
// Save all selected files into application's isolated storage
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
foreach (FileDialogFileInfo file in dlg.SelectedFiles) {
using (Stream fileStream = file.OpenRead()) {
using (IsolatedStorageFileStream isoStream =
new IsolatedStorageFileStream(file.Name, FileMode.Create, iso)) {
// Read and write the data block by block until finish
while(true) {
byte[] buffer = new byte[100001];
int count = fileStream.Read(buffer, 0, buffer.Length);
if (count > 0) {
isoStream.Write(buffer, 0, count);
}
else {
break;
}
}
}
}
}
}

Resources