Escaping double quotes in JSON result - c#

I have a set of codes where i have done error handling. I want the result to be {"ErrorMessage": Server is down} However i keep getting the result as {"ErrorMessage":"Server is down"}.
Here are my codes:
catch (Exception e)
{
var result = "Server is down";
return Ok(new { ErrorMessage = result });
}
I have tried using '#' and '\' characters however it did not work. How do i escape those extra double quotes? Someone please do help me. Thank you so much in advance.

I have decided to leave the result as it is as {"ErrorMessage":"Server is down"} is the correct way of displaying a JSON output. As explained by #dbc, that is a valid JSON object with a property named ErrorMessage whose value is the string Server is down.

Related

Why am I getting invalid base64 when implementing the ChallengeNotification for GlobalPayments 3DSecure?

I plan on answering my own question as there is a shortage of support for Global Payments.
I'm following this guide: https://developer.globalpay.com/docs/browser-auth-3DS and when working on the challenge notification url and following the example code verbatim it's ultimately resulting in an error being displayed in the ThreeDSecure iframe:
Invalid Base64 string
Here's the example from their documentation:
var cres = Request.Form["cres"];
try
{
byte[] data = Convert.FromBase64String(cres); <-- THIS FAILS
string challengeUrlResponseString = Encoding.UTF8.GetString(data);
...
}
catch (Exception exce)
{
...
}
The reason for this issue is because it's not a valid base64 string. There are potentially invalid characters that will need to be replaced as well as proper padding:
var cres = payload["cres"].ToString();
var padded = cres.Replace("-", "+").Replace("_", "/").PadRight(cres.Length + (4 - cres.Length % 4) % 4, '=');
var data = Convert.FromBase64String(padded);
While I'm at it, in case you get stumped on the next portion... which is returning the result, you literally have to write the script in the response:
HttpContext.Current.Response.Write($"<script src=\"actual-path-to/globalpayments-3ds.min.js\"></script><script>GlobalPayments.ThreeDSecure.handleChallengeNotification({challengeUrlResponseString});</script>");
Or, in my case I'm using action result, so I just return it within:
return Ok($"<script src=\"actual-path-to/globalpayments-3ds.min.js\"></script><script>GlobalPayments.ThreeDSecure.handleChallengeNotification({challengeUrlResponseString});</script>");
This works for me, but if anyone knows of a better proper way, please share, as the docs are lacking.

Is there a method in c# to check if a string is a valid hexadecimal number?

I wanted to add a manual hexadecimal input for a C# repository of mine, I had no way of verifying if the user's input was a legitimate ARGB hexadecimal value the user had entered into the textbox or if it was a garbage hexadecimal number. Does anyone have a potential solution to this?
You can just use regex:
string pattern = #"^0[xX][0-9a-f]{8}$";
string input = "0x1a2b3C";
Match m = Regex.Match(input, pattern, RegexOptions.IgnoreCase);
if (m.Success)
{...}
So, I did a very inefficient method, I started off by making a pastebin with every single valid ARGB hex code, I then wrote the following:
WebClient Checker = new WebClient();
string List = Checker.Downloadstring("https://pastebin.com/raw/link");//link would be the pastebin
string Input = this.TextBox.Text;
if (List.Contains(Input))
{
//submit write file code here
}
else
{
System.Windows.Messagebox.Show("The Input Was Not Valid! Please Input A Valid ARGB Code!", "Error!");
}
This method ended up working for me. It isn't recommended but does the job right.

Convert string into a valid JSON in c#

In the code snippet below, the JSON string in the commented out jsonString variable is valid while the uncommented out one causes JObject.Parse to throw a JsonReaderException with the message:
After parsing a value an unexpected character was encountered: e. Path 'Key', line 1, position 15.
var jsonString = "{\"Key\":\"Value \"extra\" \"}";
//var jsonString = "{\"Key\":\"Value \\\"extra\\\" \"}";
JObject.Parse(jsonString);
Are there any methods available in Newtonsoft.Json or elsewhere that can transform a JSON string to make it valid?
No, because NewtonSoft cannot guess what you want. E.g. is extra a new key and did you just ommit a comma or is it part of the previous value, or is it just something that can be ignored. It would be better to have the thing you are consuming the json from construct valid json.
Using Regex might help you to resolve the existing JSON you have. If you can control how subsequent JSON is generated, you really should fix it at that point.
This solution counts the value as existing from the first " after a "key":, through to the last " before a , or a }, and then it reserializes the value to ensure that it is correctly escaped. If it finds ",, it expects it to be followed by another key ("key":). This is in an attempt to avoid red herrings (i.e. {"key": "test "," value"}) which might otherwise confuse it.
private static string FixJson(string json)
{
var regex = new Regex("\"(?<key>.*?)\"\\W?:\\W?\"(?<value>.*?)\"(?=,\".*?\"\\W?:|}$)");
return regex.Replace(json, new MatchEvaluator(m => {
var key = m.Groups["key"].Value;
var val = m.Groups["value"].Value;
return string.Format("\"{0}\":{1}", key, JsonConvert.SerializeObject(val));
}));
}
Disclaimer: It's a regular expression, it's not foolproof, and if your JSON is more broken than you have indicated, it will probably spit out broken JSON, or incorrect values, so use it at your own risk.
Try it online

C# Ignore error/warning on Substring

I use Substring to decode a generated code for activating
but when a user enter wrong code like 1 or 123
c# stop and say "Index and length must refer to a location within the string." or ..
how to ignore it without check length ...
in php we can ignore warnings and error by using "#"
#myfunc(12);
but how in C# ?
The short answer is, you can't.
The correct answer is you shouldn't, and to check that the input is valid.
The horrible answer would look something like this:
public void SwallowExceptions(Action action)
{
try
{
action();
}
catch
{
}
}
public string DoSomething()
{
string data = "TerribleIdea";
string result = null;
SwallowExceptions(() => result = data.Substring(0, 10000));
return result;
}

C# - can I parse back text that have already formatted to currency?

this is function to format text that contains numbers only into $ currency
private String GLOBALIZE_TEXT(String originalText)
{
decimal parsed;
CultureInfo myCultureInfo;
string formattedText = "";
//use try catch to prevent larger inputs
try
{
parsed = decimal.Parse(originalText, CultureInfo.InvariantCulture);
myCultureInfo = new CultureInfo("$");
formattedText = string.Format(myCultureInfo, "{0:c}", parsed);
}
catch (Exception ignorethis)
{
}
return formattedText;
}
now in usage:
String myString = "3821";
myString = GLOBALIZE_TEXT(myString);
//now my String becomes "$3,821.00"
question is, can I parse back that "$3,821.00" to "3821" again?
I need to parse it back so I can use it as an integer where "3821" can be converted by Convert.ToInt32("3821").
or maybe that parsed String can also be converted directly to string?
Please let me know your opinion.
You can try:
double.Parse(myString, NumberStyles.Currency);
More information on the NumberStyles enum can be found on MSDN here and more information on this specific double.Parse method can be found on MSDN here.
Maybe it's best to ask why you need to do this? You should always try and store a value in it's native format. If you need to do it from a captured or imported string then I would go the route of using a regular expression to remove it.
Regular expression to remove any currency symbol from a string?

Categories