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

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);

Related

Convert string with '=' to JSON format

I am trying to convert a string i receive back from an API into a JSON object in Angular.
The issue is that the string is not normalized to be parsed into JSON easily.
This is the string im working with:
"{rootCause=EJBusinessException: This is a sample exception thrown for testing additional info field, description=This is a more detailed description about the incident., stackTrace=com.springboot.streams.infrastructure.web.heartbeat.HeartbeatService.testServiceNow(HeartbeatService.java:200)}"
When trying to do JSON.parse(myStr) it throws an error due to invalid string format.
Is there an easy way to convert the listed string into a more correct JSON format, getting rid of the '=' and replacing them with ':' instead.
There is more to it than just .replace(/['"]+/g, ''), as even with that the string is not ready to be turned into JSON yet.
Hoping someone more versed in Javascript knows a trick i dont.
You just need to manipulate the string before parsing it remove unecessary string that can cause error to the object like "{" and "}" and split it by "," example is in below.
var obj = {}, str = "{rootCause=EJBusinessException: This is a sample exception thrown for testing additional info field, description=This is a more detailed description about the incident., stackTrace=com.springboot.streams.infrastructure.web.heartbeat.HeartbeatService.testServiceNow(HeartbeatService.java:200)}"
str.split(",").forEach((st, i) => {
pair = st.split("=")
if(pair.length > 1) {
obj[pair[0].replace("{",'').replace("}", '').trim()] = pair[1]
} else {
obj[i] = pair
}
})
console.log(obj)
As commenters have posted, unless you control the API or at least have documentation that output will always follow a specific format, then you are limited in what you can do. With your current example, however you can trim off the extraneous bits to get the actual data... (remove braces, split on comma, split on equals) to get your key:value pairs... then build a javascript object from scratch with the data... if you need json string at that point can just JSON.stringify()
var initialString = "{rootCause=EJBusinessException: This is a sample exception thrown for testing additional info field, description=This is a more detailed description about the incident., stackTrace=com.springboot.streams.infrastructure.web.heartbeat.HeartbeatService.testServiceNow(HeartbeatService.java:200)}"
var trimmedString = initialString.substr(1, initialString.length - 2);
var pairArray = trimmedString.split(',');
var objArray = [];
pairArray.forEach(pair => {
var elementArray = pair.split('=');
var obj = {
key: elementArray[0].trim(),
value: elementArray[1].trim()
};
objArray.push(obj);
});
var returnObj = {};
objArray.forEach(element => {
returnObj[element.key] = element.value;
});
console.log(JSON.stringify(returnObj));

JSON to Go Structure

I have a JSON like
{
"company_id": "Sahil",
"company_name": "Sahil",
"ats_operators": ["123"],
"ids": [
{
"duns_id": "1234"
}
],
"company_symbol": "1234"
}
I wanted to convert the above JSON into the Go Structure.
I have one way to do it like:
type AutoGenerated struct {
CompanyID string `json:"company_id"`
CompanyName string `json:"company_name"`
AtsOperators []string `json:"ats_operators"`
Ids []struct {
DubnsID string `json:"dubns_id"`
} `json:"ids"`
CompanySymbol string `json:"company_symbol"`
}
But i wanted to use the Go-Map instead of Nested structure.
I tried to use the below code but it is unable to parse the above JSON.
type Test struct {
CompanyID string `json:"company_id"`
CompanyName string `json:"company_name"`
CompanySymbol string `json:"company_symbol"`
IDs map[string][]string `json:"ids"`
AtsOperators []string `json:"ats_operators"`
}
Please help and let me know what is the wrong with the above Go structure?
Do something like this and try. If you are fetching the data from mongodb then keep bson:"" part else just json tags is ok.
type DubnsID struct {
DubnsId string `bson:"dubns_id" json:"dubns_id"`
}
type AutoGenerated struct {
CompanyID string `bson:"company_id" json:"company_id"`
CompanyName string `bson:"company_name" json:"company_name"`
AtsOperators []string `bson:"ats_operators" json:"ats_operators"`
Ids map[string][]DubnsID `bson:"ids" json:"ids"`
CompanySymbol string `bson:"company_symbol" json:"company_symbol"`
}
You might have to use a struct like this:
type AutoGenerated struct {
CompanyID string `json:"company_id"`
CompanyName string `json:"company_name"`
AtsOperators []string `json:"ats_operators"`
Ids []map[string]interface{} `json:"ids"`
CompanySymbol string `json:"company_symbol"`
}

ModelState invalid for decimal (2000.00)

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)

JavaScript save JSON response to other file extension with nice format

I've written some code to generate CSR as well as the private key.
The response to <textarea> is formatted nicely with a newline (if you know what the proper CSR/Private key looks like).
I have a problem with saving the private key to .pfx file type, where it will not be formatted nicely.
Here's how it looks like in the browser when placed into a <textarea>:
-----BEGIN PRIVATE KEY-----
MIIEowIBAAKCAQEAsUM5i1BX1NWS1CGsou86LN3oRcfkA63FdqneDLi36602dxQO
pSPabp8lqR+LgIWq/nIxShbZgc5YwlmhylrqYm1jdHXUQlNhBjsJE6Y0SwybXD9k
ERyWgFfaFLeUjUTXax01/M9oh4JQ+o4pWz+cw3oUjklH5iviLx34bZMq0k5azLus
312FRgA1x2AKG4QWUwTijTISYZ4mtLDTli2iqWVvPpLi87hLKTAMmLdJZ8hJkXOJ
QYRALpiERwX4lhckh1xnr/NfzE+QY0zxGwmvE4Uk0MqT7liUfqPnXiMLIIGuC/pt
xf2SXQBv/A9eus2jI0gM627iyvbDdkw0E1B+5QIDAQABAoIBAQCjpZM/aSnc5FsM
GhZ9yWsktqzTlymKt+dfmIzVo8av/hYVMuAeVw42KBilnOi1+zEUfKnCY3vkGXLZ
4dO6s9pEigZSIuGVZdJh5SiJClymmHnpXOBt572NuQ0tKRosnUxep/YKchRnXciS
t6G4iu6XjGHjxg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KEY-----
How it looks like in the file:
"-----BEGIN PRIVATE KEY-----\nMIIEowIBAAKCAQEAsUM5i1BX1NWS1CGsou86LN3oRcfkA63FdqneDLi36602dxQO\npSPabp8lqR+LgIWq/nIxShbZgc5YwlmhylrqYm1jdHXUQlNhBjsJE6Y0SwybXD9k\nERyWgFfaFLeUjUTXax01/M9oh4JQ+o4pWz+cw3oUjklH5iviLx34bZMq0k5azLus\n312FRgA1x2AKG4QWUwTijTISYZ4mtLDTli2iqWVvPpLi87hLKTAMmLdJZ8hJkXOJ\nQYRALpiERwX4lhckh1xnr/NfzE+QY0zxGwmvE4Uk0MqT7liUfqPnXiMLIIGuC/pt\nxf2SXQBv/A9eus2jI0gM627iyvbDdkw0E1B+5QIDAQABAoIBAQCjpZM/aSnc5FsM\nGhZ9yWsktqzTlymKt+dfmIzVo8av/hYVMuAeVw42KBilnOi1+zEUfKnCY3vkGXLZ\n4dO6s9pEigZSIuGVZdJh5SiJClymmHnpXOBt572NuQ0tKRosnUxep/YKchRnXciS\nt6G4iu6XjGHjxgVpmkPTCdEqn73drkf4jeQQrXWJQeOFH3b0e7XwvkoBKrjn6Tu3\nuUURrNmeZRQnCGaj51wn8KYejCS7ReL071MdhwgJesCJzTpZFJ+HpLJSZI8FJQpd\npzX8rZ+4UfXMd1bcSaLMpgRZJrzGLx5uugO2sgTFelF6rzcg+yD+/JOETzSE3Am1\nL5TA7MA1AoGBAPsxFTGAwg3Vvwg2xrSBAaUu2Vu8R3mvCRp2fjX1Q9CUM5vJpkqH\n8h1xX3miVsGF//+W0yoSzVxcoPEALre5kiEQrmKYtXCaL6b4JY3BHJrUl4yIh0iO\n1luFitq/T4R2flmshESd4SolqvdrpTVg3vryj9v9X75sIFlssdV3slZDAoGBALSn\n3coa/8Dha5v+qBnWkHZcVGe/q9OOGJWloAbgI/S9TjcKqwe5u+EtvS2S3MurDbE6\nuUBC85wCqjDelc36mn84f0YXDDy6vtZp0HoErGL7/wXL5zn52iRmVvF31vU1ahcK\n2TT62MYQ8aCr7nNczvG8iF43hbfCd5c5yWDekwe3AoGAQ6REAMCbgP4+IwgdGh5j\nQwgKoBljZfEskmO2OPGDAXfnLdxvW0KggC03eJmuow5ikYEb/Ah0JJsM+9kAu5jN\nMPo8+3AD6/6ZNm08L6ABA/CbnsxlIbTVJHAhpCZAU3tVKvC57YBWUfMyxs3F/0nG\nwezvsF3amnyjeXE7sjA5ZeECgYBzsendTCssaHEVByK64WnFE15OzzaIlsDx3Y89\nt//u9emIYIGlwfIrxLIZ5KsYmCR9syD+oaIH8MDz6SjBMFQPU6xWw93naqVbBYsp\nCaMpBT+Og8ZCn9tvYkcd/2SfxyR5O05dmqSHPESyZEmigfZaZCZlSGOPirAyHiT0\nr7YzwwKBgAQSh1wgnlOaadkKHzItrXf9i9dUaAzuUYj/B/EpZR+y5ckXFuohpczE\nrQ4yJIgvynxKJW7r2AVS0ad/fbgh5YNCaykB8HDhP1ZQY8ng1ae6VoHRQiLZAdKx\ncAqWIvwWEjAFFbHixt4d3OChDlubpeB3p24MlWycc1H63L4RKAto\n-----END PRIVATE KEY-----"
My CSR code:
var csrResult = (JSON.parse(csr))
var csrResultResdata = JSON.parse(csrResult["resdata"]["csrgen"]["context"])
var csrResultResdataCSR = csrResultResdata["csr"]
var csrSpliter = csrResultResdataCSR.split("\n\n")
var csrOnly = csrSpliter[0]
var privateKeyOnly = csrSpliter[1]
var exportName = "private_key"
downloadObjectAsJson(privateKeyOnly, exportName)
My save as file code:
function downloadObjectAsJson(exportObj, exportName){
var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(exportObj));
var downloadAnchorNode = document.createElement('a');
downloadAnchorNode.setAttribute("href", dataStr);
downloadAnchorNode.setAttribute("download", exportName + ".pfx");
downloadAnchorNode.click();
downloadAnchorNode.remove();
}
I need help on format the file content.
The original response from API is:
{
"result": {
"code": "0",
"msg": "Command completed successfully"
},
"resdata": {
"csrgen": {
"context": "{\"csr\":\"-----BEGIN NEW CERTIFICATE REQUE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P5XmT2Ks7CSJAc5GL9sMCc0TcWBbYUYZkyK1fOAjtFK9UEma7J\\nni5iNSDIeJ+/bPUDeRspxHGgVHtXwEd7Cg8AGz1WJj+ETxmHUQdG124m4OjMxFnZ\\nI/R7ue0AZnAN5ggfC+sIuQKBgCfn0c3wjXBWIkNTYkqCrWa2r7dM9n/esTUbEVFl\\nHW28yfYTBpJFWU7lXOihHjZoyRYLbIdM08qDE1aQEvaaVSLCsJM1+BfYkSVDN/TW\\nK0fXwuhQeTnQTOiTqRqnEDjIaJVnOfCXFNFfJ6Wco5yGMReB2Pwc6PpJVHzWMwcP\\nZghJAoGBAKOscoFpm2qt25IfWJlIlLEC3IUNCNLAG2dQSndB+S1BnfNEPPnSWxOg\\ncVhmamk/w1L67RtzwJ69S6sTECwfnHDlOBLJwCTtVzGTfHZQ1QBctNnyZ1sHUetd\\nwX5QuEO1vsI/T7jpozg0PGr+5BE5r1kr6VjvPBe+WOhO/4X1wUFt\\n-----END PRIVATE KEY-----\",\"status\":\"Success\"}"
}
}
}
Why are you storing your PFX file as JSON formatted? Just remove the JSON.stringify and output it as plain text, seeing as what you're passing in is just a basic string anyway. All that stringify does is wrap it in quote marks and encode the newlines.
var dataStr = "data:text/plain;charset=utf-8," + exportObj;
Here is a JSbin of it working correctly: http://jsbin.com/lipaxuhidi/edit?html,js,output

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

Categories

Resources