ModelState invalid for decimal (2000.00) - javascript

I'm having trouble validating 1 instance of my model medewerker_functie.
In that Model I have 3 instances that are decimals, 2 of them are being validated while Salary isn't.
The 3 instances are uren which is 40.0, fulltime_salaris which is 2200.00, salaris which is 2000.00.
In my Actionresult Create I get those values as strings, the reason of that is I get the value from a field with JavaScript: upon filling in the salaris input field:
onblur="$(this).val(parseFloat($(this).val()).toFixed(2))"
for display purposes.
And then just before the AJAX call, I get the values using jQuery and thought I'd try and make it a number type value so I did another parseFloat(2000.00).toFixed(2) but that just keeps it as a string and doesn't change the value.
This is my ActionResult Create:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,medID,functieID,type_contract,startdatum,einddatum,aantal_uur,aantal_dagen,fulltime_salaris,salaris")] medewerker_functie medewerker_functie, int medID, int functieID, string contract, DateTime startDate, DateTime? endDate, String uren, int dagen, String fulltime, String salaris)
{
System.Globalization.CultureInfo culInfo = new System.Globalization.CultureInfo("en-EN", false);
decimal dec_uren = Convert.ToDecimal(uren.Replace('.', ','), culInfo);
decimal dec_fulltime = Convert.ToDecimal(fulltime.Replace('.', ','), culInfo);
decimal dec_salaris = Convert.ToDecimal(salaris.Replace('.', ','), culInfo);
//Vervang decimaal punten met comma's
//uren = uren.Replace('.', ',');
//fulltime = fulltime.Replace('.', ',');
//salaris = salaris.Replace('.', ',');
//decimal dec_uren = Convert.ToDecimal(uren);
//decimal dec_fulltime = Convert.ToDecimal(fulltime);
//decimal dec_salaris = Convert.ToDecimal(salaris);
//vull medewerker_functie met waardes
medewerker_functie.medID = medID;
medewerker_functie.functieID = functieID;
medewerker_functie.type_contract = contract;
medewerker_functie.startdatum = startDate;
medewerker_functie.einddatum = endDate;
medewerker_functie.aantal_dagen = dagen;
//These are the fields in question but mostly just salaris.
medewerker_functie.aantal_uur = dec_uren;
medewerker_functie.fulltime_salaris = dec_fulltime;
//medewerker_functie.salaris = Convert.ToDecimal(salaris);
medewerker_functie.salaris = dec_salaris;
if (ModelState.IsValid) //The value '2000.00' is not valid for salaris
{
db.medewerker_functie.Add(medewerker_functie);
db.SaveChanges();
return RedirectToAction("Details", "medewerker");
}
ViewBag.functieID = new SelectList(db.functie, "ID", "Functie1", medewerker_functie.functieID);
ViewBag.medID = new SelectList(db.medewerker, "ID", "roepnaam", medewerker_functie.medID);
return View(medewerker_functie);
}
In my model they're also specified as decimal:
public decimal aantal_uur { get; set; }
public Nullable<decimal> fulltime_salaris { get; set; }
public Nullable<decimal> salaris { get; set; }
Also my globalization is set to nl-NL:
<globalization culture="nl-NL" uiCulture="nl-NL"/>
I've tried converting to decimal with culInfo and without, with replacing, to . and the other way around and without, but none of it seems to be working, any thoughts?
But what's even more confusing to me is that it does accept 2200.00 for fulltime_salaris and 40.0 for uren.
Oh and in my database the fields are also specified as decimal(18,2);
And I figured I'd mention it was quite the search for the error because it was nearly buried, but this is where I found the error:
EDIT
This is the AJAX call:
console.log(uren, fullTime, salaris); //returns 40.0, 2200.00, 2000.00
console.log($.type(uren), $.type(fullTime), $.type(salaris)); // returns string, string, string
var floatUren = parseFloat(uren).toFixed(1);
var floatFullTime = parseFloat(fullTime).toFixed(2);
var floatSalaris = parseFloat(salaris).toFixed(2);
console.log(floatUren, floatFullTime, floatSalaris); //returns 40.0, 2200.00, 2000.00
console.log($.type(floatUren), $.type(floatFullTime), $.type(floatSalaris)); // returns string, string, string
var form = $('#__AjaxAntiForgeryForm');
var token = $('input[name="__RequestVerificationToken"]', form).val();
$.ajax({
type: "POST",
url: '#Url.Action("Create", "medewerker_functie")',
data: {
__RequestVerificationToken: token,
medID: medewerker,
functieID: functie,
contract: contract,
startDate: startDate,
endDate: endDate,
uren: floatUren,
dagen: dagen,
fullTime: floatFullTime,
salarispara: floatSalaris
},
success: function() {
alert('Succes!');
},
error: function() {
alert('Failure!');
}
});

The fix was changing the name of the parameter String salaris. I can only assume it was conflicting with the Bind parameter Salaris so I was placing dec_salaris in the Model but the ModelState.IsValid was checking on the Bind param Salaris which was still a string, thus invalid..
Thanks everyone for your assistance x)

Related

Java Filter string values separated by comma

Below is the string of values separated by commas. Need to filter each values and append them with specific values.
String values - Hello, MyName, Is, XYZ
Above is the string that i am sending through an API
What i want is - How to add (_true) this string value to each element on above String Values. That also to few String values that i am checking with some specific condition
So that it should be like below in that API call which is sent to FrontEnd.
Hello(_true), MyName, Is, XYZ(_true)
public static String StringAppenderWithLogic(String given, String del) {
return String.join(del, Arrays.stream(given.split(del)).
map(p -> {
//put any logic specific to your requirement
if (p.trim().startsWith("H") || p.trim().startsWith("X")) {
p = p + "(_true)";
}
return p;
}).collect(Collectors.toList()));
}
You can try this
import java.util.*;
import java.util.stream.Collectors;
public class Main
{
public static void main(String[] args) {
String apiOutput = "Hello, MyName, Is, XYZ";
List<String> s = List.of(apiOutput.split(", ")).stream()
.map(Main::stringController)
.collect(Collectors.toList());
String result = String.join(", ", s);
System.out.println(result);
}
private static String stringController(String in){
if(hasMatchCondition(in)){
return in + "(_true)";
}
return in;
}
private static boolean hasMatchedCondition(String in){
//place your logic here
//[START] exemple
if(in.length() == 5 || in.length() == 3)
return true;
return false;
//[END] exemple
}
}

JS: Getting "0" if input or formula result has decimal value

I'm trying to create a virtual shop.
Everything works fine unless the input values are decimal despite they're being declared as decimals, as you can see in the attached printscreens.
How do I get past this?
var total = (parseInt($("#quantity").val()) * parseFloat($("#price").val())) +
(parseInt($("#quantity").val()) * parseFloat($("#price").val() * (parseFloat($("#IVA").val()) / 100)));
$("#total").val(total);
public int ID { get; set; }
public int OrderID { get; set; }
public int ProductID { get; set; }
public decimal Price { get; set; }
public int Quantity { get; set; }
public decimal IVA { get; set; }
public decimal TotalPrice { get; set; }
https://i.stack.imgur.com/aj3ti.png
https://i.stack.imgur.com/fnJ1E.png
Since you are working with currency, you probably want to use toFixed() to round all your values to 2 decimal places.
var total = "246.6880000000000001" * 1;
console.log(total.toFixed(2)); // outputs 246.69
Not only is this good for trimming long trailing rounding errors, but it will also help with formating things like 147.6 to 147.60 so that it is all in the same standard currency format.

GetSafeHtmlFragment is still not working as expected to stop cross site scripting in c#

What I want is, I want to stop user from entering invalid code like hi<script>alert('1')</script> or other invalid characters what an attacker can insert.
So For that I tried the below code by using
[HttpPost]
[ValidateInput(false)]
public JsonResult InitiateWFfttx(string FSAID, string CREATEDBY, string MZONECODE, string MZONENAME, double COMLEG, double UGLEG, double ARLEG, double MDULEG, int STATUSID, string HOTOOFFERDATE, string REMARK, double HOTOOFFERLEG, int UMSGROUPIDBY, string UMSGROUPNAMEBY, int UMSGROUPIDTO, string UMSGROUPNAMETO, string SPANTYPE)
{
string strMessage = "";
string Message = "";
string msg = "";
try
{
string strRemarks = "";
strRemarks = Sanitizer.GetSafeHtmlFragment(Convert.ToString(REMARK)); // here it is by passing the invalid character
if (strRemarks != "")
{
CTManagement ObjCTMang = new CTManagement();
ApplicationLog.Trace("Info", "Initated the process", UMSGROUPNAMEBY, CREATEDBY);
Message = ObjCTMang.InitiateWorkflow_Fttx(FSAID, CREATEDBY, MZONECODE, MZONENAME, COMLEG, UGLEG, ARLEG, MDULEG, STATUSID, HOTOOFFERDATE, REMARK, HOTOOFFERLEG, UMSGROUPIDBY, UMSGROUPNAMEBY, UMSGROUPIDTO, UMSGROUPNAMETO, SPANTYPE);
string state = Message.Split('|')[0];
string req_id = Message.Split('|')[1];
if (state == "SUCCESS")
{
//Code commented for optimizing the Job createing response by Jyotir
//SendEmail(CREATEDBY, UMSGROUPIDTO, UMSGROUPNAMETO, UMSGROUPNAMEBY, "NEW", req_id, SPANTYPE, R4GState, MZONECODE, REMARK, SPANTYPE == "INTERCITY" ? SPANID : LINKID);
ApplicationLog.Trace("Info", "Sucessfully generated Request Id: " + req_id, UMSGROUPNAMEBY, CREATEDBY);
}
}
else
{
Message = "ERROR|Invalid text not allowed in Remarks";
}
strMessage = JsonConvert.SerializeObject(Message);
}
catch (Exception ex)
{
if (Message.Length > 0)
{
msg = Message.Split('|')[1];
}
else
{
msg = ex.Message;
}
//ErrorLog.HandleErrorLog(CREATEDBY, SPANID, "InitiateWF", msg);
/*
* Error(string LogType, string functionname, string msg)
*/
ApplicationLog.Error("Error", "InitiateWFfttx", msg);
}
return Json(strMessage);
}
Please suggest how to encode this.
strRemarks = Sanitizer.GetSafeHtmlFragment(Convert.ToString(REMARK)); here its bypassing the html fragment.
Here is how the Sanitizer works
string REMARK = "hi<script>alert('1')</script>";
string strRemarks = Sanitizer.GetSafeHtmlFragment(Convert.ToString(REMARK));
Console.WriteLine("Sanitizer output:" + strRemarks);
This will properly show hi as output. Why? Because the sanitizer will totally remove everything but the html tags.
The script tag is a definite problem as most xss attacks start with injecting some kind of javascript.
To make your code work change your if to
if (strRemarks.Equals(REMARKS))

Verify private key in signed XML with public key

I use javascript to open CAPICOM store to choose certificate.
After that I export selected certificate, public key and private key of that certificate and put them in three hidden fields.
var privateKey = certificates.Item(1).PrivateKey;
var cert = certificates.Item(1);
var publicKey = cert.PublicKey().EncodedKey.Value
When signing xml I used:
To take certificate
Dim hideCertCapicom As String = Replace(HiddenCert.Value, " ", "+")
Dim certificate As New X509Certificate2(Convert.FromBase64String(hideCertCapicom))
For defining private key I used
Dim keyC As String = hideKey
Dim cspp As New CspParameters()
cspp.KeyContainerName = keyC
Dim tmpRsa As New RSACryptoServiceProvider(cspp)
tmpRsa.PersistKeyInCsp = True
This will successfully signed my xml.
For verifying xml I used:
Dim hidePublicKey As String = HiddenPublicKey.Value
Dim keyC As String = hidePublicKey
Dim cspp As New CspParameters()
cspp.KeyContainerName = keyC
Dim tmpRsa As New RSACryptoServiceProvider(cspp)
tmpRsa.PersistKeyInCsp = True
But this doesn't work. It works only if I use the private key again.
Is it good practice to sign and verify with the same private key or to do both with public key?
I was able to sign with private key and verify the signature with public key, and I want to share with you.
In SignXml() function I exported public key from private key:
Dim publicKey as String = tmpRsa.ToXmlString(False)
Then in the same function I call verifyXml() function:
Dim verifySign As Boolean
verifySign = VerifyXml(doc, publicKey)
In verifyXml() function I took public key on this way:
Public Function VerifyXml(Doc As XmlDocument, Key As String) As Boolean
Dim tmpRsa As New RSACryptoServiceProvider()
tmpRsa.FromXmlString(Key)
Dim signedXml As New SignedXml(Doc)
Dim nodeList As XmlNodeList = Doc.GetElementsByTagName("Signature")
If nodeList.Count <= 0 Then
Throw New CryptographicException("Verification failed: No Signature was found in the document.")
End If
If nodeList.Count >= 2 Then
Throw New CryptographicException("Verification failed: More that one signature was found for the document.")
End If
signedXml.LoadXml(DirectCast(nodeList(0), XmlElement))
Return signedXml.CheckSignature(tmpRsa)
End Function

while assigning value to asp hidden field, escape character gets cleared

I am following one strange issue. Following is the detailed description
My object of JSON String
public class ChartSearchCriteria
{
public ChartSearchCriteria()
{
}
public DateTime StartDate
{
get;
set;
}
public DateTime EndDate
{
get;
set;
}
public Int32 ClassType
{
get;
set;
}
public Int32 InstructorID
{
get;
set;
}
}
I am converting this object to JSON string and assigning to one hidden field
ChartSearchCriteria objChartSearchCriteria = new ChartSearchCriteria()
{
StartDate = startDate,
EndDate = endDate,
ClassType = Convert.ToInt32(ddlClassType.SelectedValue)
};
string jsonSearchCriteria = new JavaScriptSerializer().Serialize(objChartSearchCriteria);
// Here in jsonSearchCriteria i am getting following string
// "{\"StartDate\":\"\\/Date(1436466600000)\\/\",\"EndDate\":\"\\/Date(1439145000000)\\/\",\"ClassType\":0,\"InstructorID\":0}"
hdnSearchData.Value = jsonSearchCriteria;
I want to pass this json string to another page with query string. I have used following javascript to get url
alert(document.getElementById("hdnSearchData").value);
// Here i am getting following JSON string from hidden field
// {"StartDate":"\/Date(1436466600000)\/","EndDate":"\/Date(1439145000000)\/","ClassType":0,"InstructorID":0}
var searchData = JSON.parse(document.getElementById("hdnSearchData").value);
var redirectUrl = _spPageContextInfo.webAbsoluteUrl + "/_layouts/15/DetailedChart.aspx?searchdata=" + encodeURIComponen(JSON.stringify(searchData));
Now I have used following code to Deserialize that json string to object into another page where I have passed that json string as query string
string jsonString = Convert.ToString(Page.Request.QueryString["searchdata"]);
jsonString = HttpUtility.UrlDecode(jsonString);
// Here I am getting following json string
// {"StartDate":"\/Date(1436466600000)\/","EndDate":"\/Date(1439145000000)\/","ClassType":0,"InstructorID":0}
JavaScriptSerializer oJS = new JavaScriptSerializer();
ChartSearchCriteria oRootObject = new ChartSearchCriteria();
oRootObject = oJS.Deserialize<ChartSearchCriteria>(jsonString);
So here i am getting exception like:
"Date(234234000)" cannot be converted to date time when Deserializing json string to object
The only thing which I get is that while assigning to json string to hidden field, It is losing escape character from json.
JSON String created from server side :
{\"StartDate\":\"\/Date(1436466600000)\/\",\"EndDate\":\"\/Date(1439145000000)\/\",\"ClassType\":0,\"InstructorID\":0}"
JSON string gotten from client side using javascript:
{"StartDate":"/Date(1436466600000)/","EndDate":"/Date(1439145000000)/","ClassType":0,"InstructorID":0}
So you can see above both different string which shows while assigning json string to hidden field , it is removing escape characters and that's why I cannot convert it back to object into another page.
I am sure 100% that it is issue related to escape character because i have checked deserialize method with following string and it is working fine
{\"StartDate\":\"\/Date(1436466600000)\/\",\"EndDate\":\"\/Date(1439145000000)\/\",\"ClassType\":0,\"InstructorID\":0}"
So how can I resolve that issue? My final goal is to pass json string to another page and deserializing into same object.
Any help will be highly appreciated and let me know anyone want some more information on it.
I have resolved issue by using following code.
string jsonString = Convert.ToString(Page.Request.QueryString["searchdata"]);
jsonString = HttpUtility.UrlDecode(jsonString);
// Here I am getting following json string
// {"StartDate":"\/Date(1436466600000)\/","EndDate":"\/Date(1439145000000)\/","ClassType":0,"InstructorID":0}
// By using following line I have corrected json string and now it is being deserialized to object.
jsonString = jsonString.Replace("/", "\\/");
JavaScriptSerializer oJS = new JavaScriptSerializer();
ChartSearchCriteria oRootObject = new ChartSearchCriteria();
oRootObject = oJS.Deserialize<ChartSearchCriteria>(jsonString);

Categories

Resources