On PREM Dynamics CRM 2016 JavaScript equivalent of my C# QueryExpression - javascript

I am trying to get the FetchXML query for a specific query expression fro Dynamics CRM. I have manged to do it using the XRM SDK in a C# project as follows.
string connectionStr = #"Server=https://mycompany.com/XRMServices/2011/Organization.svc; Username=theUserName; Password=pwd";
Microsoft.Xrm.Client.CrmConnection conn = Microsoft.Xrm.Client.CrmConnection.Parse(connectionStr);
var service = new Microsoft.Xrm.Client.CrmOrganizationServiceContext(conn);
var query = new QueryExpression();
QueryExpressionToFetchXmlRequest req = new QueryExpressionToFetchXmlRequest();
query.EntityName = "my_entity";
query.ColumnSet = new ColumnSet("_accountnumber", "_id");
FilterExpression filter = new FilterExpression();
filter.Conditions.Add(new ConditionExpression("_Oactivedate", ConditionOperator.NotNull));
filter.Conditions.Add(new ConditionExpression("_Oinactivedate", ConditionOperator.Null));
filter.Conditions.Add(new ConditionExpression("_state", ConditionOperator.Equal, 0));
FilterExpression filter1 = new FilterExpression(LogicalOperator.Or);
var filter2 = new FilterExpression(LogicalOperator.And);
filter2.Conditions.Add(new ConditionExpression("_lastname", ConditionOperator.Equal, lastName));
filter2.Conditions.Add(new ConditionExpression("_accountnumber", ConditionOperator.Equal, accountId));
var filter3 = new FilterExpression(LogicalOperator.And);
filter3.Conditions.Add(new ConditionExpression("_accountactivedate", ConditionOperator.NotNull));
filter3.Conditions.Add(new ConditionExpression("_accountinactivedate", ConditionOperator.Null));
filter1.AddFilter(filter2);
filter1.AddFilter(filter3);
filter.AddFilter(filter1);
query.Criteria = filter;
req.Query = query;
QueryExpressionToFetchXmlResponse resp = (QueryExpressionToFetchXmlResponse)service.Execute(req);
//fetchxml string
string myfetch = resp.FetchXml;
My requirement doesn't allow for a .Net DLL, therefore I would like to do this in JS. I have tried to look at the JS SDK and it is not as friendly as the C# one (maybe it's just me :). I would really appreciate anyone who can attempt to write a JS equivalent of my code above, or guide to a good material that can help me figure it out myself. My main interest is the generation of the FetchXml query from a dynamic strongly typed QueryExpression object. Thanks!

You should be able to build your query in Advanced find & Download the fetchxml from there to use in JavaScript. Read more
You can use XrmToolBox - FetchXml Builder as well for building queries (this will give SQL, QueryExpression equivalent too), then generate language compatible output using this online formatter tool
Code sample to use fetchxml in JavaScript can be find in this blog. For Example:
var encodedFetchXml = encodeURI(fetchContact);
var reqURL = clientURL + “/api/data/v8.2/contacts?fetchXml=” + encodedFetchXml;
var req = new XMLHttpRequest();
req.open(“GET”, reqURL, false);
QueryExpression, FetchXml, LINQ are all choices to write the same query. As you know - QueryExpression cannot be used in JavaScript, but fetchxml can be used in both C# & JS.

In addition to #Arun's excellent answer, another possibility would be to keep your logic in C# and register it in the system as a custom Action, which you then call from JavaScript.

Related

Can not encrypt a signature using Topaz SigWeb API

I am trying to integrate SigWeb API into my application. I want to use the digital signature in all modern browsers. Now it works only in IE, using ActiveX object. The problem is that I can not use the encryption key.
Let me explain:
Old version js code looks like:
SigPlus1.AutoKeyStart();
SigPlus1.AutoKeyData = "Some Key Data";
SigPlus1.AutoKeyFinish();
SigPlus1.EncryptionMode = 2;
SigPlus1.SigCompressionMode = 1;
var strSignature = SigPlus1.SigString;
New version (using SigWebTablet.js):
AutoKeyStart();
SetAutoKeyData("Some Key Data");
AutoKeyFinish();
SetEncryptionMode(2);
SetSigCompressionMode(1);
var strSignature = GetSigString();
The value of strSignature is passed to the server and converted to .jpg file. On the server side (java) I am using following code:
ClassLoader firma = (com.topaz.sigplus.SigPlus.class).getClassLoader();
sigObj = (SigPlus)Beans.instantiate(firma, "com.topaz.sigplus.SigPlus");
sigObj.autoKeyStart();
sigObj.setAutoKeyData("Some Key Data"); // the same data in front-end
sigObj.autoKeyFinish();
sigObj.setEncryptionMode (2);
sigObj.setSigCompressionMode(1);
sigObj.setSigString(strSignature);
The problem in setSigString method - it doesn't set the new value (with the old code SigPlus1.SigString works), but if I disable setAutoKeyData - it works fine.
The tablet model: T-LBK766SE-BHSB-R
I have found a solution which works for me. Before signature capture it needs to reset the encryption mode, i.e. to call SetEncryptionMode(0)
UPD (05/03/2017). Guys from dev support recommended me to use AutoKeyAddData function instead AutoKeyStart and AutoKeyFinish functions. I have tested and it works for me. I think this better solution of this issue.
http://www.sigplusweb.com/sigwebtablet_autokeydemo.htm

extract data from javascript using Python

I am a new user to Python, and I have inherited a Python notebook from my predecessor that I want to improve. The purpose of it is to grab product details from a website.
How it works:
It scrapes the script from a website using beautiful soup:
source = urllib2.urlopen('http://www.testwebsite.html').read()
soup = bs4.BeautifulSoup(source)
job_postings = soup.findAll("script")
job_postings = [jp for jp in job_postings if not jp.get('type') is None
and ''.join(jp.get('type')) =="text/javascript"
and ''.join(jp.get('type')) =="text/javascript"]
it returns all the script in the webpage:
(1st part of data)
window.wf=window.wf||{};wf.appData=wf.appData||{};wf.appData.product_data_TEST123=wf.appData.product_data_TEST123||{};wf.appData.product_data_TEST123 = {"sku":"TES123","is_grid_view":false,,"default_img_display":0,"manufacturer_name":"Supplier1","product_name":"product test","part_number":"1234","list_price":1000,"is_price_hidden":false,"base_price":1000,"has_opt":true,"opt_details":[{"option_ids":[],"regular_price":2681.25],"has_free_shipping":false,,"total_qty":1,"display_set_quantity":1,"is_standard_layout":true,"page_type":"ProductPage"};Y_config.app.product_data_TEST123 = {"sku":"TEST123",........ same info here ....};
2 sd part of data:
\n wf.extend({"YUI_config":{"app":{"pageAlias":"ProductPage"}},"wf":{"appData":{"pageAlias":"ProductPage",,"mkcName":"AU: FurnitureRoom","productReviews":{"b_show_review_tags":false,"kit_subgroup_price":null,"catalog_currency":"AUD","price_model":null,"colors":"",,"available_after":{"date":"2016-07-28 18:05:16.000000","timezone":"Australia\\/Sydney"},"inventory_info":{"sku":"TEST123",,"latest_inventory_update":"2016-07-29 00:45:06","option_ids":[],"available_quantity":17,"display_quantity":17,","quantity_available_string":" more then 10 in Stock","short_lead_time_id":2,"short_lead_time_string":"Leaves warehouse in 1 to 3 business days"}}};
Then I extract the data I need:
jsonfile = re.findall(r'wf.appData.product_data_[A-Z]{4}[0-9]{4} = (\{.*});YUI_config.app.product_data_',str(job_postings))
I have this:
{"sku":"TEST123","is_grid_view":false,,"default_img_display":0,"manufacturer_name":"Supplier1","product_name":"product test","part_number":"1234","list_price":1000,"is_price_hidden":false,"base_price":1000,"has_opt":true,"opt_details":[{"option_ids":[],"regular_price":2681.25],"has_free_shipping":false,,"total_qty":1,"display_set_quantity":1,"is_standard_layout":true,"page_type":"ProductPage"}
My problem is now: I want to add the "inventory_info" list to my data
I've tried:
jsonfile = re.findall(r'inventory_info' = (\{.*}),str(job_postings))
or
Jsonfile = re.compile('inventory_info' = ({.*?});', re.DOTALL)
Neither of those work.
I'm knowledge of Python is very limited so I'm a bit lost now.
Thanks for your help.
You may have already found the answer to your question but here it goes anyways.
For getting inventory_info, you could always do a split (assuming job_postings is converted to type string), as so:
inventory_info = job_postings.split("inventory_info:")[1].split("}")[0] + "}"
job_postings += inventory_info

RSA Verification Javascript

I am trying to verify an RSA signature in Javascript but I can't seem to get it to work. I think I have to do something with my key and signatures but I am very confused.
Here is a link to this library
var publicKey = "MIIBIjBNBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoPNkJzHqbY/6mAjJwb4zUbOiOjvmg3b8fvydYdGXdv04r6vzgn/FD5NPJM7bojAxi6sZ8vV+fYVIQey6HnrLSsdU/QXhT3p22a+kB4ym8SbKsOy2fWqL950nZCPYW/DC9txHy+ceFuKMAarFWAMJRe+MaVIbDIAAi8tMNjZ204GkmqveyAeA6JppzthAuiX69H8Zb3Hbs49CHNwLnSpKz5HBTfcgWqHkar2HlEFccvWC++Kq47MIkEcKScS/oneDb/TiL5ClOas1gMxfwiVtkFI6zNxxJOJDSTlY66oHCVCfTruk2pQbtOtwJEGrOwq6B536QL/EkeEKMgiqlpZJbQIDAQAB";
var stringToVerify = "aaa";
var signature = "hXyRmdQOCiVBNgDdGtiWF/gJwIk0Hs+MZtfEU4sFMEu05xsBjR9uymOJ/8FwhKCB0p+Kc1jqtsZxQqtxC0Du2EYyvjs0j5bbU9ZugZw0+9VHqKm0UA23djmZ1MT6nXt2ZEUEsS0La9yrfEnig/swAku1fQorsxG5FK5GFRjaacNIF+O0GOr0cbzEvlaAof6T6JFMueIw/iZykivs8XohSlghdPzoNmVueY9JF1XbtHZayau17jGhFTbeNNxbDBanPo593eZdgi5aTZMYHbxHx87cfU1sE5cjSioPQLsG9cQwVaWrrZa9BnB8IhR8Rv0NdRXYNTcVhc+sVHJN/QghNQ==";
var KJUR = require("cloud/jsrsasign-4.7.0/npm/lib/jsrsasign.js");
var verifier = new KJUR.crypto.Signature({alg: "SHA1withRSA", prov: "cryptojs/jsrsa"});
verifier.init(publicKey);
verifier.updateString(stringToVerify);
console.log(verifier.verify(signature));
Thanks in advance
You need to base 64 decode both the public key and the signature. They key and signature should then be re-encoded as hexadecimals. Then you hopefully should be able to use this method to generate a public RSAKey object.
I'm saying hopefully, as the the API description is just horrible. Personally I would not recommend to use such an API.

Mirth Connect and HL7 v3 message validation

I'm using Mirth Connect (stable version) to create interfaces for HL7v3. I've created an interface to recieve a PRPA_IN201305UV02 message.
At this point I want to do some sort of validation of the incoming XML message. After some search I discovered that HL7 has schemas files (xsd) to verify the correctness of the messages.
So, I'm trying to implement the validation against a xsd file. Searching the mirth forum one of the administrators posted a link to a java library for xml validation.
In my channel source transformer I wrote the javascript based on that link.
// parse an XML document into a DOM tree
var parser = Packages.javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder();
var document = parser.parse(msg);
The last line of code is getting me an error when I recieve a message
Wrapped java.net.MalformedURLException: no protocol
I tried also with
var document = parser.parse(messageObject.getRawData());
But I get the same error.
What is missing here?
Is this the best way to do a XML validation on Mirth Connect?
Thank you
I have found this answer
And I transformed that to Javascript in Mirth
var schemaFile = new Packages.java.io.File("C:\\schema.xsd");
var url = new Packages.java.net.URL("file:C:\\input.xml");
var xmlFile = new Packages.javax.xml.transform.stream.StreamSource(url);
var schemaFactory = Packages.javax.xml.validation.SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
var schema = schemaFactory.newSchema(schemaFile);
var validator = schema.newValidator();
try {
validator.validate(xmlFile);
logger.info('valid');
} catch (err) {
logger.error(err.toString());
}
You need to download JAXP (Java API for XML Processing) from here
I hope it helps others

SHA-1 in Amazon Api Authorization in Javascript

I've been trying to get Authorization for Amazon's s3 rest api going. It's pretty damn complicated.
Because I'm trying to make a simple GET request from an admin page on my website, I'm just trying to do this through Javascript. Here are the instructions for constructing the Signature for the Authorization header:
Signature = Base64( HMAC-SHA1( YourSecretAccessKeyID, UTF-8-Encoding-Of( StringToSign ) ))
To keep us sane, they give us a few examples, with the following givens:
var AWSSecretAccessKey = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY,
StringToSign = 'GET\n\n\nTue, 27 Mar 2007 19:36:42 +0000\n/johnsmith/photos/puppy.jpg;'
The output for this in their docs is bWq2s1WEIj+Ydj0vQ697zp+IXMU=. Based on the following I am getting ZGVjNzNmNTE0MGU4OWQxYTg3NTg0M2MxZDM5NjIyZDI0MGQxZGY0ZQ==:
function encode_utf8(s) {
return unescape(encodeURIComponent(s));
}
I used code.google.com's CryptoJS.HmacSHA1 function for the SHA1 hashing. My final Signature function looks like this:
var signature = btoa( CryptoJS.HmacSHA1( aws_secret, encode_utf8( StringToSign) ) );
What is going wrong here???
I actually found the answer from an SO question with reference to google's older (2.0) CrytpoJs library. You need:
2.0.0-crypto-sha1.js
2.0.0-hmac-min.js
Then you create your signature as so:
Signature = btoa( Crypto.HMAC(Crypto.SHA1, encode_utf8(StringToSign), aws_secret, { asString: true }) )
I couldn't find a way to to get Strings instead of Bits in the new version.

Categories

Resources