Culture-sensitive string sorting - javascript

In my .NET c# code, I would like to sort some strings - specifically, currently my app support two locales, English and Chinese (possibly more in future). And I would like to return a list of names to the client side.
right before the list of strings is returned to the client, I would like to sort the strings.
I basically need to do what Javascript does for "localeCompare". Is that something that can be done on the C# code? I found some thing related to CultureInfo, but it seems to me that I need to set that value dynamically.

There is a Sort overload, accepting an IComparer, that can be used culture aware.
Your client should pass it‘s desired language via Accept-Language request-header when requesting the API or it could be a claim or setting for the logged in user.
Here is an example within your controller on the API side:
var requestLanguage = "zh-Hans"; // pass the correct one
namesList.Sort(StringComparer.Create(new CultureInfo(requestLanguage), true));
The true parameter indicates that it’s case sensitive. You can find the cultureinfo on MSDN.
Docs about the String Comparer.

Related

Using accept language header to guess user's country, if available

I want to use Javascript/PHP to determine if a user's browser has a country (locale variant) defined in the accept-language header.
Knowing that the contents of the accept-language header value can vary, and is not always accurate, is there a way to logically determine if a country present in the accept-language header string? And then extract that via JS?
For example, if a user's accept language header contains en-US, I would want to set a local variable="US".
My intial thought was to create a very large array of all accept header language and locale values and check against that, but that did not seem like a very efficient approach.
The Accept-Language header has a couple of formats it can take, see the documentation on MDN. Getting the preferred languages as a structured list (like an array sorted by q-factor) is just a matter of parsing that list in a way that is resilient to all the possible permutations of the header values.
Instead of trying to write this logic yourself, it's simpler to use a library built for this exact purpose, which will be better at handling all kinds of weird edge-cases. For example, willdurand/Negotiation allows you to parse the Accept-Language header and match it to a list of locales supported by your site to find the best language to use.
You will have to do this on the server-side (in PHP). Once you know the language, you can pass that to client-side JavaScript in a number of ways. For example, you can use the JS tag to include a piece of JavaScript in your page template that sets a global variable with the determined language.

Go templating engine that also runs in the browser

I'm developing a web application with Go on the server, and the router will use PushState, so the server will also have to be able to render my templates. That means that I'll need a templating engine that works with Go and Javascript. The only one I've come across so far is Mustache, but it doesn't seem to be able to handle lowercase properties of structs, and there also doesn't seem to be a possibility to provide custom names like JSON:
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
So, is there a templating engine that is available in both Go and JavaScript, and that can handle lowercase struct properties?
As the comments above state, you can't expect any 3rd party library to be able to read lowercase properties on your struct, but it appears you are trying to use tags to represent alternative representations of your struct (as you can with the encoding/json library).
What you can do is use something like github.com/fatih/structs to convert your structs to maps and then range through to lowercase all of your keys (copying the values and removing the uppercase versions) and pass it into mustache.Render() as your context. If you want to use struct tags like the encoding/json library does, you'd have to use the reflect package and write a struct-to-map function that takes into account the tags on the struct (basic example given in the documentation here). There are some SO answers on how to write a struct-to-map function using reflection, which you can improve upon to add struct tag handling as you need.
To answer your question, I don't think this is something a current templating library does that also works with javascript, but it shouldn't be too hard to get working with mustache given the idea above.

Angular app and internationalization and localization

we have an existing silverlight app which runs in browser + on hardware.
we want to rewrite this app using angular js and html5.
one of the key requirements with new system is support of internationalization and localization. and target countries are usa, brazil, italy for now.
Am new to this area and have lot of basic questions.
does existing database needs to be redesigned to support same ? i mean to identify columns (product_name/customer_name etc) that needs to have locale specific data and then store data for each locale and modify sprocs and webapi to accept language parameter and then get content based on that. ?
I believe we need to user nvarchar for such columns.
what will happen to currency and date time columns in db ? say there is quantity column then what should be data type of this column in db ? if current locale is Portuguese then will qty stored in Portuguese number.
what is the best practices for storing and retrieving currency column
based on locale.
what is the best practices for storing and retrieving date column
based on locale.
how to handle string checks, numeric checks in webapi methods ?
how to do comparison and checks in javascript for string,number,datetime
please share link to some good pointers which could help.
so in short right from javascript to .net webapi to database (sql) how should we take care of locale dependent logic and fields
thanks.
A lot of questions, let's see if I can answer those.
If your existing application is properly internationalized, I don't think there is any need to modify the database. Just make sure it is able to handle international characters (NCHAR, NVARCHAR, NTEXT in MS SQL, valid character encodings in others).
As for DB design, it is good to keep things locale-independent as long as you can. For instance it is better to store keys in the database and resolve them at runtime. However, if your data is dynamic (i.e. you have product names and their descriptions that changes often), the only way to go is to have translation table and look the data up using valid locale. It's quite complex in relational world (i.e. joins), but it could be done.
2,3. All the numeric columns should be kept locale-independent and formatted on the UI side. The more problematic would be prices and sales orders - you would need an additional column to store the currency code (i.e. 12.34 | USD). On the UI side you would need to pass the code to the Angular currency filter. The only gotcha here is, Angular does not support easy locale context switching, so you would need to use a hacky library like Angular Dynamic Locale to load the formats for you.
Similar. Keep it locale-independent. DB built-in types should automatically handle that for you and give you nice DateTime/DateTimeOffset (in a .Net world) back. The only gotcha would be the time zone - it may make sense to use DATETIMEOFFSET MS SQL type, as others does not store time zone.
There is an alternative way to store date and times in the database - you may decide to store it as a number of milliseconds since January 1, 1970 UTC - as BIGINT type. Especially if you are going to read this directly to JS, you will be able to easily re-create JS Date object (should you need this for calculations or something) in a valid time zone (it works the other way round as well). All you have to do to format date is to use this number (not date, that is AFAIR) and Angular's date filter with UTC as a parameter.
I don't think I understand what you're asking exactly. I guess the question is about validation of user input, rather than API. Well, beware of using Regular Expressions, because JavaScript doesn't handle Unicode well (at least in this area). You'd need to ask more precise question.
Assuming that you have Number and Date objects (i.e. typeof o == 'number') it is straightforward (as in obj1 === obj2).
As far as strings are concerned... Well, str1 === str2 will give you valid answer if you want to be exact. If you want to sort them, modern web browsers (Chrome 14+, Firefox 29+, IE11+) implement EcmaScript 402 Internationalization API so you can do something like str1.localeCompare(str2, locale), see this article.
The real problem occurs when you want to compare two strings case insensitive and accent insensitive for equality (as oppose for ordering like in case of sorting). Basically, there is no way (and this is true even in "big" programming languages like Java or C#).

Underscore parameter for ping and negotiate

Where is the underscore parameter generated from on SignalR URLs?
e.g. the XHR GETs to /signalr/negotiate?_=1234561234 and /signalr/ping?_=789012341234
It doesn't appear to be passed from the server so I am wondering if it is a purely client side generated value?
I am asking as am I attempted to write a script to performance test the application but I do not know what to use for these parameter values. I guessed that this might be randomly generated but I wish to confirm or disconfirm this. Usually these are based on time, but they don't seem to be the usual UNIX epoch time format.
Please answer with specific reference to SignalR and if possible the code snippet where this is generated.
Most libraries when provided a no caching flag use _ as a key to suffix random query parameter to avoid url caching.
e.g if in jQuery, you do $ajaxSetup -> cache:false, then a key _ with value equal to current timestamp gets appended in every url call.
So yes, this is most probably client side addition.

Can I have an URL query with numerical, possibly equal (non-unique) keys?

I am building an HTML5 single page app, and I want to allow the user to keep the current application state for later use. I want to achieve this by creating a link URL to my page, with a specially crafted query part. When called again, with the URL, the application would parse the query part and recreate the stored state.
Now, some part of the state is a list, whose items are numerical values and an associated text. The floating-point numerical values, as well as the text is not required to be unique.
Like this:
4.54 first
12.1 another
12.1 more
34 more
My intent is to create an URL like so:
www.myappdomain.com/SinglePage.html?4.54=first&12.1=another&12.1=more&34=more
Is this a legal URL? Given proper encoding of the text, will this work in the wild?
I have read What Every Developer Should Know About URLs by Alan Skorkin, which I can generally recommend about URLs and this Answer about URL character usage.
To me, doing it that way seems legal but I still feel a little uncomfortable, since I have not found information about the possibly non-unique keys I might have and about numbers as keys in query parts in general.
Edit: I've brought it to work, see below (tell me if link ever breaks):
http://quir.li/player.html?media=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D0VqTwnAuHws&title=What%20makes%20you%20beautiful&artist=The%20piano%20guys%20covering%20One%20Republic&album=Youtube&6.49=Intro&30.12=Knocking%20part&46.02=Real%20playing&51.5=Piano%20forte&93.32=Stringified&123.35=Vocals&139.38=Key%20cover%20jam&150.16=Good%20morning%20sky&173.96=Final%20chord
This is a legal URL by the URI specification -- https://www.rfc-editor.org/rfc/rfc3986. However, whether this will work in the wild is a different issue since the specification only defines the generic syntax of URIs.
Since there is no specification on what should be done for duplicate keys in the query part (see Authoritative position of duplicate HTTP GET query keys) different software frameworks will treat such URIs differently. However, most frameworks will correctly detect duplicate keys as multiple values with the same key and group such values into a single array/list of values for the given key (rather than using the last value with the given key and discarding all the previous values for that key). Using numbers as keys is also OK since keys are parsed as text strings. In short: you should be safe.
I don't think it a good way to pass data, query string parameters generally regarded as parameters that can be accessed by their name, here you actually pass some data as parameters , while from technical point of view this can be done it makes your code somewhat obfuscated, I would pass this data in a single parameter using JSON encoding
This post suggests that there is no spec which says that non-unique keys are invalid.
Authoritative position of duplicate HTTP GET query keys
I can't seem to find anything concrete about number keys.
However, this might be a workaround if you don't want to use non-unique numeric keys for any reason: Use some basic encoding to map numbers to strings. Something basic could be 1-a, 2-b, 3-c, 4-d...9-i, 0-j. And '.' could be 'k' (if there is not spec about whether '.' is a legal character in a URL parameter)
Then, e.g., 21.3 would encode to bakc. Also you can add a number in the end of the encoded key to ensure that keys are unique. These numbers would be ignored while decoding (or could help differentiate between the parameters). Then the first 21.3 would encode to bakc1, the next bakc2 etc)

Categories

Resources