Selenium: Using the wrong element in for loop - c#

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 OpenQA.Selenium;
using OpenQA.Selenium.Support;
using OpenQA.Selenium.Chrome;
using System.Text.RegularExpressions;
using System.IO;
using OpenQA.Selenium.Support.UI;
namespace FlippaSearch
{
public partial class Form1 : Form
{
static IWebDriver driverGC;
public Form1()
{
driverGC = new ChromeDriver(#"Z:\Justin\Documents\Visual Studio 2015\chromedriver_win32");
driverGC.Navigate().GoToUrl("https://flippa.com/websites/starter-sites?sitetype=blog&uniques_per_month_min=1000");
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
List<IWebElement> starterSites = new List<IWebElement>();
List<String> myStarterSites = new List<string>();
IWait<IWebDriver> wait = new WebDriverWait(driverGC, TimeSpan.FromSeconds(30.00));
var numPages = (driverGC.FindElement(By.XPath("//*[#id='searchBody']/div[1]/div[1]/h2/span")).Text);
double numberPages = int.Parse(Regex.Match(numPages, #"\d+", RegexOptions.RightToLeft).Value);
numberPages = Math.Ceiling(numberPages / 50);
int j;
for (int i = 1; i <= numberPages; i++)
{
driverGC.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(30);
var mySites = driverGC.FindElements(By.CssSelector(".ListingResults___listingResult"));
int size = 1;
for (j = 0; j < 3; ++j)
{
driverGC.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(30);
mySites = driverGC.FindElements(By.CssSelector(".ListingResults___listingResult"));
size = mySites.Count();
driverGC.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(30);
String siteLink = " ";
siteLink = mySites[j].FindElement(By.CssSelector(".ListingResults___listingResultLink")).GetAttribute("href");
driverGC.Navigate().GoToUrl(siteLink);
driverGC.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
//testing tables
int row_tr = 5;
int Column_td = 3;
String CellValue;
String newCellValue;
String cellValueChange;
try
{
driverGC.FindElement(By.XPath("/html/body/div[3]/div[1]/div[1]/div[5]/div[1]/div/table[1]/tbody"));
for (int k = 1; k <= row_tr; k++)
{
for (int b = 1; b <= Column_td; b++)
{
CellValue = driverGC.FindElement(By.XPath("/html/body/div[3]/div[1]/div[1]/div[5]/div[1]/div/table[1]/tbody/tr[" + k + "]/td[" + b + "]")).Text.ToString();
if (CellValue == "Organic Search")
{
String mySiteName = driverGC.FindElement(By.XPath("/html/body/div[3]/div[1]/div[1]/div[1]/div[1]/h1")).Text.ToString();
newCellValue = driverGC.FindElement(By.XPath("/html/body/div[3]/div[1]/div[1]/div[5]/div[1]/div/table[1]/tbody/tr[" + k + "]/td[3]")).Text.ToString();
cellValueChange = Regex.Replace(newCellValue, #"[%\s]", string.Empty);
float organicSearch = float.Parse(cellValueChange);
if (organicSearch >= 50)
{
myStarterSites.Add(mySiteName);
myStarterSites.Add(CellValue);
myStarterSites.Add(newCellValue);
Console.WriteLine(mySiteName);
Console.WriteLine(CellValue);
Console.WriteLine(newCellValue);
}
}
}
}
}
catch (OpenQA.Selenium.NoSuchElementException)
{
}
//testing tables
driverGC.Navigate().Back();
//write shit to file
siteLink = "";
driverGC.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(30);
}
j = 0;
//mySites = null;
try
{
driverGC.FindElement(By.XPath("//*[#id='searchBody']/div[2]/div[2]/div/a[3]")).Click();
//driverGC.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(30);
}
catch (ElementNotVisibleException)
{
Console.WriteLine("No more pages");
}
}
using (StreamWriter writer = new StreamWriter(#"C:\Users\Justin\Desktop\newFile.txt"))
{
foreach (string s in myStarterSites)
{
writer.WriteLine(s + " ");// Writes in next line
writer.WriteLine(" ");
}
}
//MessageBox.Show("End");
driverGC.Quit();
Application.Exit();
}
}
}
Upon starting, the code will run fine on the first page. It grab's the elements, puts them in a list, and then i can gather the required information. Once it loops through the first page (i have it set to 3 strictly for testing reasons so its quicker) it will click next page, and then the next page loads and the loop begins again. The issue is, when the second page loads, the first element on the first page is being checked again, and then after that one is checked, it will go to the 2nd element on the 2nd page, and then continue on from there. My question is, how can i get it to scan the first element on the second page instead of redoing the first element on the first page again? I have tried using Waits but I cannot seem to get anything to work.
Thanks in advance.

It probably timing issue, the next loop iteration starts before the next page is actually loaded. You can use explicit wait and ExpectedConditions TextToBePresentInElementLocated on the page numbers to make sure the current page is what you actually need. You can do it by checking the number in the element with Pagination___activeLink class
driverGC.FindElement(By.XPath("//*[#id='searchBody']/div[2]/div[2]/div/a[3]")).Click(); // go to next page
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
wait.Until(ExpectedConditions.TextToBePresentInElementLocated(By.ClassName("Pagination___activeLink"), (i + 1).ToString()));

Related

When executing second for loop into listbox program populates no data

so the assignment is to read from the student file into an array and read into the answer key array, compare the two and output a grade based on the array comparison.
the issue i'm having is that when i try to load the answer key into it's array it's like its not even getting the data, because all the questions output as wrong.
below is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AshleyBrown_CPT185A01S_Chapter7Lab
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//variables
private const int SIZE = 20; //current # of q's on test
private int index = 0, count = 1; //counter variables
private int wrong = 0, right = 0; //grade variables
these are the arrays that are used for the answers:
//arrays
private char[] studentAnswers = new char[SIZE];
private char[] answerKey = new char[SIZE];
private void calculateBtn_Click(object sender, EventArgs e)
{
//prevents any file errors
try
{
ReadStudentFile();
ReadAnswerKey();
CompareAnswers();
}
catch
{
MessageBox.Show("File doesn't exist or has the wrong name.");
}
}
private void clearBtn_Click(object sender, EventArgs e)
{
//Clear Form
studentAListBox.Items.Clear();
correctAListBox.Items.Clear();
wrongAListBox.Items.Clear();
incorrectBox.Text = "";
correctBox.Text = "";
percentBox.Text = "";
}
private void exitBtn_Click(object sender, EventArgs e)
{
//close program
Close();
}
method for reading the student file that works:
private void ReadStudentFile()
{
//Stream Reader Setup
StreamReader studentFile;
studentFile = File.OpenText("C:\\Users\\aabro\\Documents\\_CPT 185\\AshleyBrown_CPT185A01S_Chapter7Lab\\Student File.txt");
//Read Student Answers into studentAnswers Array
while (index < studentAnswers.Length && !studentFile.EndOfStream)
{
studentAnswers[index] = char.Parse(studentFile.ReadLine());
index++;
}
//Close Student Answer file
studentFile.Close();
//Display Student Answers
foreach (char answer in studentAnswers)
{
studentAListBox.Items.Add(count + ". " + answer.ToString());
count++;
}
}
method for reading answer key that populates with no data:
private void ReadAnswerKey()
{
//Stream Reader Setup
StreamReader answerFile;
answerFile = File.OpenText("C:\\Users\\aabro\\Documents\\_CPT 185\\AshleyBrown_CPT185A01S_Chapter7Lab\\Answer Key.txt");
//Read Answer Key in answerKey Array
while (index < answerKey.Length && !answerFile.EndOfStream)
{
answerKey[index] = char.Parse(answerFile.ReadLine());
index++;
}
//Close answer key file
answerFile.Close();
//clear count
count = 1;
//display answer key in correct answer list box
foreach (char key in answerKey)
{
correctAListBox.Items.Add(count + ". " + key.ToString());
count++;
}
}
private void CompareAnswers()
{
//reset count
count = 1;
for (index = 0; index < answerKey.Length; index++)
{
//determine if answer is right
if (studentAnswers[index] != answerKey[index])
{
wrongAListBox.Items.Add(count + ". " + answerKey[index]);
wrong++;
count++;
}
}
//fail display
if (wrong > 5)
{
MessageBox.Show("Student has failed");
}
//calculations
double pointPerQ = 5;
double wrongTotal = wrong;
double wrongPointTotal = wrong * pointPerQ;
double grade = 100 - wrongPointTotal;
//output grade information
incorrectBox.Text = wrong.ToString();
correctBox.Text = right.ToString();
percentBox.Text = grade.ToString("p0");
}
}
}
this is the current output from running the program, I did double check the file names and contents as well.
output of current code
One issue that I saw in code is using of index in multiple while loops without previously assigning to 0.
I suggest using of local variables(variable which exists only in the current block of code).
Also in my opinion it will be good to declare and initialize new variable in for-loop like this:
for(int index = 0; index < answerKey.Length; index++)
{
// your code
}
it will be more readable and easier if you want later to separate loops in methods or move in service or helper.

Cannot get int to be displayed in text box for dice roller app

I'm trying to get back into programming and I'm having trouble getting the final int answers into the text boxes at the end. It has been a few years since I've coded, so if I messed up big time, please let me know.
{
int dice_total;
int dice_num;
int diff_num;
int succ_num = 0;
int ones = 0;
Boolean comp_num = false;
string Succ;
string Comp;
dice_total = int.Parse(Dice.Text);
diff_num = int.Parse(Diff.Text);
Random random = new Random();
dice_num = random.Next(dice_total);
if (dice_num >= diff_num)
{
succ_num++;
}
else
{
if (dice_num == 1)
{
ones++;
}
}
if (ones >= succ_num)
{
comp_num = true;
}
else
{
comp_num = false;
}
Succ = succ_num.ToString();
Comp = comp_num.ToString();
}```
[your text box name].Text=[some int].ToString();
For example:
label1.Text = product.BuyingPrice.ToString();
I can't seem to get it count up the successes. For those who don't know, WoD has you roll d10s and you are given a difficulty. You have to roll that difficulty number or higher to get successes. If there are more (or equal) 1s than total successes, its a complication. This isn't even including code for when you roll a 10 (which has you roll again while still counting as a success).
Ex. Roll 5d10s with a difficulty of 6
6, 8, 10, 1, 1 = 3 success
Roll again for the 10: 1
Total: 3 successes and a complication
using Accord.Math.Distances;
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 Roller
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int dice_total;
int dice_add;
int dice_num;
int diff_num;
int succ_num = 0;
int ones = 0;
Boolean comp_num = false;
public void button1_Click(object sender, EventArgs e)
{
dice_total = int.Parse(Dice.Text);
diff_num = int.Parse(Diff.Text);
for (dice_add = 0; dice_add < dice_total; dice_add++)
{
Random random = new Random();
dice_num = random.Next(dice_total);
if (dice_num >= diff_num)
{
succ_num++;
}
else
{
if (dice_num == 1)
{
ones++;
}
}
if (ones >= succ_num)
{
comp_num = true;
}
else
{
comp_num = false;
}
}
Succ.Text = succ_num.ToString();
Comp.Text = comp_num.ToString();
}
}
}

Bubble Sort using C# windows application form how to clear label.text every button click

Hi guys every time I pressed the button to generate the sorted string the output gets concatenated in the previous label output. I'm lost on how to clear the previous output on the label before showing the new one here's my 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 You_Source
{
public partial class Form1 : Form
{
string method;
public Form1()
{
InitializeComponent();
}
private void radio_checked(object sender, EventArgs e)
{
RadioButton radio = (RadioButton)sender;
method = radio.Text;
//label_Output.Text = method;
}
private void button_Sort_Click(object sender, EventArgs e)
{
string input = textBox_Input.Text;
label_Output.Clear();
if ( method == "Bubble Sort")
{
char[] charInput = input.ToCharArray();
char temp;
for (int j = 0; j <= charInput.Length - 2; j++)
{
for (int i = 0; i <= charInput.Length - 2; i++)
{
if (charInput[i] > charInput[i + 1])
{
temp = charInput[i + 1];
charInput[i + 1] = charInput[i];
charInput[i] = temp;
}
}
}
foreach (char letter in charInput)
label_Output.Text = label_Output.Text+letter;
}
}
}
can anyone give me a hint on what to do.
example( if i enter "cba" the output would be "abc", then when i entered another input in the text box "zyx" the new label output would be "abcxyz". I just one the new one "xyz" to be shown.
You can just set the string to "" at some point of your code, and overwrite it with the new string

getting a value from an image in C#

I am creating a project where random images show when i click a button and the total of the images (dice) will have to be guessed. I already have down the random image generating and keeping track of the persons amount of rolls. However; I cant figure out how to make a dice (image) have a certain value. Like dice 5 shows and has a value of 4. The person puts there guess in the guessBx and clicks on the guessBtn and it will pop up if they are correct or not.
Here is my code as of now:
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 PetalsAroundTheRose
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int a = 0;
int diceRoll;
int diceImage;
int diceValue;
private void btnRoll_Click_1(object sender, EventArgs e)
{
Random random = new Random();
picBx1.Image = imageList1.Images[random.Next(1, 6)];
picBx2.Image = imageList1.Images[random.Next(1, 6)];
picBx3.Image = imageList1.Images[random.Next(1, 6)];
picBx4.Image = imageList1.Images[random.Next(1, 6)];
a++;
txtBxRolls.Text = a.ToString();
//each dice seperate
//dice 1
diceRoll = 1;
diceImage = imageList1.Images[(1)];
diceValue = 0;
//dice 2
diceRoll = 1;
diceImage = imageList1.Images[(2)];
diceValue = 0;
//dice 3
diceRoll = 1;
diceImage = imageList1.Images[(3)];
diceValue = 2;
//dice 4
diceRoll = 1;
diceImage = imageList1.Images[(4)];
diceValue = 0;
//dice 5
diceRoll = 1;
diceImage = imageList1.Images[(5)];
diceValue = 4;
}
private void guessBx_TextChanged_1(object sender, EventArgs e)
{
}
}
}
On my design I have btnRoll for rolling the dice. guessBx for entering the guess, btnGuess, txtBxCorrect for the amount correct they got, and txtBxResult to say if they are correct or not
The images are in an imageList
Firstly i create a class with these two properties
public class Dice
{
public int Indexer { get; set; }
public string PhotoPath { get; set; }
public Dice(int indexer, string photoPath)
{
Indexer = indexer;
PhotoPath = photoPath;
}
}
After that i put in my form the picture boxes and then i created two methods
the first one:
public void SetUp()
{
for (int i = 1; i <= 6; i++)
{
temp = random.Next(1, 6);
dice = new Die(temp, "C:\\Users\\giorg\\Desktop\\dice\\dice" + temp + ".PNG");
dices.Add(dice); // list<Dice> dices = new list<Dice>();
}
}
and the second one:
public void RollDices()
{
//this is not necessary but if you want to keep a sum of dices keep
//it
var count = 0;
foreach (var dice in dices)
{
count += dice.Indexer;
}
//pictureboxes 2-7 are guess boxes
if(textBox2.Text.Equals(dices[0].Indexer.ToString()))
pictureBox1.Image = Image.FromFile(dices[0].PhotoPath);
if (textBox3.Text.Equals(dices[1].Indexer.ToString()))
pictureBox2.Image = Image.FromFile(dices[1].PhotoPath);
if (textBox4.Text.Equals(dices[2].Indexer.ToString()))
pictureBox3.Image = Image.FromFile(dices[2].PhotoPath);
if (textBox5.Text.Equals(dices[3].Indexer.ToString()))
pictureBox4.Image = Image.FromFile(dices[3].PhotoPath);
if (textBox6.Text.Equals(dices[4].Indexer.ToString()))
pictureBox5.Image = Image.FromFile(dices[4].PhotoPath);
if (textBox7.Text.Equals(dices[5].Indexer.ToString()))
pictureBox6.Image = Image.FromFile(dices[5].PhotoPath);
}
Put these two methods to your button click event and you are ok...
Inform me if you are ok with this approach.

How do I determine if a file contains a specific class in SrcML.Net

I want to display if the Android "ServiceTestCase" Class is being used in any of the Directories.
The Program currently
1) Displays the Sensor Types the File uses
2) Displays the number of Implementations of the "onSensorChanged" Method
3) Displays the other functions that call the "onSensorChange" Implementation.
How do I display Classes?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ABB.SrcML;
using ABB.SrcML.Data;
using NUnit.Framework;
using System.Collections;
namespace CodeAnalysisToolkit
{
[TestFixture]
public class SimpleAnalyticsCalculator_Thesis
{
//------Test Case Class------------------------------------------------------------------------
[TestCase]
public void CalculateSimpleProjectStats()
{
int NumOfApps = 5;
//-----------Current Working Method to Get sub directories -------------------------
// Get list of files in the specific directory.
string[] TopDirectories = Directory.GetDirectories(#"C:\School\Grad School (Comp Sci)\Thesis\Apps\",
"*.*",
SearchOption.TopDirectoryOnly);
// Display all the files.
//for (int i = 0; i <= NumOfApps; i++)
//{
// Console.WriteLine(TopDirectories[i]);
//}
//Print out all Top Sub Directoies for Specified Path
//foreach (string file in TopDirectories)
//{
// Console.WriteLine(file);
//}
//----------End of Print Sub directory Method----------------------------------------
for (int i = 0; i < NumOfApps; i++)
{
var dataProject = new DataProject<CompleteWorkingSet>(TopDirectories[i],
Path.GetFullPath(TopDirectories[i]),
"..//..//..//SrcML");
Console.WriteLine();
Debug.WriteLine("#############################################");
Debug.WriteLine("Parsing " + TopDirectories[i]);
dataProject.UpdateAsync().Wait();
NamespaceDefinition globalNamespace;
Assert.That(dataProject.WorkingSet.TryObtainReadLock(5000, out globalNamespace));
DisplaySensorTypes(globalNamespace);
//DisplayWhetherAppIsUnitTested();
DisplayCallsToOnSensorChanged(globalNamespace);
}
}
//-------Display Sensor Type Class--------------------------------------------------------------
private void DisplaySensorTypes(NamespaceDefinition globalNamespace)
{
var getDefaultSensorCalls = from statement in globalNamespace.GetDescendantsAndSelf()
from expression in statement.GetExpressions()
from call in expression.GetDescendantsAndSelf<MethodCall>()
where call.Name == "getDefaultSensor"
select call;
foreach (var call in getDefaultSensorCalls)
{
if (call.Arguments.Any())
{
var firstArg = call.Arguments.First();
var components = firstArg.Components;
if (components.Count() == 3 &&
components.ElementAt(0).ToString() == "Sensor" &&
components.ElementAt(1).ToString() == ".")
{
Debug.WriteLine("sensor " + components.ElementAt(2).ToString() + " found");
}
}
}
}
private void DisplayWhetherAppIsUnitTested()
{
throw new NotImplementedException();
}
//-------Display Calls to OnSensorChanged Class------------------------------------------------
private void DisplayCallsToOnSensorChanged(NamespaceDefinition globalNamespace)
{
var senChangedMethods = from method in globalNamespace.GetDescendants<MethodDefinition>()
where method.Name == "onSensorChanged"
select method;
if (senChangedMethods.Count() == 0)
{
Debug.WriteLine("This File Does not contain any Sensor Change Mehtods");
}
else
{
Debug.WriteLine("----- ");
Debug.WriteLine("\r\n");
Debug.WriteLine(senChangedMethods.Count() + " Implementations of " + senChangedMethods.First().GetFullName());
Debug.WriteLine("----- ");
int n = senChangedMethods.Count();
for (int i = 0; i < n; i++)
{
var senChangedMethod = senChangedMethods.ElementAt(i);
Debug.WriteLine("Implementations of onSensorChaged # " + (i + 1) + ": " + senChangedMethod.GetFullName());
//"GetCallsToSelf" returns the number of times the number is called
var callsToSenChanged = senChangedMethod.GetCallsToSelf();
for (int j = 0; j < callsToSenChanged.Count(); j++)
{
var callerMethod = callsToSenChanged.ElementAt(j).ParentStatement.GetAncestorsAndSelf<MethodDefinition>();
if (callerMethod.Any())
{
Debug.WriteLine(" Called by --> " + callerMethod.ElementAt(0).GetFullName());
}
}
//Debug.WriteLine("----- ");
}
} //End of Else does not Equal 0 Check
}
//-------Display Test Class--------------------------------------------------------------
}
}

Categories

Resources