Stop formData string from being converted to a date string representation - string

This one is being hard to uncover. We have a .NET Core 2.2 app in which we have a form with many fields and a field for the user to attach some file.
Problem: one specific field CaqhNumber has a min and max length = 8.
When the user types in a value for example 20200706 the value that get's sent to the server is a date string representation of this value. So on the server side we get:
07/06/2020
Basically it thinks this specific field is an ISO date.
How can one stop this from happening? We just want to get the string on the server side the way it was entered on the UI side. It's not a date. It's plain string in both sides.
Something tells me this is related to the .NET Core configs.

Guess what... there was a piece of code behind the curtains messing up with the value:
const isValidDate = moment(
value,
moment.ISO_8601,
true
).isValid();
if (isValidDate) {
formData.append(
key,
moment(value).format('MM/DD/YYYY')
);
The fix:
if (value instanceof Date) {
formData.append(key, moment(value).format('MM/DD/YYYY'));

Related

How to turn String Value into Number - Google Tag Manager

Im setting up my Google Tag Manager and I want to grab the purchase value from my Data Layer. This works fine, but Facebook doesn't recognize this value as its a "String" and not a number.
Therefore my question is: How can I convert this String (Return Type) to a Number (Return Type) in order for Facebook to pick it up? If that helps, its a currency.
Create JavaScript Variable named "String2Number Convertor"
function(){
return function(s){
return +s;
}
}
Create another JavaScript Variable named "Facebook Purchase Value"
function(){
return {{String2Number Convertor}}({{DataLayer Conversion Value}})
}
I assume you have your purchase value in data layer variable I called in this example as DataLayer Conversion Value
With this approach you can convert any other variables into number.

EPPlus - Mark cell as date data type without providing format

I have website application, where I generate excel file (server side).
// Get data to collection
var dates = _dbContext.dates.Select(x => new { x.FirstColumn, Date = Convert.ToDateTime(x.Date) }).ToList();
// Load collection into excel
ws.Cells["A1"].LoadFromCollection(dates, true, TableStyles.Medium6);
Now date column shows integer numbers (probably OADate (OLE Automation Date)).
The question is, can I somehow mark the date column as datetime without providing a specific format ? Just to switch category to date. The reason is that I do not know the language (and specific computer format settings) of the user and I want excel to handle this issue.
In your Controller you can capture the current users language settings from the Request Object, like so:
string language= Request.UserLanguages.FirstOrDefault() ?? "en-US";
If, for whatever reason, the collection is empty, you set a fallback language, here it is US English.
You then pass this string to your Excel function, and the first things you do in that function, is to create a new CultureInfo object with the users language and change it in the current thread:
CultureInfo currentCulture = new CultureInfo(language, false);
Thread.CurrentThread.CurrentCulture = currentCulture;
You can now style the cells of your choice, with the correct format by using the DateTimeFormatInfo.CurrentInfo type:
// Load collection into excel AND FORMAT THE CELLS
workSheet.Cells["A1"].LoadFromCollection(dates, true, TableStyles.Medium6).Style.Numberformat.Format = DateTimeFormatInfo.CurrentInfo.ShortDatePattern;

Obtaining FluentValidation max string length rules and their max values

We want to implement a character counter in our Javascript data entry form, so the user gets immediate keystroke feedback as to how many characters he has typed and how many he has left (something like "25/100", indicating current string length is 25 and 100 is the max allowed).
To do this, I would like to write a service that returns a list of dto property names and their max allowed lengths.
{Name='SmallComment', MaxLength=128}
{Name='BigComment', MaxLength=512}
The best way I can think of to do this would be to create an instance of the validator for that dto and iterate through it to pull out the .Length(min,max) rules. I had other ideas as well, like storing the max lengths in an attribute, but this would require rewriting all the validators to set up the rules based on the attributes.
Whatever solution is best, the goal is to store the max length for each property in a single place, so that changing that length affects the validation rule and the service data passed down to the javascript client.
If you want to maintain a single source of reference for both client/server I would take a metadata approach and provide a Service that returns the max lengths to the client for all types, something like:
public class ValidationMetadataServices : Service
{
public object Any(GetFieldMaxLengths request)
{
return new GetFieldMaxLengthsResponse {
Type1 = GetFieldMaxLengths<Type1>(),
Type2 = GetFieldMaxLengths<Type2>(),
Type3 = GetFieldMaxLengths<Type3>(),
};
}
static Dictionary<string,int> GetFieldMaxLengths<T>()
{
var to = new Dictionary<string,int>();
typeof(T).GetPublicProperties()
.Where(p => p.FirstAttribute<StringLengthAttribute>() != null)
.Each(p => to[p.PropertyName] =
p.FirstAttribute<StringLengthAttribute>().MaximumLength);
return to;
}
}
But FluentValidation uses Static properties so that would require manually specifying a rule for each property that validates against the length from the property metadata attribute.

Couchbase java sdk 1.4.7 numeric key in view Query not returning results

The view definition emits a string field from the document as a key. The field value can be all numeric or alphanumeric. Query using key with all numeric value does not return any row but alphanumeric key returns data.
On server web console and rest api, I could see the row so view is getting updated properly and hence leaning to believe that issue is with java sdk client.
Below is the code I use to query.
CouchbaseClient couchBaseDAO; // = initialize client.
String corelationId = "12345678";
Query query = new Query();
query.setKey(corelationId);
ViewResponse result = couchBaseDAO.query(queryConfig, query);
JSONArray jsonArray = new JSONArray();
if(result != null){
for(ViewRow row: result){
jsonArray.put(row.getValue());
}
}
return jsonArray.toString();
Map:
function(doc,meta) {
if(doc!=null && doc.requestData!=null) {
emit(doc.requestData.corelationId, [doc.request.id, doc.status]);
}
}
If I changed key to alphanumeric, it works.
String corelationId = "ab-12-09-a-123";
Java HotSpot 7.
Couchbase java sdk 1.4.7
Couchbase Server 3.0.3
Solution
Based on the information given in answer below, below are two options you have
Option 1 Server side map change
If you are building a new map than go for it. Harmonize your key to become always string emit("" + doc.requestData.corelationId, ...);
If your view already exists then all your existing documents will not change right away.
Option 2 Client side change
If you are like me where option 1 is not possible, go for harmonizing your key in your code. It overcomes's skd's logic to treat it as numeric.
corelationId = StringUtils.isNumeric(corelationId)?"\""+corelationId+"\"":corelationId;
Your view emits the corelationId as it is, in its original type. You said that in the documents it was alternating between a numerical value and a string.
If you pass the key to the SDK as a Long it will work.
(I suspect that in the web ui you naturally typed in 12345678 in the key field and not "12345678", so you did the correct equivalent of using a Long in the web UI)
If you cannot know the correct type to use for each key you search, harmonize the key type in the map function so that you know always to use strings:
emit("" + doc.requestData.corelationId, ...);

Xamarin Numeric only field

In my Xamarin forms View I have an entry control, to which I have added,
myEntry.Keyboard = Keyboard.Numeric;
to make it decimal only.
In Android devices this code will accept only one decimal point at any given time.
However in IOS, it accepts multiple decimal points?? Is there any way I can restrict only one decimal point in IOS too.
In Xamarin.Forms Entry you have a TextChanged event handler that you can tap into when the entry changes.
You are given both the old text string and also the new text string value.
You can then do a count on the number of decimal points that are in the new text string, check to see if it is greater than 1.
If it is, simply set the Entry.Text to the old value and then you will only ever have one decimal point.
Using the TextChanged event handler you can one of the various TryParse methods. These methods can be given specific cultures and styles also. Example below uses Double's version.
private void Entry_TextChanged(object sender, TextChangedEventArgs e)
{
string newValue = e.NewTextValue;
double value;
if (double.TryParse(newValue, out value))
{
// Do logic for valid value
}
else
{
// Do logic for invalid value
}
}

Resources