C# - Unable to remove the back slashes in JSON - c#

I am trying to construct a string which I want to use it to update a JSON.
The code is below
public string ConstructCylicLoop(string fieldName, int LoopCount, string BadDataLabel,string ImmediateParent)
{
string start = "";
string fullbody = "";
string end = "";
string body = "";
for (int i = 0; i < LoopCount; i++)
{
LoopTestData = (new ExcelUtilities().getAPITestData(ApplicationConfiguration.LoopSheetName));
body = "";
foreach (Dictionary<string, string> loopData in LoopTestData)
{
string ParentNode = "";
string Key = "";
string Data = "";
loopData.TryGetValue("ParentNode", out ParentNode);
loopData.TryGetValue("Key", out Key);
loopData.TryGetValue("Data", out Data);
if(ImmediateParent.Equals(ParentNode)) //&& Key.Equals(fieldName)
{
body = body + '"' + Key + '"' + ":" + '"' + Data + '"'+',';
}
}
body = body.Remove(body.Length - 1);
body = "{" + body + "},";
fullbody = fullbody + body;
}
fullbody = fullbody.Remove(fullbody.Length - 1);
return start + fullbody + end;
}
The issue with this code is it always returns a text like this
"{\"my_address_type\":\"primarypropertyaddress\",\"my_address-street\":\"52 Street\",\"my_address-suburb\":\"vinvent\",\"my_address-postcode\":\"2121\"}"
When I update this string to an JSON node, the server is not able to parse it and the issue is with the back slash. Is there a way to remove the back slash. so I get something like this..
"{"my_address_type":"primarypropertyaddress","my_address-street":"52 Street","my_address-suburb":"vinvent","my_address-postcode":"2121"}"
I tried all possibilities but not able to clear/remove the backslash. Any code snippet on removing the backslashes. Thanks in advance.

Related

C# HttpWebRequest removing any encoding on an URL

I'm trying to send percent-encoded ASCII characters using HttpWebRequest, for example https://example.com/%74%65%73%74
Using POSTMAN I'm able to send a request and see in charles that it's still encoded, however, regardless of what I do, any C# library will simplify this to https://example.com/test.
Is there any workaround or async compatible library to work around this?
Thanks in advance
Example Code
string newURL = "";
string path = "test";
foreach (char character in path)
{
string charac = "";
string finished = "";
if (character != '-' || character != '/')
{
if (random.Next(1, 10) >= 5)
{
charac = "%" + Convert.ToInt32(character).ToString("X");
}
else
{
charac = character.ToString();
}
}
newURL = newURL + charac;
}
string main = "http://www.example.com";
HttpWebRequest request = HttpWebRequest.CreateHttp(main + "/en/" + newURL);

Read a table from a file with nullable columns

I have a file with some rows and I can read everything, but I will get an error if one column has a empty cell.
What should I do?
while ((line = reader.ReadLine()) != null) {
FundPriceModel model = new FundPriceModel();
if (isColumn) {
model.Columns = line.Split(spliter[0]);
isColumn = false;
} else {
string[] row = line.Split(spliter);
model.LipperID = Int32.Parse(row[0]);
model.PriceDate = DateTime.Parse(row[1]);
model.PriceCode = row[2][0];
model.PriceType = row[3][0];
model.PriceCurrency = row[4];
model.PriceValueLC = float.Parse(row[5]);
model.Estimate = row[6][0];
Console.WriteLine(model.LipperID + "\t" + model.PriceDate + "\t" + model.PriceCode + "\t" + model.PriceType + "\t" + model.PriceCurrency + "\t" + model.PriceValueLC + "\t" + model.Estimate);
}
}
Table:
The error is probably when you try to parse something. This leads me to believe that you need to use TryParse instead or Parse :)
Something like this: int x; int? val=int.TryParse(row[0],out x)?x:(int?)null;
Also, row[3][0] gets the first letter in an existing string and returning an error when the string is empty. You could encapsulate it somewhat like this:
private T safeValue<T>(string text, Func<string,T> func) {
if (string.IsNullOrEmpty(text)) return default(T);
return func(text)
}
and you would use it like this:
model.LipperID = safeValue(row[0],v=>Int32.Parse(v));
model.PriceCode = safeValue(row[2], v=>v[0]);

capture string from a string c#

I need to format some text entered by user.
For example: string str = "{{Lorem Ipsum|bold}}" is simply dummy text of the printing and typesetting industry.
I have extracted Lorem Ipsum from the string using IndexOf and displayed in Bold. But facing problem if I have two words to format in same string.
For example: string str ="{{Lorem Ipsum|bold}}" is simply dummy text of the "{{printing|blue}}" and typesetting industry.
Can someone help me out with any Regex pattern to extract {{Lorem Ipsum|bold}} and {{printing|blue}} as a array in c#.
Note: The pattern sometimes may be {{printing|blue,bold,http://www.google.com}}.
Extension Method for formatting. I have hard coded for testing, later i'll optimize accordingly.
public static string Format(this string value)
{
System.Uri uriResult = null;
bool result = false;
string path = ConfigurationManager.AppSettings["path"];
if (value.Length > 0)
{
if (value.Contains("{{") && value.Contains("|") && value.Contains("}}"))
{
int totalLength = value.Length;
string unformattedText = value.Substring(value.IndexOf("{{"), (value.IndexOf("}}") - value.IndexOf("{{")) + 2);
string flowersRemoved = unformattedText.Substring(0, unformattedText.Length - 2);
flowersRemoved = flowersRemoved.Substring(2, flowersRemoved.Length - 2);
string[] textFormats = flowersRemoved.Split('|');
string text = textFormats[0];
string[] formats = textFormats[1].Split(',');
foreach (string format in formats)
{
result = Uri.TryCreate(format.ToLower(), UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp;
if (format.ToLower() == "bold")
text = "<b>" + text + "</b>";
else if (format.ToLower() == "red")
text = "<font color = \"red\">" + text + "</font>";
else if (format.ToLower() == "blue")
text = "<font color = \"blue\">" + text + "</font>";
else if (result)
text = "" + text + "";
else if (System.IO.File.Exists(path + format))
{
string fileName = System.IO.Path.GetFileName(path + format);
text = "" + text + "";
}
}
value = value.Replace(unformattedText, text);
}
return value;
}
return value;
}
You can use next regexp with replace function
string str = "{{Lorem Ipsum|bold}}";
string path = ConfigurationManager.AppSettings["path"];
var formattedString = Regex.Replace(str, #"{{(?<symbol>[^|]+?)\|(?<formats>.+?)}}", m =>
{
var formatedPattern = m.Groups["formats"].Value.Split(',').Aggregate("{0}", (acc, f) =>
{
switch (f.ToLower())
{
case "bold": return "<b>" + acc + "</b>";
case "red": return "<font color = \"red\">" + acc + "</font>";
case "blue": return "<font color = \"blue\">" + acc + "</font>";
};
Uri uriResult;
if (Uri.TryCreate(f.ToLower(), UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp)
{
return "" + acc + "";
}
else if (System.IO.File.Exists(path + f))
{
string fileName = System.IO.Path.GetFileName(path + f);
return "" + acc + "";
}
return acc;
});
return string.Format(formatedPattern, m.Groups["symbol"].Value);
});
The pattern sometimes may be {{printing|blue,bold,http://www.google.com}}.
Try Split.
The following fiddle uses Split() not regex, because regex tends to be hard to read. The resultant key string contains the word to format, and a values string array contains the relevant settings.
string str = "{{printing|blue,bold,http://www.google.com}}";
// get your settings
int pFrom = str.IndexOf("{{") + "{{".Length;
int pTo = str.LastIndexOf("}}");
string settings = str.Substring(pFrom, pTo - pFrom);
// split
string[] parts = settings.Split('|');
string key = parts[0];
string[] values = parts[1].Split(',');
// for demo purposes only
Console.WriteLine(key);
foreach(var v in values)
{
Console.WriteLine("-" + v);
}
Output
printing
-blue
-bold
-http://www.google.com
If you tack this on the end you can have your desired HTML:
// create html
var html = string.Format(#"
<a href='{3}' target ='_blank'>
<font color='{1}'>
<b>{0}</b>
</font>
</a>", key, values[0], values[1], values[2]);
Console.WriteLine(html);
Output
<a href ='http://www.google.com' target = '_blank'>
<font color ='blue'>
<b>printing</b>
</font>
</a>
Watch it run here.

Regex catch string between strings

I created a small function to catch a string between strings.
public static string[] _StringBetween(string sString, string sStart, string sEnd)
{
if (sStart == "" && sEnd == "")
{
return null;
}
string sPattern = sStart + "(.*?)" + sEnd;
MatchCollection rgx = Regex.Matches(sString, sPattern);
if (rgx.Count < 1)
{
return null;
}
string[] matches = new string[rgx.Count];
for (int i = 0; i < matches.Length; i++)
{
matches[i] = rgx[i].ToString();
//MessageBox.Show(matches[i]);
}
return matches;
}
However if i call my function like this: _StringBetween("[18][20][3][5][500][60]", "[", "]");
It will fail. A way would be if i changed this line string sPattern = "\\" + sStart + "(.*?)" + "\\" + sEnd;
However i can not because i dont know if the character is going to be a bracket or a word.
Sorry if this is a stupid question but i couldn't find something similar searching.
A way would be if i changed this line string sPattern = "\\" + sStart + "(.*?)" + "\\" + sEnd; However i can not because i don't know if the character is going to be a bracket or a word.
You can escape all meta-characters by calling Regex.Escape:
string sPattern = Regex.Escape(sStart) + "(.*?)" + Regex.Escape(sEnd);
This would cause the content of sStart and sEnd to be interpreted literally.

IndexOutOfRangeException while adding text to String

My programs adds two arrays into a part of a string using a while loop
ex:
hnames[0] = user
hvals[0] = admin
transformed into: user=admin&
I get IndexOutOfRangeException and i don't know how to fix it.
string[] hnames = names.ToArray(typeof(string)) as string[];
string[] hvals = values.ToArray(typeof(string)) as string[];
String postData = "";
//Loops through the arrays and put data into postData var
while (i < hnames.Length)
{
i++;
int end = hnames.Length;
end--;
if (!(i == end))
{
postData = postData + hnames[i] + "=" + hvals[i] + "&"; //IndexOutOfRangeException here
}
else
{
postData = postData + hnames[i] + "=" + hvals[i];
}
}
You're incrementing i before using it, so at the end of the loop, when i = hnames.Length - 1, the i++; at the start of the loop sets i = hnames.Length, which is over the end of the array. You're also skipping i = 0, in effect.
Move i++; down to the end of the loop.
I just wanted to show you a simplified version of your logic with the foreach as suggested by others. Number of lines may be same but I think this is easy to read.
string[] hnames = names.ToArray(typeof(string)) as string[];
string[] hvals = values.ToArray(typeof(string)) as string[];
string postData = string.Empty;
bool isFirst = true;
int i = 0;
/* Assumption - Both arrays hnames and hvals are of same length.
Otherwise you'll get the same error if hvals.Length < hnames.Length even if you use the foreach
*/
foreach (string hname in hnames)
{
if (isFirst)
{
postData = hname + "=" + hvals[i] + "&"; //IndexOutOfRangeException here
isFirst = false;
}
else
{
postData += hname + "=" + hvals[i];
}
i++;
}

Categories

Resources