In ASP.NET MVC 2 / EF, comma in number causes model binding error - asp.net-mvc-2

In my HTTP POST controller method for add/editing data, I'm receiving an entity from my EF data model. Some of the fields in that entity are of type double. Everything works fine unless the user types in a comma for a thousands separator, which then causes a model binding validation error.
Has anyone run into this before? Is replacing the default model binder with a custom one the only solution or is there a better approach?
Any advice would be greatly appreciated.
Thanks.

Modelbinding for MVC uses a culture invariant mode of binding. Therefore numbers must be in the 100000.00 format.
Though the following relates to the datetime it also is pertinent to the decimal type as well.
Quote from the asp.net team member:
"This is intentional. Anything that is part of the URI (note the 'Uniform' in URI) is interpreted as if it were coming from the invariant culture. This is so that a user in the U.S. who copies a link and sends it over IM to a friend in the U.K. can be confident that his friend will see the exact same page (as opposed to an HTTP 500 due to a DateTime conversion error, for example). In general, dates passed in RouteData or QueryString should be in the format yyyy-mm-dd so as to be unambiguous across cultures.
If you need to interpret a QueryString or RouteData parameter in a culture-aware manner, pull it in as a string, then convert it to the desired type manually, passing in the desired culture. (DateTime.Parse has overloads that allow you to specify a culture.) If you do this, I recommend also taking the desired culture as a QueryString or a RouteData parameter so that the 'Uniform' part of URI isn't lost, e.g. the URL will look something like ...?culture=fr-fr&date=01-10-1990."

Related

How server handle REST API path parameters

When design REST API, you can have
GET /userinfo?id=124,
you can also make the parameter part of the path:
GET /userinfo/124.
I understand on the server side, how the server get the parameter for the first case. But I do not understand how server can get the userid parameter in the second case: /userinfo/124.
Could anyone explain?
I understand on the server side, how the server get the parameter for the first case. But I do not understand how server can get the userid parameter in the second case: /userinfo/124.
Exactly the same way: the server parses the string.
Which is to say, in exactly the same way that we can take a string, and break it up into a path part and a query part, and then break the query part into a sequence of key and value pairs, we can also take the path part and break it up into a sequence of path segments.
It might help to look at RFC 6570, which describes URI templates, or to look at how the Java annotation javax.ws.rs.Path is used in routing, but under the covers it is all just string manipulation plus conventions for finding the right String to X parsing function.

Multiple requestparam, rest philosophy and good pratice

I have many crud operation.
User must be able to search by many field of the resource.
Some have around 10.
I could use RequestParam, but method will have a lot of parameter an habitually it's not a good pratice.
/card?id=2&imso=trx&icco=98x&type=23&scm=988&createat=2017-02-01
Is there another good solution?
There are two issues here and depending on what carries what importance to you - you can approach a solution.
Problem # 1 : Long REST URLs at client
Problem # 2 : Controller methods with long & complicated signatures
Solution 1 : You group your #RequestParam into optional & mandatory parameters and then you create a DTO only for optional parameters. Then You can have your controller method signature like controllerMethod(#RequestParam param1 , #RequestParam param2, DTO dto).
Note that, you don't use #RequestBody before DTO.
Values for DTO will be passed in client URL itself like before and Spring MVC automatically converts it into DTO.
This solves complicated controller method signature but not long URL problem while you retain your request type to be GET
It is assumed that usually mandatory parameters are only a few and there is always a long list of optional fields.
Solution 2: You change server side to convert your GET request to a POST and start accepting a #RequestBody DTO. This solves both the problems but your original API changes to POST type.
As far as I know, changing a GET to POST shouldn't be a problem in most cases but vice versa is not true.

Do I need to provide an IFormatProvider when converting a date to a string with a specific format?

If I'm using this:
DateTime.Now.Date.ToString("yyyy-MM-dd")
FXCop complains that I'm violating CA1305 and says that I should provider an IFormatProvider. Do I need to? I'm asking for the date in a specific format anyway (which is the format I'm expected to put it into the XML as).
Would providing a format provider make any difference? Might it actually produce the wrong results in this case?
Why don't you want to specify the format provider?
If it is just laziness then I can recommend defining two snippets. ic for CultureInfo.InvariantCulture and cc for CultureInfo.CurrentCulture.
Never assume anything about how conversion to string works with the default culture. Not everyone in the world uses the gregorian calendar. Some day you customer might hire a contractor with a computer with another calendar as default and then you are not generating correct XML. Explain then to your customer that you didn't want to follow the FxCop recommendation.
Best thing would be if .Net included a Xml Culture. Then you could just do
DateTime.Today.ToString("d", CultureInfo.Xml)
For some reason Microsoft choose to create a separate class instead XmlConvert. The class has been there since .Net 1.0.
XmlConvert.ToString(DateTime.Today, "yyyy-MM-dd")
will always create a correct Xml date.
Not sure if it is bug or intended behaviour but XmlConvert.ToString(DateTime.Today, "d") will not create a valid Xml date.
so after a bit more research it seems that in my instance it doesn't make any difference, but in the general case months might be displayed in a specific locale.
More details here:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

Issue: Action redirect do not include parameter as complex objects in Struts2?

I have tried an example in which i have inserted a user using insert method of UserAction class.
On insert I have redirected the success to loadAdd method of UserAction.
During redirect I have passed the parameter as
${user}
In struts 2.0.14 this gives an ognl exception.
whereas when I pass
${user.id}
it works.
My observation says this is a bug in struts or ognl that it does parse composite objects while it parses simple data types.
Any work-around please suggest.
Or
Is there any way by which I can forward the complete action context or value stack in the redirected action
It's not a bug.
Struts2 uses a type conversion system to convert between Strings (native HTTP) and other objects. It has default type converters for all of the standard primitives, boxed primitives, collections, maps, etc. If you want to allow Struts2 to automatically convert between a string and your User class, you need to create a type converter for it. Otherwise, you can use ${user.id}, which is a primitive or boxed primitive.
http://struts.apache.org/2.2.3/docs/type-conversion.html
Also, the ValueStack is per-request, so when you redirect and create a new request, the previous requests ValueStack is no longer available.

GWT - internationalization of entity properties

I'm looking for an elegant solution for the following problem:
In my database, I have some predefined(!) entities. These entities have names and descriptions (Strings). Around the data access layer, there are some EJBs containing business logic to load/search for/etc. those entities.
Now for the frontend, we are developing a GWT application which calls the EJB methods on our backend.
The problem is, that the name and the descriptions of the entities mentioned above must be internationalized - e.g., depending on the user's locale, an entity's description must be "My cool description" (English) or "Beschreibung bla" (German) or whatever :)
My first approach was to use a resource string in the database. So entity A has a description "descriptionA", entity B has a description "descriptionB"... Later on, the GWT app (or any other client) translates this resource string into the actual description using some kind of "resource bundle". E.g.:
*resources_en.properties*:
descriptionA=Actual Description of Entity A
descriptionB=Actual Description of Entity B
*resources_de.properties*:
descriptionA=Beschreibung A
descriptionB=Beschreibung B
(Remember, the entities are predefined, so it's possible to "know" all descriptions at compile time. BUT it would be better if the resource bundle could be enhanced without having to recompile the application).
Is this possible with GWT? How can I do this? Is it better to "translate" on the server or on the client side?
Otherwise, I've to deal with all that i18n stuff on the backend side. Well, this would allow to keep data together (instead of defining the descriptions on the client side). But the big drawback is that the backend must be aware of the caller's locale.
Regards,
Frank
It's mainly a decision between download time/speed vs flexibility. If you compile it GWT inlines the messages and can generate a little faster code, because no string lookup has to be done. However, if you need to make changes and don't want to recompile or want to be a able to let users dynamically alter messages you need dynamic messages.
Regarding the latter case, the Dictionary class can help you with this, see also: http://code.google.com/webtoolkit/doc/latest/DevGuideI18n.html#DevGuideDynamicStringInternationalization
With the Dictionary you generate all messages in the static page served to the user. The users locale can be found in the header Accept-Language, which is send by the browser when a page is requested.
In either case (compiled or dynamic) you might want to serve the locale set by the user in some configuration property and in that case you still need logic for both cases on the server side to serve the locale to the user.
Everything is possible for those who try...
Back to your question: there are several ways to resolve your issue. One would be to introduce some kind of i18n facade and treat your descriptions and names as resource keys. Then you could define convenience methods to access translations i.e. public String translate(String message, Locale locale);. This method could use standard Java ResourceBundle class to access resources at runtime.
The only real problem I see is how to deal with compound messages (i.e. "Blah, blah 4 items" where 4 is a placeholder). Well, what we did in one project in similar situation, we added delimiter and actual resource key then another delimiter and count: "Blah, blah 4 items##items.in.your.whatever##4". In the case of English you could simply trim the first part and for other languages you would need to process whole string.