How do I turn a C# Array to XML - c#

I have a basic Generic List that I want turned into XML so I can return it to jquery. What I am trying to do is update my comments section in my article directory. I am returning an array of comment text, comment id, and user name. I would like to turn all of this into an array. Thanks
if (CommentFunctions.AddComment(aid, l.GetUserID(), id, comment))
{
//lets get all the comments for the article
List<CommentType> ct = CommentFunctions.GetCommentsByArticleID(id);
}

As others have pointed out, you'll need to serialize it to convert to XML.
I'd like to mention that if you're trying to return a list of objects to JQuery, that XML isn't the best or easiest format. Have you considered returning JSON?
JavaScriptSerializer serializer = new JavaScriptSerializer();
string JSONText = serializer.Serialize(List<CommentType>);
This will automatically create necessary json to describe your list of CommentTypes. JSON is much easier to parse in javascript and is much smaller to return via HTML.
Plus, you don't need to tell it your field names. It will find them for you and your JSON will be a list of classes just like your CommentType class.

You have to serialize it to XML. There are a number of ways to do this, more or less complex depending on the relative efficiency/speed you need, and the amount of control you need over the XML output.
Have a look here:
http://msdn.microsoft.com/en-us/library/ms950721.aspx

As Robert's comment mentions, you have to serialize the array to XML. Instead of retyping out the answer, however, I would recommend reading this blog post which discusses exactly how you would go about doing that.

Related

C# force integer when converting XML to JSON

I am attempting to convert XML into JSON in order to generate a HTTP POST request to an API. I am getting an error because one of the fields is meant to be an integer instead of a string. From what i have read adding "json:Integer="true"" to the node will cause it to become an int, but this doesnt seem to be working for me. Here is the xml and the resulting json. The arrays are working, but the integer is not.
<shipments json:Array="true" xmlns:json="http://james.newtonking.com/projects/json">
<shipment_tracking_number />
<response_shipment_date>2016-10-18T01:00:00.0000000-04:00</response_shipment_date>
<response_shipment_method>UPS Ground</response_shipment_method>
<expected_delivery_date>2016-10-18T01:00:00.0000000-04:00</expected_delivery_date>
<ship_from_zip_code>12345</ship_from_zip_code>
<carrier_pick_up_date>2016-10-18T01:00:00.0000000-04:00</carrier_pick_up_date>
<carrier>UPS</carrier>
<shipment_items json:Array="true">
<shipment_item_id>FF12345K</shipment_item_id>
<alt_shipment_item_id>1234567890</alt_shipment_item_id>
<merchant_sku>B00xxxx</merchant_sku>
<response_shipment_sku_quantity json:Integer="true">1</response_shipment_sku_quantity>
</shipment_items>
</shipments>
string jsonrequest = JsonConvert.SerializeXmlNode(doc,
Newtonsoft.Json.Formatting.None, true);
{"shipments":[
{
"shipment_tracking_number":null,
"response_shipment_date":"2016-10-18T01:00:00.0000000-04:00",
"response_shipment_method":"UPS Ground",
"expected_delivery_date":"2016-10-18T01:00:00.0000000-04:00",
"ship_from_zip_code":"12345",
"carrier_pick_up_date":"2016-10-18T01:00:00.0000000-04:00",
"carrier":"UPS",
"shipment_items":[
{
"shipment_item_id":"FF12345K",
"alt_shipment_item_id":"1234567890",
"merchant_sku":"B00xxxx",
"response_shipment_sku_quantity":"1"
}]
}]
}
I need "response_shipment_sku_quantity":"1" to show up as "response_shipment_sku_quantity":1, but it doesnt seem to be working. I can modify the XML or the code that performs the conversion. I dont mind which as long as this can be done.
You define the attribute wrongly. This is how it should look like.
<response_shipment_sku_quantity json:Type='Integer'>1</response_shipment_sku_quantity>
EDIT:
Newtonsoft.Json XmlNodeConverter
Look methods private void SerializeNode and string dataType = GetDataType(node); they suggest this definition.
Another option is to Deserialize the xml to class with proper types for the properties and after that Serialize it to Json.

cleaning JSON for XSS before deserializing

I am using Newtonsoft JSON deserializer. How can one clean JSON for XSS (cross site scripting)? Either cleaning the JSON string before de-serializing or writing some kind of custom converter/sanitizer? If so - I am not 100% sure about the best way to approach this.
Below is an example of JSON that has a dangerous script injected and needs "cleaning." I want a want to manage this before I de-serialize it. But we need to assume all kinds of XSS scenarios, including BASE64 encoded script etc, so the problem is more complex that a simple REGEX string replace.
{ "MyVar" : "hello<script>bad script code</script>world" }
Here is a snapshot of my deserializer ( JSON -> Object ):
public T Deserialize<T>(string json)
{
T obj;
var JSON = cleanJSON(json); //OPTION 1 sanitize here
var customConverter = new JSONSanitizer();// OPTION 2 create a custom converter
obj = JsonConvert.DeserializeObject<T>(json, customConverter);
return obj;
}
JSON is posted from a 3rd party UI interface, so it's fairly exposed, hence the server-side validation. From there, it gets serialized into all kinds of objects and is usually stored in a DB, later to be retrieved and outputted directly in HTML based UI so script injection must be mitigated.
Ok, I am going to try to keep this rather short, because this is a lot of work to write up the whole thing. But, essentially, you need to focus on the context of the data you need to sanitize. From comments on the original post, it sounds like some values in the JSON will be used as HTML that will be rendered, and this HTML comes from an un-trusted source.
The first step is to extract whichever JSON values need to be sanitized as HTML, and for each of those objects you need to run them through an HTML parser and strip away everything that is not in a whitelist. Don't forget that you will also need a whitelist for attributes.
HTML Agility Pack is a good starting place for parsing HTML in C#. How to do this part is a separate question in my opinion - and probably a duplicate of the linked question.
Your worry about base64 strings seems a little over-emphasized in my opinion. It's not like you can simply put aW5zZXJ0IGg0eCBoZXJl into an HTML document and the browser will render it. It can be abused through javascript (which your whitelist will prevent) and, to some extent, through data: urls (but this isn't THAT bad, as javascript will run in the context of the data page. Not good, but you aren't automatically gobbling up cookies with this). If you have to allow a tags, part of the process needs to be validating that the URL is http(s) (or whatever schemes you want to allow).
Ideally, you would avoid this uncomfortable situation, and instead use something like markdown - then you could simply escape the HTML string, but this is not always something we can control. You'd still have to do some URL validation though.
Interesting!! Thanks for asking. we normally use html.urlencode in terms of web forms. I have a enterprise web api running that has validations like this. We have created a custom regex to validate. Please have a look at this MSDN link.
This is the sample model created to parse the request named KeyValue (say)
public class KeyValue
{
public string Key { get; set; }
}
Step 1: Trying with a custom regex
var json = #"[{ 'MyVar' : 'hello<script>bad script code</script>world' }]";
JArray readArray = JArray.Parse(json);
IList<KeyValue> blogPost = readArray.Select(p => new KeyValue { Key = (string)p["MyVar"] }).ToList();
if (!Regex.IsMatch(blogPost.ToString(),
#"^[\p{L}\p{Zs}\p{Lu}\p{Ll}\']{1,40}$"))
Console.WriteLine("InValid");
// ^ means start looking at this position.
// \p{ ..} matches any character in the named character class specified by {..}.
// {L} performs a left-to-right match.
// {Lu} performs a match of uppercase.
// {Ll} performs a match of lowercase.
// {Zs} matches separator and space.
// 'matches apostrophe.
// {1,40} specifies the number of characters: no less than 1 and no more than 40.
// $ means stop looking at this position.
Step 2: Using HttpUtility.UrlEncode - this newtonsoft website link suggests the below implementation.
string json = #"[{ 'MyVar' : 'hello<script>bad script code</script>world' }]";
JArray readArray = JArray.Parse(json);
IList<KeyValue> blogPost = readArray.Select(p => new KeyValue {Key =HttpUtility.UrlEncode((string)p["MyVar"])}).ToList();

Generating CSS using parameterized templating

I have already looked at the post: Efficient plain text template engine, but it didn't answer my question. It's documentation is more than a little lacking, and I don't see that it does what I'm trying to do.
I'm wondering if you can iterate over a template and fill in the values with a function, whose parameters come from attributes within the template. e.g.:
"The <comparison property='fruit' value='green'> and the <comparison property='bowl' value='big'>."
becomes, after iterating over each variable and passing it to a function,
"The fruit is green and the bowl is big."
I'm trying to generate a css page based upon a JSON object containing appearance settings.
EDIT: I'm wondering if there's a way to get the straight object from JsonConvert.DeserializeObject(). The JObject has a lot of information I don't need.
(I am not sure if this is what you are looking for, but) I guess, you can combine my previous answer (showing the use of JObject.SelectToken) with regex to create your own templating engine.
string Parse(string json, string template)
{
var jObj = JObject.Parse(json);
return Regex.Replace(template, #"\{\{(.+?)\}\}",
m => jObj.SelectToken(m.Groups[1].Value).ToString());
}
string json = #"{name:""John"" , addr:{state:""CA""}}";
string template = "dummy text. Hello {{name}} at {{addr.state}} dummy text.";
string result = Parse(json, template);

How to deserialize in C# an unknown JSON string to some Object

I need to parse in C# (key ,value wise) a string that is built in a JSON format (to be exact I need to parse the binding parameter of Knockout data-bind).
I go over the html file and I extract the bindings. I want to modify each and every binding (string-wise), but It's really hard for me to parse the string, since I can't really know where each binding stops and the other starts.
for example:
data-bind="text:'ggggg',event:{mouseover:x=function(){alert(1);return 'd,y'}}"
will result in the following string:
"text:'ggggg',event:{mouseover:x=function(){alert(1);return 'd,y'}}"
I want to modify the string in the following way:
newString= "text('gggg'),event(mouseover(x=function(){alert(1);return 'd,y'}))"
I figured out that the best way to do it is to deserialize the string by JSON and then it will be easier for me to get access to each and every binding element.
I write at C#, but since I go over the html file and each data-bind is different and can contain different amount and type of attributes I would like to have a general object that I can deserialize to.
I checked out DataContractJsonSerializer but I don't see how it solves my problem.
Can you please suggest me what's best for my case?
Mary
You can do it with something like this:
var obj = ko.bindingProvider.instance.getBindings(yourDomElement,
ko.contextFor(yourDomElement));
alert(JSON.stringify(obj));
And then do whatever you want with obj.
Fiddle
But... well... don't!

Is it possible to load Json to a holder object similar to XElement?

The answer to this question shows how to load a Json string to a hard-coded class using JavaScriptSerializer. However, the class structure has to be coded, and this looks impractical if you're just interested in a few values, and not interested in parsing the whole string.
Is there something similar to XElement, where I can simply load a XML string and then use xElement.Elements("Items").Select( el => el.Elements("Title")) in order to list the title of all items, for example. I prefer if I can use pure .NET without third-party libraries. It would be nice if I can also linq it like XElement
In case the context is useful, I'm trying to parse the a list of question provided by StackExchange API (json format) to a nicely formatted string, and I only want some infos like title, link, and author.
It sounds like what you are really asking for is a Linq to JSON adapter. Why be burdened by XML if you don't need to be? JSON is an object serialization format, not an XML format, so you should think of it as "How can I use LINQ to Objects with objects from JSON?
A quick google search for "Linq json" turns up several interesting topics. Give it a spin.

Categories