selenium c# - c#

Hi all I am using this function to get name's of the input fields from browser. Problem is that in couple of my sites input fields have the same position, so i cant cycle thrue them correctly. Any ideas how to do this cycle in some different way as thrue position?
Thank you.
public void hladame_fieldy ()
{
//fieldy
string nazov_fieldu;
decimal celkovy_pocet_fieldov = selenium.GetXpathCount ("//input[#type='text']");
string field = "#type='text'";
int b = 1;
for (b = 1;b<=celkovy_pocet_fieldov;b++)
{
nazov_fieldu = selenium.GetAttribute("xpath=//input[position()="+b+" and "+field+"]#name");
Console.WriteLine(nazov_fieldu);
}
Console.WriteLine ("Celkovy pocet fieldov je = " + celkovy_pocet_fieldov);
}

Since you have the amount of elements you can just go through them as an array
public void hladame_fieldy ()
{
//fieldy
string nazov_fieldu;
decimal celkovy_pocet_fieldov = selenium.GetXpathCount ("//input[#type='text']");
string field = "#type='text'";
int b = 1;
for (b = 1;b<=celkovy_pocet_fieldov;b++)
{
nazov_fieldu = selenium.GetAttribute("xpath=//input[" + b + "]#name");
Console.WriteLine(nazov_fieldu);
}
Console.WriteLine ("Celkovy pocet fieldov je = " + celkovy_pocet_fieldov);
}
That way you just go through all the input elements in the DOM from top to bottom.

final solution:
public void hladame_fieldy ()
{
//fieldy
string nazov_fieldu;
decimal celkovy_pocet_fieldov = selenium.GetXpathCount ("//input[#type='text']");
int b = 1;
string pomoc = "";
for (b = 1;b<=celkovy_pocet_fieldov;b++)
{
nazov_fieldu = selenium.GetAttribute("xpath=//input[#type='text'" + pomoc +"]#name");
pomoc = pomoc + " and #name!= '" + nazov_fieldu + "'";
Console.WriteLine(nazov_fieldu);
}
Console.WriteLine ("Celkovy pocet fieldov je = " + celkovy_pocet_fieldov);
}

Related

How to make a number string decrement based on the value of the number

I want the the timeToString values change based on the count changing.So when the count of seconds decrement the second.Count.ToString("59") should decrement to "58".In the debug the PondoreCount function is working as expected, however I can't see the value decrementing in the console.
public class PonodoreTimer : Clock
{
private Clock _seconds;
private Clock _minutes;
public PonodoreTimer()
{
_seconds = new Clock();
_minutes = new Clock();
_seconds.Count = 59;
_minutes.Count = 24;
// string timeToString = _minutes.Count.ToString("24") + ":" + _seconds.Count.ToString("59");
}
public string PondoreTimerInString()
{
string timeToString = _minutes.Count.ToString("24") + ":" + _seconds.Count.ToString("59");
return timeToString;
}
public void PonodoreCount()
{
//string timeToString = _minutes.Count + ":" + _seconds.Count;
//Console.WriteLine(timeToString);
while (_minutes.Count != 0)
{
_seconds.Decrement();
if(_seconds.Count == 0)
{
_minutes.Decrement();
_seconds.Count = 59;
}
}
}
}
The whole thing can be replaced by:
var ts = TimeSpan.FromMinutes(25);
var one = TimeSpan.FromSeconds(1);
while(ts > TimeSpan.Zero){
ts = ts - one;
Console.WriteLine($#"{ts:mm\:ss}");
}
24:59, 24:58 ...
If you want it to count down from 25:00, put the WriteLine before the subtract
Change this string
string timeToString = _minutes.Count.ToString("24") + ":" + _seconds.Count.ToString("59");
to this
string timeToString = _minutes.Count.ToString() + ":" + _seconds.Count.ToString();
or you always get "24" and "59"...

Check the value exists in List using C#

I have List as mentioned below. Now When I am going to add new string value into this list, My method GetNewCopiedValue has to check the new text value into the list lstNames.If the name does not exist in the list it should return the value as it is. If the new string value is exist already in the list, it has to return the string with respective index number as like EC(1).For example, If I am sending EC(1) again to the list, the method has to check the value in the list and It should return EC(3) since EC(1) is exist already in the list, the method has to check the similar values and it should return the value with next index number which is not there in the list.
Main()
{
List<string> lstNames=new List<string>{"Ecard","EC","EC(1)","EC(2)","NCard(1)"};
var copiedValue= GetNewCopiedValue(lstNames,EC(2));
Console.WriteLine("Copied Text is :"+copiedValue);
}
public static string GetNewCopiedValue(List<string> lstNames,string sourceLabel)
{
label = sourceLabel;
if (lstNames.Any(i => i.Equals(sourceLabel)))
{
var labelSubstring = sourceLabel.Substring(0, sourceLabel.Length - 2);
var sameNameList = lstNames.Where(i => i.Contains(labelSubstring)).ToList();
int count = sameNameList.Count+1;
label = labelSubstring + count + ")";
while (lstNames.Any(i => i.Equals(label)))
{
var indexLabel = sourceLabel.Substring(sourceLabel.Length-2,1);
var maxIndex = sameNameList.Max(i =>int.Parse( i.Substring(sourceLabel.Length - 2, 1)));
int labelCount = maxIndex + 1;
label = labelSubstring + labelCount + ")";
}
}
return label;
}
Actual Input:
EC(2)
Expected output:
EC(3)
I have tried with some logic but it was not working with all input strings. It worked for few cases only.
Please help me on this.
https://dotnetfiddle.net/dFrzhA
public static void Main() {
List<string> lstNames= new List<string>{"Ecard","EC","EC(1)","EC(2)","NCard(1)"};
var copiedValue= GetNewCopiedValue(lstNames, "EC(1)");
Console.WriteLine("Copied Text is :" + copiedValue);
}
public static string GetNewCopiedValue(List<string> lstNames, string ValueToCopyInList) {
string newName;
if (!lstNames.Contains(ValueToCopyInList)) {
newName = ValueToCopyInList;
} else {
int? suffix = ParseSuffix(ValueToCopyInList);
string baseName = suffix == null ? ValueToCopyInList : ValueToCopyInList.Substring(0, ValueToCopyInList.LastIndexOf('('));
suffix = suffix ?? 1;
newName = baseName + "(" + suffix + ")";
while (lstNames.Contains(newName)) {
suffix++;
newName = baseName + "(" + suffix + ")";
}
}
lstNames.Add(newName);
return newName;
}
public static int? ParseSuffix(string value) {
int output;
if (string.IsNullOrEmpty(value)) return null;
if (!value.EndsWith(")")) {
return null;
}
var idxStart = value.LastIndexOf('(');
var strResult = value.Substring(idxStart + 1, value.Length - (idxStart + 2));
if (int.TryParse(strResult, out output))
return output;
return null;
}

ArgumentOutOfRangeException: startIndex cannot be longer than the length of string

When I run the compiler it throws an exception:
ArgumentOutOfRangeException: startIndex cannot be longer than the
length of string.
I do not understand why, the string which I write into the compiler consists of 10 numbers, and i want the substring to pick the 9th number, but obviously I'm doing something wrong.
Example of string: 9303140456
Code:
public string kollaKön()
{
string siffraAsString = form.textBox3.Text.Substring(8, 1);
int siffraAsNum = int.Parse(siffraAsString);
int result = (siffraAsNum % 2);
if (result == 1)
{
return form.textBox5.Text = ("Är en Man");
}
else
{
return form.textBox5.Text = (" Är en Kvinna");
}
}
Complete code, maybe makes my mistake obvious:
namespace WindowsFormsApplication3
{
public class Person
{
Form1 form = new Form1();
string förnamn;
string efternamn;
string personnummer;
string Kön;
public Person(string förNamn, string efterNamn, string personNummer)
{
string förnamn = förNamn;
string efternamn = efterNamn;
string personnummer = personNummer;
}
static bool luhn(string personNummer)
{
int sum = 0;
for (int i = 0; i < personNummer.Length; i++)
{
int temp = (personNummer[i] - '0') << (1 - (i & 1));
if (temp > 9) temp -= 9;
sum += temp;
}
return (sum % 10) == 0;
}
public string kollaKön()
{
string debuggerIsMyFriend = form.textBox3.Text;
string siffraAsString = form.textBox3.Text.Substring(8, 1);
int siffraAsNum = int.Parse(siffraAsString);
int result = (siffraAsNum % 2);
if (result == 1)
{
return form.textBox5.Text = ("Är en Man");
}
else
{
return form.textBox5.Text = (" Är en Kvinna");
}
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
string förnamn = textBox1.Text;
string efternamn = textBox2.Text;
string personnummer = textBox3.Text;
string persnr = "";
if (personnummer.Length != 10)
{
persnr = " Personnummer är i fel format. ";
}
if (personnummer.Length == 10)
{
persnr = " Personnummers är i korrekt format.";
}
Person p1 = new Person(förnamn, efternamn, personnummer);
p1.kollaKön();
textBox4.Text = förnamn + " " + efternamn + " " + personnummer + " " + " " + persnr;
}
}
}
This line in your Person class
Form1 form = new Form1();
declares and initialize a new Instance of Form1. This instance is not the one that you have shown on your monitor. When you type your strings you type them on the instance that is shown on monitor not into the textboxes of this hidden instance.
Of course this means that when you write
string siffraAsString = form.textBox3.Text.Substring(8, 1);
you are taking the text of the hidden textbox that is empty and the following Substring code fails with the Index Out of Range Exception
You need to change you Person class and add properties that receive the content of the textboxes required for your calculations.
For example
public class Person
{
// Sorry but I have no idea of what Siffra means...
// change the name as you wish
public string Siffra {get;set;}
...... other properties
public string kollaKön()
{
// A defensive attitude is always a good practice.
if(string.IsNullOrEmpty(this.Siffra) ||
this.Siffra.Length < 10)
return "Invalid Siffra";
string siffraAsString = this.Siffra.Substring(8, 1);
int siffraAsNum = int.Parse(siffraAsString);
int result = (siffraAsNum % 2);
return (result == 1 ? "Är en Man" : " Är en Kvinna");
}
}
and in your button click on the form you run
.....
Person p1 = new Person(förnamn, efternamn, personnummer);
p1.Siffra = this.textBox3.Text;
string result = p1.kollaKön();
this.textBox5.Text = result;
Before all your code, add this line
string debuggerIsMyFriend = form.textBox3.Text;
Set a breakpoint on that line, run the code and hover the mouse over the variable to see what it actually contains, I bet it's not the 10 characters string you are expecting
You should handle this more gracefully. This will handle your edge cases properly.
The string you're getting in that TextBox is most certainly not 9 characters long or more, and unless you have 100% certainty that your input is 9 characters, you should handle it gracefully.
Rule of thumb: Don't try to access the index of an array without checking its length first.
...Second rule of thumb: Also make sure you're accessing the correct UI control if you think something's fishy.
public string kollaKön()
{
//string siffraAsString = form.textBox3.Text.Substring(8, 1);
int siffraAsNum = GetNinthNumber(form.textBox3.Text);
int result = (siffraAsNum % 2);
if (result == 1)
{
return form.textBox5.Text = ("Är en Man");
}
else
{
return form.textBox5.Text = (" Är en Kvinna");
}
}
public static int GetNinthNumber(string str)
{
string numberField = str.Trim();
if (numberField.Length < 9)
{
// Handle less than 9 cases
return 0;
}
else
{
int number;
bool isNumber = Int32.TryParse(str[8].ToString(), out number);
if (!isNumber)
{
throw new Exception("Value is not a number");
}
return number;
}
}
I'm very sure that your line string siffraAsString = form.textBox3.Text.Substring(8, 1); doesn't have 10 numbers.
Checks the value of form.textBox3.Text as say Jacopo.

Calculate code to a new class.cs

i want to set my code to another class, example: A new class AgeCalculate.cs, How can I get the data from AgeCalculate.cs back to my Button_Click event.
Example:
AgeCalculate Calculate = new AgeCalculate();?
and from the class to Form1 =?
My code is now in button_Click.
double startkapital = 0;
double procentsats = 0;
int år = 0;
double kapital = 0;
startkapital = int.Parse(sKapTxt.Text);
procentsats = int.Parse(proSatsTxt.Text);
kapital = startkapital;
while (kapital < startkapital * 2)
{
kapital = kapital * (1 + procentsats / 100);
år = år + 1;
listBox1.Items.Add("Årtal: " + år);
listBox1.Items.Add("Kapital: " + kapital + "kr ");
listBox1.Items.Add(" ");
}
listBox1.Items.Add("Totalt antal år: " + år + "år ");
listBox1.Items.Add("Total kapital: " + kapital + "kr ");
listBox1.Items.Add(" ");
double exaktaåret = år / ((100 + procentsats) / 100);
listBox1.Items.Add(string.Format("Kapitalet fördubblades efter {0:0} år", exaktaåret));
if (kapital >= 2 * startkapital)
{
listBox1.Visible = true;
}
First, under your button_Click in your code behind C# event you will need to create an object of AgeCalculate.cs. I am not sure whether this is the correct way or not in C# but here it goes:
AgeCalculate calc = new AgeCalculate();
Then you use the object you created to call a function which returns the age calculated like this:
calc.FunctionName;
But before all, make sure in your class AgeCalculate there is a Function which has a return to return calculated age. And then once you do calc.FunctionName the calculated age will be returned.
Example:
In AgeCalculate.cs
public string calc(string value1)
{
//calculate age
String str = calculated age;
return str;
}
In C#
AgeCalculate calculate = new AgeCalculate();
calculate.calc(pass the argument you will use to calculate age);
You can create a public property in your AgeClass and get that property in your button click.

How to get "X8" hex type split to "X2-X2-X2-X2" type

Here is my code and I was just wondering how to split the 4bytes to 1byte-1byte-1byte-1byte
static int count;
private void SetClock_Click(object sender, EventArgs e)
{
count++;
label5.Text = count.ToString("X8");
DateTime time = DateTime.Now;
txtSend.Text = "4D-" + "1A-" + "2B-" + "3C-" +
(label5.Text.ToString()) + "-" + "03-" + "07-" + "00-" +
time.ToString("yy-MM-dd-") +
((int)time.DayOfWeek).ToString("00") +
time.ToString("-HH-mm-ss");
string[] allHaxValues = txtSend.Text.Split(new char[] { '-' });
int result = 0;
foreach (string haxValue in allHaxValues)
{
result = result ^ Convert.ToInt32(haxValue, 16);
}
//txtSend.Text = s;
txtSend.Text = txtSend.Text + ("-") + result.ToString("X2");
}
I am receiving value on click "00000001". I want to get it like others "00-00-00-01" Thanks
You can use the BitConverter class to turn the int value into the xx-xx-xx-xx form:
// make a four byte array of the int
byte[] parts = BitConverter.GetBytes(result);
// put the bytes in the right order
if (BitConverter.IsLittleEndian) {
Array.Reverse(parts);
}
// turn the bytes into the xx-xx-xx-xx format
string resultString = BitConverter.ToString(parts);
Based on #Guffa solution:
private string IntToBytes(int count)
{
// make a four byte array of the int
byte[] parts = BitConverter.GetBytes(count);
// put the bytes in the right order
if (BitConverter.IsLittleEndian) {
Array.Reverse(parts);
}
// turn the bytes into the xx-xx-xx-xx format
return BitConverter.ToString(parts);
}
now just replace
label5.Text = count.ToString("X8");
with
label5.Text = IntToBytes(count);

Categories

Resources