How to return localized content from WebAPI? Strings work but not numbers - asp.net-web-api

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/

Related

Powerautomate Parsing JSON Array

I've seen the JSON array questions here and I'm still a little lost, so could use some extra help.
Here's the setup:
My Flow calls a sproc on my DB and that sproc returns this JSON:
{
"ResultSets": {
"Table1": [
{
"OrderID": 9518338,
"BasketID": 9518338,
"RefID": 65178176,
"SiteConfigID": 237
}
]
},
"OutputParameters": {}
}
Then I use a PARSE JSON action to get what looks like the same result, but now I'm told it's parsed and I can call variables.
Issue is when I try to call just, say, SiteConfigID, I get "The output you selected is inside a collection and needs to be looped over to be accessed. This action cannot be inside a foreach."
After some research, I know what's going on here. Table1 is an Array, and I need to tell PowerAutomate to just grab the first record of that array so it knows it's working with just a record instead of a full array. Fair enough. So I spin up a "Return Values to Virtual Power Agents" action just to see my output. I know I'm supposed to use a 'first' expression or a 'get [0] from array expression here, but I can't seem to make them work. Below are what I've tried and the errors I get:
Tried:
first(body('Parse-Sproc')?['Table1/SiteConfigID'])
Got: InvalidTemplate. Unable to process template language expressions in action 'Return_value(s)_to_Power_Virtual_Agents' inputs at line '0' and column '0': 'The template language function 'first' expects its parameter be an array or a string. The provided value is of type 'Null'. Please see https://aka.ms/logicexpressions#first for usage details.'.
Also Tried:
body('Parse-Sproc')?['Table1/SiteconfigID']
which just returns a null valued variable
Finally I tried
outputs('Parse-Sproc')?['Table1']?['value'][0]?['SiteConfigID']
Which STILL gives me a null-valued variable. It's the worst.
In that last expression, I also switched the variable type in the return to pva action to a string instead of a number, no dice.
Also, changed 'outputs' in that expression for 'body' .. also no dice
Here is a screenie of the setup:
To be clear: the end result i'm looking for is for the system to just return "SiteConfigID" as a string or an int so that I can pipe that into a virtual agent.
I believe this is what you need as an expression ...
body('Parse-Sproc')?['ResultSets']['Table1'][0]?['SiteConfigID']
You can see I'm just traversing down to the object and through the array to get the value.
Naturally, I don't have your exact flow but if I use your JSON and load it up into Parse JSON step to get the schema, I am able to get the result. I do get a different schema to you though so will be interesting to see if it directly translates.

How to make Get Request with Request param in Postman

I have created an endpoint that accepts a string in its request param
#GetMapping(value = "/validate")
private void validateExpression(#RequestParam(value = "expression") String expression) {
System.out.println(expression);
// code to validate the input string
}
While sending the request from postman as
https://localhost:8443/validate?expression=Y07607=Curr_month:Y07606/Curr_month:Y07608
// lets say this is a valid input
console displays as
Y07607=Curr_month:Y07606/Curr_month:Y07608 Valid
But when i send
https://localhost:8443/validate?expression=Y07607=Curr_month:Y07606+Curr_month:Y07608
//which is also an valid input
console displays as
Y07607=Curr_month:Y07606 Curr_month:Y07608 Invalid
I am not understanding why "+" is not accepted as parameter.
"+" just vanishes till it reaches the api! Why?
I suggest to add this regular expression to your code to handle '+' char :
#GetMapping(value = "/validate")
private void validateExpression(#RequestParam(value = "expression:.+") String expression) {
System.out.println(expression);
// code to validate the input string
}
I didn't find any solution but the reason is because + is a special character in a URL escape for spaces. Thats why it is replacing + with a " " i.e. a space.
So apparently I have to encode it from my front-end
Its wise to encode special characters in a URL. Characters like \ or :, etc.
For + the format or value is %2. You can read more about URL encoding here. This is actually the preferred method because these special characters can sometimes cause unintended events to occur, like / or = which can mean something else in the URL.
And you need not worry about manually decoding it in the backend or server because it is automatically decoded, in most cases and frameworks. In your case, I assume you are using Spring Boot, so you don't need to worry about decoding.

What does "read_strt" meaning here?

What does this vbscript code mean?
<%=read_strt(objRS, "ccnumber", "")%>
I want to know whats the meaning or used of read_strt on the code?
Any ideas?
The statement writes the return value of a call to the function "read_strt" to the HTML output stream. The function seems to read the value of a field/column in the current row of a database query (recordset), convert its type to String and/or test it against 'bad' (e.g. Null) values; in that case the default value ("", empty string) is returned.

Freemarker - default value for variable that may be missing or blank?

In Freemarker, I want to treat something that may be missing (not defined on given object or in given Map), have a null value, be an empty string "" or a string with whitespace only (" \t\n"), AKA blank string. Or a real value like "foo".
In case it's anything besides a non-blank string, I want the expression to return a default value.
How can I handle this in Freemarker?
So far, this is what I use:
${ obj.propery???then(obj.property?trim!"default") }
But I can imagine something more ellegant, like
${ obj.property!!?trim!"default" }
and even with trimming (which is quite common operation for templates):
${ obj.property!!!"default" }
Is there something such in Freemarker? (Besides coding my own method or macro.)
There's nothing in FreeMarker for that, at least not in 2.3.24. I think the best way to address that is wiriting a trimToNull function, and then you can write trimToNull(obj.property)!"default" and trimToNull(obj.property)??, etc.
I had the same challenge and came to this solution:
${ (obj.property!"")?trim }
It also trims the empty string but is easier to read than writing an function or a if.

Java8 LocalDateTime to XMLGregorianCalender Remove "+05:30" Portion

Did like below,
LocalDateTime currentUTCTime = LocalDateTime.now(ZoneId.of("UTC"));
String reqPattern = currentUTCTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS"));
System.out.println("Required pattern: " + reqPattern);
GregorianCalendar calendar = GregorianCalendar.from(currentUTCTime.atZone(ZoneId.systemDefault()));
XMLGregorianCalendar xcal = DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar);
System.out.println("But Showing As :" + xcal);
I want the output as 2015-06-18 11:59:15:135, but when i set the xcal to
a XML tag which takes XMLGregorianCalender, it shows like 2015-06-18T11:59:15.135+05:30.
How can i remove the +05:30 portion?
Use this code:
LocalDateTime currentUTCTime = LocalDateTime.now(); // using system timezone
String iso = currentUTCTime.toString();
if (currentUTCTime.getSecond() == 0 && currentUTCTime.getNano() == 0) {
iso += ":00"; // necessary hack because the second part is not optional in XML
}
XMLGregorianCalendar xml =
DatatypeFactory.newInstance().newXMLGregorianCalendar(iso‌​);
Explanation:
The code makes use of the given factory method expecting a lexicographical representation of a local timestamp in ISO-8601-format. And since a LocalDateTime does not refer to any timezone, its output via toString() cannot contain a timezone offset. Result: XMLGregorianCalendar considers the timezone offset as "not set".
Correction:
The original code did not especially bother about the ISO-variant of formatted output of currentUTCTime.toString(). However, the java.time-API produces an output without seconds or nanoseconds if those parts are equal to zero. This is perfectly legal in ISO, but the W3C-consortium has made the second part non-optional. And the class XMLGregorianCalendar closely follows this deviating spec. Therefore the shown hack above using simple string concatenation in this special edge case. Thanks a lot to #Dave's comment. By the way, using currentUTCTime.format(DateTimeFormatter.ISO_DATE_TIME) as suggested in this comment is also possible (instead of the shown hack).

Resources