What is use of '%s' in xpath - xpath

I have tried to know the reason in online but i didnt get it.
I want to know the reason why '%s' used in xpath instead of giving text message
I hope some one can help me on this.
see my scenario:
By.xpath(("//div[contains(text(),'%s')]/following-sibling::div//input"))

It's called wildcard.
E.g. you have
private final String myId = "//*[contains(#id,'%s')]";
private WebElement idSelect(String text) {
return driver.findElement(By.xpath(String.format(myId, text)));
}
Then, you can make a function like:
public void clickMyId(idName){
idSelect(idName.click();
}
And call
clickMyId('testId');
The overall goal of the %s is not using the string concatenation, but to use it injected into a string.

Sometimes, there are many locators for web elements which are of same kind, only they vary with a small difference say in index or String.
For e.g., //div[#id='one']/span[text()='Mahesh'] and
//div[#id='one']/span[text()='Jonny']
As it can been seen in the above example that the id is same for both the element but the text vary.
In that case, you can use %s instead of text. Like,
String locator = "//div[#id='one']//span[text()='%s']";
private By pageLocator(String name)
{
return By.xpath(String.format(locator, name));
}
So in your case,
By.xpath(("//div[contains(text(),'%s')]/following-sibling::div//input"))
the text is passed at runtime as only the text vary in the locator.

'%s' in XPath is used as String Replacement.
Example:
exampleXpath = "//*[contains(#id,'%s')]"
void findElement(String someText)
{
driver.findElement(By.xpath(String.format(exampleXpath, someText)));
}
So it will replace %s with someText passed by user.

Related

findelement is not throwing NoSuchElementException

I want to write a test to check if a webelement with a specified text is not present on a page. This is the code for the method doing the job:
public boolean checkOfAanvraagIsOpgevoerd (String titel)
{
String quote = "\"";
String titelMetQuotes = quote + titel +quote;
titelMetQuotes = "dierdieboeboe";
boolean isOpgevoerd=false;
try {
driver.findElement(By.xpath(".//*[#id='listRequests']//h4/a[contains(text(),"+titelMetQuotes+")]"));
isOpgevoerd=true;
} catch (NoSuchElementException NE) {
NE.printStackTrace();
}
return isOpgevoerd;
}
Although I'm absolutely sure that there is no a tag on the page wich contains the text "dierdieboeboe" still the catch block is skipped. When I replace for instance h4 in h5 in the xpath expression the NoSuchElementException is thrown as expected. It seems that the contains part in the expression is ignored.
Try this (note the single quotes around the actual text):
By.xpath("//*[#id='listRequests']//h4/a[contains(text(),'"+titelMetQuotes+"')]")
contains is a function that takes two strings. Hence the text of your variable titelMetQuotes needs to be quoted. Obviously, in this case it is easier to use single quotes.
Additionally, the variable name (titel with quotes) is quite misleading because it actually has no quotes for another flaw in the code:
String titelMetQuotes = quote + titel +quote;
titelMetQuotes = "dierdieboeboe";
The second line simply overwrites the quoted title with a non quoted string.
Finally, you don't need the leading dot in your xpath expression in order to locate the first element of any kind with id listRequests

How to return localized content from WebAPI? Strings work but not numbers

Given this ApiController:
public string TestString() {
return "The value is: " + 1.23;
}
public double TestDouble() {
return 1.23;
}
With the browser's language set to "fr-FR", the following happens:
/apiController/TestString yields
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">The value is: 1,23</string>
/apiController/TestDouble yields
<double xmlns="http://schemas.microsoft.com/2003/10/Serialization/">1.23</double>
I would expect TestDouble() to yield 1,23 in the XML. Can anyone explain why this isn't the case and, more importantly, how to make it so that it does?
It is because the conversion from double to string happens at different stage for each API. For the TestString API, double.ToString() is used to convert the number to a string using CurrentCulture of the current thread and it happens when the TestString method is called. Meanwhile, the double number which is returned by TestDouble is serialized to string during the serialization step which uses GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Culture.
In my opinion, both should use InvariantCulture. On the consumer side, the values will be parsed and be formatted with the correct culture.
Update: this is only used for JsonFormatter. XmlFormatter doesn't have such a setting.
Update 2:
It seems (decimal) numbers need special converter to make it culture-aware:
Handling decimal values in Newtonsoft.Json
Btw, if you want o change data format per action/request, you can try the last piece of code of the following link: http://tostring.it/2012/07/18/customize-json-result-in-web-api/

String value with double quote in C#

I was trying to do autocomplete for my input box. When user start typing "I, then I should exactly search the keyword what user has typed ("I). When keys pressed, I was getting the string value as "\"I. How can i do the search based on what user has entered without stripping off any character from the string. Pls provide me any suggestion to help my issue.
Sample Code
public JsonResult AutoBibs(string searchTerm)
{
model = (from line in db.BibContents
where (line.Value.StartsWith(searchTerm) || line.Value.Contains(" " + searchTerm))
select new PoDetails
{
BibId = line.BibId
}).ToList();
return model;
}
The " always appends with an Escape character while processing the String variables in C# i.e. it appends "\" at the beginning. It would not change your functionality and you can still continue with your Auto Complete feature. Generally you can find this during in DEBUG mode only.
Read this MSDN article for more details.

Run multiple string replaces with fewer calls to .replace()

I'd like to condence the following code into fewer calls to .replace(). It doesn't look like .replace() will do this. Am I right or am I just reading the documentation wrong?
public void setBody(String body) {
this.body = body.replace("“", "\"").replace("”", "\"").replace("—", "-").replace("’", "'").replace("‘", "'");
}
You should be able to use body.replace(['"', '—', '‘'], ['\"', '-', "'"]).
You are right. To solve this, you should create a StringBuilder and go through your string 1 character at a time, adding the character to the stringBuilder if it is correct or replacing if it is wrong.

T4 FieldName in camelCase without Underscore?

I'm using T4 to generate some class definitions and find that I'm getting an underscore in front of my field names.
I have set
code.CamelCaseFields = true;
just to be safe (even though I understand that's the default) but still end up with _myField rather than myField.
How can I generate a field name without the '_' character?
Also, where is the documentation for T4? I'm finding plenty of resources such as
Code Generation and Text Templates and numerous blogs, but I have not found the class-by-class, property-by-property documentation.
You're probably talking about EF4 Self Tracking Entities. The CodeGenerationTools class is included via the <## include file="EF.Utility.CS.ttinclude"#> directive, which you can find at "[VSInstallDir]\Common7\IDE\Extensions\Microsoft\Entity Framework Tools\Templates\Includes\EF.Utility.CS.ttinclude".
The FieldName function is defined as such:
private string FieldName(string name)
{
if (CamelCaseFields)
{
return "_" + CamelCase(name);
}
else
{
return "_" + name;
}
}
The "_" is hardcoded in the function. Coding your own shouldn't be difficult. Note that the CodeGenerationTools class is specific to this ttinclude file and isn't a generic and embedded way to generate code in T4.
I've written the following method to make first character upper case, remove spaces/underscores and make next character upper case. See samples below. Feel free to use.
private string CodeName(string name)
{
name = name.ToLowerInvariant();
string result = name;
bool upperCase = false;
result = string.Empty;
for (int i = 0; i < name.Length; i++)
{
if (name[i] == ' ' || name[i] == '_')
{
upperCase = true;
}
else
{
if (i == 0 || upperCase)
{
result += name[i].ToString().ToUpperInvariant();
upperCase = false;
}
else
{
result += name[i];
}
}
}
return result;
}
input/output samples:
first_name = FirstName,
id = Id,
status message = StatusMessage
This is good advice however it doesn't help you in knowing WHERE the right place to put such a function is...
Is there any guidance on DECOMPOSING the EF .tt files or stepping through the output generation to see how it builds the output?
I was able to use the above function successfully by plugging it into a function called
(Ef4.3)
public string Property(EdmProperty edmProperty)
Which appears to be used to output the lines like "public int fieldname { get; set; }"
and changed the 3rd (index {2}) param to the formating to wrap with the function to modify the name, like this:
_typeMapper.GetTypeName(edmProperty.TypeUsage), //unchanged
UnderScoreToPascalCase(_code.Escape(edmProperty)), //wrapped "name"
_code.SpaceAfter(Accessibility.ForGetter(edmProperty)), // unchanged
This is not perfect, eg: it doesn't keep existing "Ucasing" and doesn't care about things like this:
customerIP
outputs: Customerip
which IMO is not very readable...
but its better than what I WAS looking at which was a nightmare because the database was intermingled mess of camelCase, PascalCase and underscore separation, so pretty horrific.
anyway hope this helps someone...

Resources