XSD to JavaScript class conversion - javascript

With XSD.exe I can easily derive a C# or VB.NET class from a XSD file. Is there a tool available to convert XSD to JavaScript?

Try xsd /language:JS (see here).
Try Jsonix.
Disclaimer: I am the author of Jsonix, an open-source library for XML<->JS conversion.
With Jsonix you can compile your schema into JavaScript mappings and then marshall/unmarshall XML in your JavaScript code. Here's an example:
// First we construct a Jsonix context - a factory for unmarshaller (parser)
// and marshaller (serializer)
var context = new Jsonix.Context([ PO ]);
// Then we create an unmarshaller
var unmarshaller = context.createUnmarshaller();
// Unmarshal an object from the XML retrieved from the URL
unmarshaller.unmarshalURL('/org/hisrc/jsonix/samples/po/test/po-0.xml',
// This callback function will be provided with the result
// of the unmarshalling
function(result) {
// We just check that we get the values we expect
assertEquals('Alice Smith', result.value.shipTo.name);
assertEquals('Baby Monitor', result.value.item[1].productName);
});

Related

Convert XML to plain old JavaScript object?

Given this sample XML:
<patient>
<name>
<given>Bob</given>
<family>Dole</family>
</name>
</patient>
I would like to create an object, patient and be able to do something like alert(patient.name.given) and get a popup that says "Bob". My actual data is much more complex than this so I would also need to account for attributes and arrays.
How can this be achieved?
I'm currently using parseXML() but I'd rather not have to type alert($xml.find("patient").find("name").find("given").text)
Here's an example of how to use JSONIX to parse (unmarshal) XML into JavaScript:
Parse XML into JS
// Include or require PO.js so that PO variable is available
// For instance, in node.js:
var PO = require('./mappings/PO').PO;
// First we construct a Jsonix context - a factory for unmarshaller (parser)
// and marshaller (serializer)
var context = new Jsonix.Context([PO]);
// Then we create a unmarshaller
var unmarshaller = context.createUnmarshaller();
// Unmarshal an object from the XML retrieved from the URL
unmarshaller.unmarshalURL('po.xml',
// This callback function will be provided
// with the result of the unmarshalling
function (unmarshalled) {
// Alice Smith
console.log(unmarshalled.value.shipTo.name);
// Baby Monitor
console.log(unmarshalled.value.items.item[1].productName);
});

Better way to de/serialize an Thrift object from/to JSON using the pure Javascript library?

I have a web server returning an thrift object serialized used the JSON protocol to a client html page using the pure Javascript Thrift library (thrift.js).
The server for example:
from MyThriftFile.ttypes import ThriftClass
from thrift import TSerialization
from thrift.protocol import TJSONProtocol
thrift_obj = new ThriftClass()
result = TSerialization.serialize(
thrift_obj,
protocol_factory=TJSONProtocol.TJSONProtocolFactory())
return result
Now in the C#, Python, Java, and even the node.js Thrift libraries there is some form of this generic TSerialization or TDeserialization utlity and its more or less implemented like so:
def deserialize(base,
buf,
protocol_factory=TBinaryProtocol.TBinaryProtocolFactory()):
transport = TTransport.TMemoryBuffer(buf)
protocol = protocol_factory.getProtocol(transport)
base.read(protocol)
return base
So it gets it data, loads it up into a throw away transport (because we are not going to send this information anywhere), creates a new protocol object for encoding this data, and finally the actual thrift object reads this data to populate itself.
The pure javacript library however seems to lack this functionality. I understand why the client library only support the JSON protocol (web pages don't deal in raw binary data) but why not method for de/serialization from/to JSON?
I made my own method for doing the job but it seems hacky. Anyone have a better trick?
$(document).ready(function() {
$.get("www.mysite.com/thrift_object_i_want/", function(data, status) {
var transport = new Thrift.Transport();
var protocol = new Thrift.Protocol(transport);
// Sets the data we are going to read from.
transport.setRecvBuffer(data);
// This is basically equal to
// rawd = data
rawd = transport.readAll();
// The following is lifited from
// readMessageBegin().
// These params I am setting are private memeber
// vars that protocol needs set in order to read
// data set in setRevBuff()
obj = $.parseJSON(rawd);
protocol.rpos = []
protocol.rstack = []
protocol.rstack.push(obj)
// Now that the protocl has been hacked to function
// populate our object from it
tc = new ThriftClass();
tc.read(protocol);
// u is now a js object equal to the python object
});
});
I haven't tried your code but I assume it is working.
It seems correct and is essentially what the TSerializer et al classes do in those other languages. Granted, it could be wrapped in a more friendly way for the vanilla JS library.
The only thing that I might recommend to make it less "hacky" would be to just create a Thrift service method that returns the object(s) you need... then the serialization/deserialization logic will be automatically wrapped up nicely for you in the generated service client.

JSON in Google Apps Script

I am trying to validate a webhook with Podio (https://developers.podio.com/doc/hooks/validate-hook-verificated-215241) using google apps script.
Currently I have the following script successfully writing data to a document (after the Podio Post is activated):
function doPost(l) {
var doc = DocumentApp.openById('1to3-JzhE27-LK0Zw7hEsdYgiSd7xQq7jjp13m6YwRh0');
var jstring = Utilities.jsonStringify(l);
doc.appendParagraph(jstring);
}
With the data appearing as follows:
{"queryString":null,"parameter":{"hook_id":"38035","code":"a92e06a2","type":"hook.verify"},"contextPath":"","parameters":{"hook_id":["38035"],"code":["a92e06a2"],"type":["hook.verify"]},"contentLength":44}
For some reason, google apps script won't let me take this data and access the properties like this:
jstring.parameter.code;
If I copy the (seemingly) JSON string into a separate script under a new variable, I can then access the data within the JSON.
What am I doing wrong here?
It looks like you have a JavaScript object that you convert to a JSON string, jstring. It is just a string. If you want to access the properties represented in the string, use the original object, l. Ie, l.parameter.code
function doPost(l) {
var doc = DocumentApp.openById('1to3-JzhE27-LK0Zw7hEsdYgiSd7xQq7jjp13m6YwRh0');
var jstring = Utilities.jsonStringify(l);
doc.appendParagraph(jstring);
dosomething(l.parameter.code);
}

Convert PHP hash_hmac(sha512) to NodeJS

I am porting a php script to node, and I don't know much about encryption.
The php script uses this function:
hash_hmac('sha512', text, key);
So, I need to implement a function in Node js for returning a keyed hash using the hmac method (SHA512).
From what I can see, node has this functionality built in via the crypto module (http://nodejs.org/docs/latest/api/crypto.html#crypto_crypto) -- But I unclear how to reproduce this function.
Any help would be appreciated.
Thanks,
Yes, use the crypto library.
var hash = crypto.createHmac('sha512', key);
hash.update(text);
var hashed_data = hash.digest();
More details (e.g. arguments to digest to control the output encoding from hash.digest) are at the link you provided.
As Nick points out, you will need to do this entire process each time you want to encrypt a new string (i.e. create a new hash object via crypto.createHmac.)

How to default construct JavaScript object from JSON Schema?

I've started using Newtonsoft.Json.Schema.JsonSchemaGenerator along with various property attributes over in my C# code to help keep my client script DRY. What I'd like to do is create a default initialized object client-side based on the schema from the server. This would be useful for, say, when the user clicks 'New Foo' to add a new entry into a table.
Obviously I can just code it up to iterate the .Properties and build up the new object, which is what I'm doing at the moment. However I'd prefer to avoid reinventing any wheels.
Are there any JS libraries for working with JSON schema that will do this, among other nifty things I've yet to realize I need?
1/29/2013 UPDATE
Some people have attempted to answer my question and have been off base, and as a result have received some negative feedback from the SO community. So let me attempt to clarify things. Here is the challenge:
In JS client script, you have an object that represents the JSON Schema of another object. Let's say, this came from the server via JSON.NET and is the representation of a C# class.
Now, in the JS client script, create one of these objects based upon the JSON Schema. Each field/property in the object must be default initialized according to the schema, including all contained objects!
BONUS: Bind this new object to the UI using MVVM (eg Knockout). Change some of the fields in response to user input.
Send this new object to the server. The server-side code will add it to a collection, database table, whatever. (Yes, the object will be sent as JSON using Ajax -- we can assume that)
No duplication! The only place where the class is defined is in the server-side code (C# in my example). This includes all metadata such as default values, description text, valid ranges, etc.
Yes there is (I tried it with NodeJS):
JSON Schema defaults
Link updated.
i think...you have to use two way binding with your HTML code...so, once your client side change you will get on your costume js file.
check here for knockout js.
Knock Out JS Link
and on C# code use : $("#urlhidden").val() OR Document.GetElemenyByID("#urlhidden").val().
here you will get array/list or textbox value
Use json with Ko
create new viewmodel for knockout js which you will get the idea about on above link.
and create a json call
like:
self.LoadMAS_Client = function () {
try {
var params = { "clientID": ClientId };
$.ajax({
type: "POST",
url: "http://" + ServerString + "/Services/LogisticsAppSuite-Services-Web-Services-MasClientService.svc/Json/GetAllLevelSubClients",
contentType: 'application/json',
data: JSON.stringify(params),
dataType: 'json',
async: false,
cache: false,
success: function (response) {
// in response u will get the data.and use as per your requirement.
eg. self.SelectedClient(response.your value);
},
error: function (ErrorResponse) {
}
});
}
catch (error) {
}
};
================================New Update ==========================================
i think..one way you can do...get data on xml format at C# code and covert into json string...check below code // To convert an XML node contained in string xml into a JSON string
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);
// To convert JSON text contained in string json into an XML node
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);

Categories