How to answer Pin code with selenium c# - c#

Very new to programming/selenium automation in C# and have hit a bit of a stumbling block that I am struggling at resolving, I have looked around on here / google but nothing has come up matching what I am looking for, I could be wording my question slightly wrong so forgive me if that is the case.
What I need to achieve,
When logging into a website after entering a username/password we are prompted to enter a pin code, specifically a randomly generated combination – example “Please enter numbers 1, 2 & 3 of your PIN” - where (in the example) 1, 2, 3 can be anything from 1 to 6 (always chronological order), the message itself, “,” and “&” positions do not change – only the numbers.
** Info from the 'line' containing the message (and numbers) **
Inner HTML
Please enter numbers 1, 3 & 5 of your PIN
Outer HTML
Please enter numbers 1, 3 & 5 of your PIN
CSS Selector
h2.login-desktop-only
xPath
/html/body/section[2]/div/div/div/form/div/div[2]/div[1]/div/h2
For this situation I am using a ‘UAT site’ so I have control on the PIN, let’s say it is always 123456 – so 1 = 1, 2 =2, 3-3 and so on. I have no way to determine which numbers will be asked each time the test is run.
How can I ‘scrape’ the text from ‘Please enter numbers XXXXX’ and parse (I think that is the correct word) the data to separate the ‘scraped’ numbers and then in turn use that data to match the pre-declared ‘1 = 1’ etc etc to then end up selecting the correct number on the keypad?
I imagine this is going to need a list of IF statements but again I still do not know how to scrape / store the requested numbers. Ideally would like to keep this using c# (however if any Java examples exist I can work with that as a colleague is using java selenium - both of us are very new to this)
Any advice would be greatly appreciated.
(EDIT TO Add code from comment)
Many thanks for getting back to me, I tried that code and it has located the index position of the integers contained within that ‘string’. Currently it ‘prints’ out the index position, but how can I get that to give the value rather than print it?
I suppose if I could assign it to a variable I could then split the three numbers down to a unique variable that has IF statements to cover the IF 1 – then 1 IF 2 – then 2 and so on. If that makes sense?
public class Some_Class {
public static void main(String[] args) {
WebDriver driver = new SafariDriver();
driver.get("SomeWebsite");
driver.findElement(By.id("username")).sendKeys("XXXXXXX");
driver.findElement(By.id("password")).sendKeys("XXXXXXX ");
driver.findElement(By.id("login-button")).click();
/* --- This was my original plan to set the xpath as a string and then replace all with numbers only. This did not work as I thought.
{
WebElement str = driver.findElement(By.xpath("/html/body/section[2]/div/div/div/form/div/div[2]/div[1]/div/h2"));
String numberOnly = str.replaceAll("[^0-9]", "");
}
*/
WebElement option = driver.findElement(By.xpath("/html/body/section[2]/div/div/div/form/div/div[2]/div[1]/div/h2"));
String word=option.getText();
String check[]=word.split("");
for(int i=0; i<check.length ; i++)
{
if( Pattern.matches("\\d", check[i]))
{
System.out.println("found integer at i = "+ i);
}
}
}
}

Input : you need to scrape a string containing ' integers and alphabets' and return only integers.
Here's an example I have done using Selenium,Java.
Please change your URL and WebElement to scrape.
driver.get("https://en.wikipedia.org/wiki/Main_Page");
WebElement option = driver.findElement(By.xpath("//*[#id=\"articlecount\"]"));
String word=option.getText();
//here you get - 5,589,206 articles in English
String check[]=word.split("");
for(int i=0; i<check.length ; i++)
{
if( Pattern.matches("\\d", check[i]))
{
System.out.println("found integer at i = "+ i);
}
}
Basically that would print you the index at which you have integers. Use them

In the case of a challenge string that says
string pinRequest = "Please enter pin digits 1,4 & 8 of your pin.";
var pinNums = pinRequest.Where(Char.IsDigit).ToArray().ToList();
pinNums will be an integer array that has 3 parts which are equal to
{1,4,8}
Your pin challenge is then solved via:
string part1 = fullWord.ToArray()[pinNums[0] - 1].ToString();
string part2 = fullWord.ToArray()[pinNums[1] - 1].ToString();
string part3 = fullWord.ToArray()[pinNums[2] - 1].ToString();
where fullWord could be something like 123123 or Password123
I am not too sure how this code will handle pin challenges >= 10 digits in length.

Related

C# string.split on readline not producing expected array length

Hi guys just carrying on working on my first app, done mainly to learn and nothing else. I want the user to be able to type in 2d6+4 OR 2d6, you should be able to substitute those numbers for any number. I'm getting errors parsing the information and I think it has something to do with the array containing more or less values than I anticipated, or it for some reason left the delimiter in. typing 2d6+4 or 2d6 +4 works fine, 2d6 however does not, which is what I thought the if statement should guard against. Any ideas?
Console.WriteLine("Please type the roll you would like to perform, for example - 2d6+4");
var rollLine = Console.ReadLine();
var diceLine = rollLine.Split(new Char[] { 'd', '+' }, StringSplitOptions.RemoveEmptyEntries);
diceCount = int.Parse(diceLine[0]);
diceType = int.Parse(diceLine[1]);
if (rollLine.Length > 2)
{
bonus = int.Parse(diceLine[2]);
}
else
{
bonus = 0;
}
It looks like you are just using the wrong variable for the length comparison. You are comparing the length of the string, not the length of the split array. It should be:
if (diceLine.Length > 2)
When user entered "2d6", the string length is 3, i.e. following rule is true
if (rollLine.Length > 2)
However, as per your logic you will get array of 2 items in the diceLine, i.e. diceLine[0] and diceLine[1] but after condition with length you call diceLine[2] that does not exist.
I.e. either change condition to
if (rollLine.Length == 5) // 2d6+4
or check for the length of the array
if (diceLine.Length > 2)
You want your IF to check if the rollLine length is greater than 3, not 2.
As the smallest thing you'll type in is, for example, 2d6, you want to check for the bonus only when the rollLine is more than 3 characters.
if (rollLine.Length > 3)
{
bonus = int.Parse(diceLine[2]);
}

Increment the numeric ending of a String by 1, using: Void increment(char[] referenceNumber)

Please help me with this interview question I faced recently, every help will be appreciated.
Please implement in C# the function that increments a string based on below rules:
It should take the string of unknown length and increment the numeric ending of that string by 1.
If numeric ending is overflown it must be reset
Don't use regular expressions.
Examples:
000002 ▶ 000003
DRI000EDERS0RE99999 ▶ DRI000EDERS0RE00000
Few ways to skin this cat. I think I would actually rely on c# ability to treat char like int, and manipulate the characters rather than trying to parse an int out of it, increment it then format it back
string s = "abcd999";
string ca = s.ToCharArray();
for(int i = ca.Length - 1; i>= 0 && char.IsDigit(ca[i]); i--){
if(ca[i] == '9')
ca[i] = '0';
else {
ca[i]++;
break;
}
}
return new string(ca);
We turn the string into a char array for easy manipulation then skip backwards over it from end to start. We want to stop looping when we hit a non digit or the string start. Then the logic is simple counting like a kid does. If we are on 9 we go back to 0 (the "bump up the next one will maybe be done by the next pass of the loop), otherwise we increment the char by one and quit:
4 becomes 5,
19 becomes 10 becomes 20,
abc9999 becomes abc9990 then abc9900 then abc9000 then abc0000 then the loop quits on the non digit c

How can I rewrite values from an array into a second array with each 2 letters being flipped? (C#)

This is for a homework assignment which I have been working on for quite a while now but have not been able to figure out. Here are the exact instructions from my teacher if you need them; it is at number five that I am stuck:
(1) Have the user enter a sentence that they want to have encoded.
(2) If the number of characters in the message is odd, concatenate a space (" ") to their message so that our message will always be an even number of letters.
(3) Now create a new char[], call it unCoded where each element is a letter from your secret message.
(4) Now create an empty second char[], call it coded, and define its length equal to the length of the other char[], unCoded.
(5) Now write the values from the uncoded array into the coded array, but flipping each 2 letters.
(6) Then write out the original uncoded message.
(7) Then write out the new coded message.
He also said step 5 must be done in a loop.
Any help would be appreciated, thanks.
What I have so far:
static void Main(string[] args)
{
Console.WriteLine("Enter the sentence you want encoded: ");
string userInput = Console.ReadLine();
int remainder = userInput.Length % 2;
if (remainder!=0)
{
userInput = userInput + " ";
}
char[] unCoded = userInput.ToArray();
char[] coded=unCoded;
//coded.Length = unCoded.Length;
for (int i = 0; i < unCoded.Length; i=i+2)
{
coded[0] = unCoded[1];
coded[1] = unCoded[0];
}
string encoded = new string(coded);
Console.WriteLine("{0}", userInput);
Console.WriteLine("{0}", encoded);
Console.ReadKey();
}
Well, in your loop you don't use the loop parameter, so you just change up the first two values several times. Consider what you are doing in your loop to be the first step of what you actually want to achieve. Do it using the "i" variable and knowing that it's first value is 0. Then when i "grows", the loop will do the same for the next two values.
so just put i in place of 0 and i+1 in place of 1

Simple way to encrpyt/decrypt a number

I need to encrypt a 2-digit number in a simple way. The samples I found in google seems to be quite complex. Is there any easy way to achieve that?
UPDATE
I'm working on a custom numeric captcha for my ASP.NET MVC application. I've created a custom html helper that will render an image tag with base-64 encoded string of the captcha image. The captcha image will be something like 23 + 12 = ?. When the user submit the answer I want to validate it right? I'm not interested in storing the sum in session so I thought of encrypt the sum and attach as a hidden field and so when the user submit the form I can easily do the validation.
If your number is x then you can encrypt it as (x + key) mod 100. This will result in another 2 digit number, y.
It doesn't get much simpler than that.
The decryption is simply x = y - key, +100 if necessary.
If key is 2:
x = 15
y = 15 + 2 = 17
x = 17 - 2 = 15
x = 99
y = 99 + 2 mod 100 = 101 mod 100 = 1
x = 1 - 2 + 100 = 99;
Even simpler would be to encrypt x as x. They would definitely never expect that...
Edit 1:
On a more serious note, If this is not some sort of personal experiment/homework I'd stay clear of such "simple" algorithms and go with System.Security.Cryptography and those not-that-complex samples from Google or charles sun's comment. Unless you make a carrier out of it never implement you own encryption/decryption algorithms, that way lies madness.
Edit 2:
So you want to send both the captcha and its correct response to the client? I don't think that is how it's done (but then again this is not my field...). I always thought validation is done on the server side (the part you control and keep secure).
To be on the safe side, I would do this the hard way and encrypt everything properly.
This is maybe not entirely serious, but it works!
static IEnumerable<string> GetRandomStringsForever()
{
var rng = new Random(); // or maybe new Random(14142848)
while (true)
{
char[] arr = new char[8];
for (int idx = 0; idx < arr.Length; ++idx)
arr[idx] = (char)rng.Next('A', 'Z' + 1);
yield return new string(arr);
}
}
static void Main()
{
var secretKey = GetRandomStringsForever().Distinct().Take(100).ToList();
int message = 42;
// encrypt:
string cryptic = secretKey[message];
Console.WriteLine("Who can guess the number from this: " + cryptic);
// decrypt:
int reconstructed = secretKey.IndexOf(cryptic);
Console.WriteLine("The message was: " + reconstructed);
}
Well, if people know you're doing this using my idea, they will probably be able to construct the secretKey themselves (using the same version of .NET as you), so this is not REALLY safe.

find word and score based on positions

hey guys i have a textfile i have divided it into 4 parts. i want to search each part for the words that appear in each part and score that word
exmaple
welcome to the national basketball finals,the basketball teams here today have come a long way. without much delay lets play basketball.
i will want to return national = 1 as it appears only in one part etc
am working on determining text context using word position.
am working with c# and not very good in text processing
basically
if a word appears in the 4 sections it scores 4
if a word appears in the 3 sections it scores 3
if a word appears in the 2 sections it scores 2
if a word appears in the 1 section it scores 1
thanks in advance
so far i have this
var s = "welcome to the national basketball finals,the basketball teams here today have come a long way. without much delay lets play basketball. ";
var numberOfParts = 4;
var eachPartLength = s.Length / numberOfParts;
var parts = new List<string>();
var words = Regex.Split(s, #"\W").Where(w => w.Length > 0); // this splits all words, removes empty strings
var wordsIndex = 0;
for (int i = 0; i < numberOfParts; i++)
{
var sb = new StringBuilder();
while (sb.Length < eachPartLength && wordsIndex < words.Count())
{
sb.AppendFormat("{0} ", words.ElementAt(wordsIndex));
wordsIndex++;
}
// here you have the part
Response.Write("[{0}]"+ sb);
parts.Add(sb.ToString());
var allwords = parts.SelectMany(p => p.Split(' ').Distinct());
var wordsInAllParts = allwords.Where(w => parts.All(p => p.Contains(w))).Distinct();
This question is very difficult to interpret. I don't fully understand your goal and it is my suspicion that you might not either.
In the absence of a clear requirement, there is no way to give a specific answer, so I will give a generic one:
Try writing a test that clearly specifies the exact behavior you want. You've got the beginnings of one with your sample string and the result you want but it's not unambiguous what you are looking for.
Make a test that, when it passes, demonstrates that one of the required behaviors is there. If that doesn't help you get a solution to the problem, come back and edit this question or make a new one that includes the test.
At the very least, you will be able to harvest better answers from this site.

Categories

Resources