How to ignore case sensitive in this xpath c# selenium - c#

I have a simple xpath:
driver.findelement(by.xpath("//li[contains(text(), 'chain')]").click()
This code is working but its not recognize chain in uppercase, how to ignore case sensitive in this xpath?

You can use the contains and translate functions together like this:
//li[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'chain')]

Use translate, but to make it shorter, you may translate only characters you are looking for
//li[contains(translate(text(), 'CHAIN', 'chain'), 'chain')]
If you are going to use this a lot, you may even write a method for that. I'll write in Java (sorry, not familiar with C#):
public static void main(String[] args) {
String l = "//li[" + containsTextIgnoringCase("StackOverflow") + "]";
System.out.println(l);
}
public static String containsTextIgnoringCase(String s) {
return String.format("contains(translate(text(), '%s', '%s'), '%s')", s.toUpperCase(), s.toLowerCase(), s);
}
output:
//li[contains(translate(text(), 'STACKOVERFLOW', 'stackoverflow'), 'stackoverflow')]
There's some space for optimization (not sure if it costs the effort, but still): translate only unique chars, and handle quotes, if passed in string

Use the value of chain in the way that assign it to a separate string variable and then apply .ToUpper() extension on it.
string strChain = "chain";
string getUpper = strChain.ToUpper();
It will give you cain in uppercase.
You can use it directly inside driver.findelement.

Related

String format proper using

Do you know another more proper way to do the same things ?
string initialTemplate = "{0}-{1}";
string template = string.Format(initialTemplate, "first", "{0}");
string answer = string.Format(template, "second");
Also the following way has actually known, but in my current case unfortunatelyI can't use that method(i think that that way more proper and the logic more clear):
string initialTemplate = "{0}-{{0}}";
string template = string.Format(initialTemplate, "first");
string answer = string.Format(template, "second");
Maybe is there another hint how to do that?
UPDATE
I'm so sorry but from yours answers I've learnt that my question wasn't enough clear. So I've added a little bit more description.
My situation:
//that template is actually placed in *.resx file
//I want storing only one template and use that in different situations
public const string InitialTemplate = "{0}-{1}";
public static string GetMessage(string one, string two)
{
return string.Format(InitialTemplate, one, two);
}
public static string GetTemplate(string one)
{
return string.Format(InitialTemplate, one, "{0}");
}
//or morew universal way
public static string GetTemplate(params object[] args)
{
return string.Format(InitialTemplate, args, "{0}");
}
static void Main(string[] args)
{
//in almost all cases in my project i need to use string.format like this
string message = GetMessage("one", "two");
//but there is another way where i have to use
//the template have already been assigned first argument
//the result must be "one-{0}"
string getTemplateWithAssignedFirstArg = GetTemplate("one");
}
Do you know more proper way for that kind of situation ?
If you are using C# 6 you can also use string interpolation.
https://msdn.microsoft.com/en-us/library/dn961160.aspx
var answer = $"{firstVar}-{secondVar}";
string initialTemplate = "{0}-{1}";
string answer = string.Format(initialTemplate, "first", "second");
Should do the trick. Or cut out the middle man with:
string answer = string.Format("{0}-{1}", "first", "second");
String.Format is a very useful convenience, but I'd be wary of using it to build format strings that you're going to use to create other format strings. Someone trying to maintain that code, figure out what's going on, and perhaps modify it will be baffled. Using String.Format that way is technically possible, and there could even be scenarios where it's useful, but it's probably just going to result in something that works but is very difficult to understand and debug.
My first suggestion would be to use a StringBuilder. Even when you're appending to the StringBuilder you can use String.Format if needed to create the individual strings.
I wonder if perhaps what you describe in the question is taking place across multiple methods (which is why you might be building your format string in steps.) If that's the case, I recommend not building the string in steps like that. Don't actually start building the string until you have all of the data that you need together, and then build the string at once.

Declare constants that include special character

I have a string that contains special character {,[,.. as follow:
"[{"name":"print","next":"null","proc":"printproc","func":"null"}]"
To assign the constant string to a variable, I have to do the following:
string s = "[{\"name\":\"print\",\"next\":\"null\",\"proc\":\"printproc\",\"func\":\"null\"}]";
or the compiler will throw out an error. Is there a less cumbersome way to declare the constant. I have tried to use # at the beginning of the string:
string s = #"[{"name":"print","next":"null","proc":"printproc","func":"null"}]";
But I got a compiler error as well. Saving the constant into a text file and load from it will work but it may be an overkill for me. Have anyone come across the same scenario in C# and have they come up with a work around?
Have you tried using single quotes to wrap the property names/values?
e.g. string s = #"[{'name':'print','next':'null','proc':'printproc','func':'null'}]"
you can put double qutes:
string s = #"[{""name"":""print""}]";
Or, put \
string s = "[{\"name\":\"print\"}]";
You can use this ' instead of "
Split your data with any way then use it
You could make a variable for each special character you want.
To show the concept, I tested this in a simple C# Console app.
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string quot = "\"";
string compound = "Now I can use " + quot + "quotation marks" + quot + " around a variable";
Console.WriteLine(compound);
}
}
}
The output is:
Now I can use "quotation marks" around a variable

UTF-8 escape sequence as string: surely a better way

Reviewing some old code of mine, and wondered if there was a better way to create a literal string with unicode symbols...
I have a REST interface that requires certain escaped characters; for example, a property called username with value of john%foobar+Smith that must be requested like this:
{"username":"john\u0025foobar\u002bSmith"}
My c# method to replace certain characters like % and + is pretty basic:
public static string EncodeUTF8(string unescaped) {
string utf8_ampersand = #"\u0026";
string utf8_percent = #"\u0025";
string utf8_plus = #"\u002b";
return unescaped.Replace("&", utf8_ampersand).Replace("+", utf8_plus).Replace("%", utf8_percent);
}
This seems an antiquated way to do this; surely there is some single line method using Encoding that would output literal UTF code, but I can't find any examples that aren't essentially replace statements like mine... is there a better way?
You could do it with Regex:
static readonly Regex ReplacerRegex = new Regex("[&+%]");
public static string Replace(Match match)
{
// 4-digits hex of the matched char
return #"\u" + ((int)match.Value[0]).ToString("x4");
}
public static string EncodeUTF8(string unescaped)
{
return ReplacerRegex.Replace(unescaped, Replace);
}
But i don't suggest it very much (unless you have tens of replaces). I do think it would be slower, and bigger to write.

words stemmer class c#

I am trying the following stemming class :
static class StemmerSteps
{
public static string stepSufixremover(this string str, string suffex)
{
if (str.EndsWith(suffex))
{
................
}
return str;
}
public static string stepPrefixemover(this string str, string prefix)
{
if (str.StartsWith(prefix)
{
.....................
}
return str;
}
}
this class works with one prefix or suffix. is there any suggestion to allow a list of prefixes or suffixes to go through the class and compare against each (str). your kind action really appreciated.
Instead of creating your own class from scratch (unless this is homework) I would definitive use an existing library. This answer provides an example of code that that implements the Porter Stemming Algorithm:
https://stackoverflow.com/questions/7611455/how-to-perform-stemming-in-c
Put your suffix/prefixes in a collection (like a List<>), and loop through and apply each possible one. This collection would need to be passed into the method.
List<string> suffixes = ...;
for (suffix in suffixes)
if (str.EndsWith(suffix))
str = str.Remove(str.Length - suffix.Length, suffix.Length);
EDIT
Considering your comment:
"just want to look if the string starts-/endswith any of the passed strings"
may be something like this can fit your needs:
public static string stepSufixremover(this string str, IEnumerable<string> suffex)
{
string suf = suffex.Where(x=>str.EndsWith(x)).SingleOrDefault();
if(!string.IsNullOrEmpty(suf))
{
str = str.Remove(str.Length - suf.Length, suf.Length);
}
return str;
}
If you use this like:
"hello".stepone(new string[]{"lo","l"}).Dump();
it produces:
hel
The simplest code would involve regular expressions.
For example, this would identify some English suffixes:
'^(.*?)(ing|ly|ed|ious|ies|ive|es|s|ment)?$'
One problem is that stemming is not as accurate as lemmatization. Lematization would require POS tagging for accuracy. For example, you don't want to add an -ing suffix to dove if it's a noun.
Another problem is that some suffixes also require prefixes. For example, you must add en- to -rich- to add a -ment suffix in en-rich-ment -- unlike a root like -govern- where you can add the suffix without any prefix.

Check for special characters (/*-+_#&$#%) in a string?

How do I check a string to make sure it contains numbers, letters, or space only?
In C# this is simple:
private bool HasSpecialChars(string yourString)
{
return yourString.Any(ch => ! char.IsLetterOrDigit(ch));
}
The easiest way it to use a regular expression:
Regular Expression for alphanumeric and underscores
Using regular expressions in .net:
http://www.regular-expressions.info/dotnet.html
MSDN Regular Expression
Regex.IsMatch
var regexItem = new Regex("^[a-zA-Z0-9 ]*$");
if(regexItem.IsMatch(YOUR_STRING)){..}
string s = #"$KUH% I*$)OFNlkfn$";
var withoutSpecial = new string(s.Where(c => Char.IsLetterOrDigit(c)
|| Char.IsWhiteSpace(c)).ToArray());
if (s != withoutSpecial)
{
Console.WriteLine("String contains special chars");
}
Try this way.
public static bool hasSpecialChar(string input)
{
string specialChar = #"\|!#$%&/()=?»«#£§€{}.-;'<>_,";
foreach (var item in specialChar)
{
if (input.Contains(item)) return true;
}
return false;
}
String test_string = "tesintg#$234524##";
if (System.Text.RegularExpressions.Regex.IsMatch(test_string, "^[a-zA-Z0-9\x20]+$"))
{
// Good-to-go
}
An example can be found here: http://ideone.com/B1HxA
If the list of acceptable characters is pretty small, you can use a regular expression like this:
Regex.IsMatch(items, "[a-z0-9 ]+", RegexOptions.IgnoreCase);
The regular expression used here looks for any character from a-z and 0-9 including a space (what's inside the square brackets []), that there is one or more of these characters (the + sign--you can use a * for 0 or more). The final option tells the regex parser to ignore case.
This will fail on anything that is not a letter, number, or space. To add more characters to the blessed list, add it inside the square brackets.
Use the regular Expression below in to validate a string to make sure it contains numbers, letters, or space only:
[a-zA-Z0-9 ]
You could do it with a bool. I've been learning recently and found I could do it this way. In this example, I'm checking a user's input to the console:
using System;
using System.Linq;
namespace CheckStringContent
{
class Program
{
static void Main(string[] args)
{
//Get a password to check
Console.WriteLine("Please input a Password: ");
string userPassword = Console.ReadLine();
//Check the string
bool symbolCheck = userPassword.Any(p => !char.IsLetterOrDigit(p));
//Write results to console
Console.WriteLine($"Symbols are present: {symbolCheck}");
}
}
}
This returns 'True' if special chars (symbolCheck) are present in the string, and 'False' if not present.
A great way using C# and Linq here:
public static bool HasSpecialCharacter(this string s)
{
foreach (var c in s)
{
if(!char.IsLetterOrDigit(c))
{
return true;
}
}
return false;
}
And access it like this:
myString.HasSpecialCharacter();
private bool isMatch(string strValue,string specialChars)
{
return specialChars.Where(x => strValue.Contains(x)).Any();
}
Create a method and call it hasSpecialChar with one parameter
and use foreach to check every single character in the textbox, add as many characters as you want in the array, in my case i just used ) and ( to prevent sql injection .
public void hasSpecialChar(string input)
{
char[] specialChar = {'(',')'};
foreach (char item in specialChar)
{
if (input.Contains(item)) MessageBox.Show("it contains");
}
}
in your button click evenement or you click btn double time like that :
private void button1_Click(object sender, EventArgs e)
{
hasSpecialChar(textbox1.Text);
}
While there are many ways to skin this cat, I prefer to wrap such code into reusable extension methods that make it trivial to do going forward. When using extension methods, you can also avoid RegEx as it is slower than a direct character check. I like using the extensions in the Extensions.cs NuGet package. It makes this check as simple as:
Add the [https://www.nuget.org/packages/Extensions.cs][1] package to your project.
Add "using Extensions;" to the top of your code.
"smith23#".IsAlphaNumeric() will return False whereas "smith23".IsAlphaNumeric() will return True. By default the .IsAlphaNumeric() method ignores spaces, but it can also be overridden such that "smith 23".IsAlphaNumeric(false) will return False since the space is not considered part of the alphabet.
Every other check in the rest of the code is simply MyString.IsAlphaNumeric().
Based on #prmph's answer, it can be even more simplified (omitting the variable, using overload resolution):
yourString.Any(char.IsLetterOrDigit);
No special characters or empty string except hyphen
^[a-zA-Z0-9-]+$

Categories

Resources