Calling the irDistribution service

  • Updated

Calling the irDistribution service programmatically

This approach allows you to obtain your rules programmatically, using the irDistribution service HTTP API. This is useful if you want to integrate the packaging of rules into your build / continuous
integration process.

The irDistribution service uses an HTTP interface which exposes primarily one method that you'll be
using. This method, appropriately named "package", accepts a Rule Application in the body of a
POST request and returns a JavaScript file. Authentication is handled by including an API
subscription key in a custom "subscription-key" header of the request.

Setting irDistribution Packaging Options

There are 3 different settings that control how irDistribution will package your Rule Application into
JavaScript. All of these are set via query string parameters on the call to irDistribution.
logOption
For each log option you want to enable, pass a logOption parameter on the query string. Available
options are Execution and StateChanges.
metadataOption
For each authoring metadata option you want to enable, pass a metadataOption parameter on the
query string. Available options are None, Attributes, DisplayName, DataType and DefaultValue.
developerExample
Set to true to include a small code sample in the packaged JavaScript file.

Code Sample (C#)
Below is a C# code sample that calls the service. This example uses the HttpClient to perform the
service call.

For this sample to run, you need:

  • A reference to Microsoft.AspNet.WebApi.Client via NuGe
  • A reference to System.Net.Http
  • A reference to InRule.Repository.dl
  • A reference to Newtonsoft.Json.dll
public static async Task<string> CallDistributionServiceAsync(RuleApplicationDef
ruleApplication, string serviceUri, string subscriptionKey)
{
using (var client = new HttpClient())
using (var requestContent = new MultipartFormDataContent())
{
client.BaseAddress = new Uri(serviceUri);
// Build up our request by reading in the rule application
var httpContent = new
ByteArrayContent(Encoding.UTF8.GetBytes(ruleApplication.GetXml()));
requestContent.Add(httpContent, "ruleApplication", ruleApplication.Name + ".ruleapp");
// Tell the server we are sending form data
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("multipart/
form-data"));
client.DefaultRequestHeaders.Add("subscription-key", subscriptionKey);
// Post the rule application to the irDistribution service API,
// enabling Execution and State Change logging, Display Name metadata, and the developer
example.
var distributionUrl = "package?logOption=Execution&logOption=StateChanges&subscription-
key=" + subscriptionKey;
var result = await client.PostAsync(distributionUrl
requestContent).ConfigureAwait(false);
// Get the return package from the result
dynamic returnPackage = result.Content.ReadAsAsync<JObject>().Result;
var errors = new StringBuilder();
if (returnPackage.Status.ToString() == "Fail")
{
foreach (var error in returnPackage.Errors)
{
// Handle errors
errors.AppendLine("* " + error.Description.ToString());
}
foreach (var unsupportedError in returnPackage.UnsupportedFeatures)
{
// Handle errors
errors.AppendLine("* " + unsupportedError.Feature.ToString());
}
// Still need to stop processing
return errors.ToString();
}
// Build the download url of the file
var downloadUrl = returnPackage.PackagedApplicationDownloadUrl.ToString();
// Get the contents
HttpResponseMessage resultDownload = await
client.GetAsync(downloadUrl).ConfigureAwait(false);
if (!resultDownload.IsSuccessStatusCode)
{
// Handle errors
errors.AppendLine(resultDownload.Content.ReadAsStringAsync().Result);
return errors.ToString();
}
return resultDownload.Content.ReadAsStringAsync().Result;
}
}

Note: Notice the use of ConfigureAwait(false) in this sample. This is needed for use in a WPF
application.

Note: The Service URI and credentials to the InRule for JavaScript web site are provided with your
InRule license. The irDistribution service subscription key is available after login to the web site. If
you are using irAuthor to package your Rule Application, these values are entered when you set
JavaScript options.
You may invoke this method with something like this:

// Load the Rule Application
var ruleAppDef = RuleApplicationDef.Load(@"C:\Temp\MyRuleApplication.ruleapp");

// Call the service to get the JavaScript for the Rule Application
var javascript = CallDistributionServiceAsync(ruleAppDef, "https://
api.distribution.inrule.com/", "< YOUR SUBSCRIPTION KEY >").Result

Note: The irDistribution service keeps your JavaScript code for a few days only. If you need to
download the JavaScript code after that, a 404 response indicates that your Rule Application has been removed, and you should upload and package it again.

Code Sample (JavaScript)
Below is a Node.js JavaScript code sample that calls the service. This example uses the request and
form-data modules to perform the service call.

try {
var fs = require('fs');
var path = require('path');
var request = require('request');
var ruleAppFilename = 'Test.ruleapp';
var subscriptionKey = '< YOUR SUBSCRIPTION KEY >';
// Create HTTP request and POST the form data
request.post(
{
url: 'https://api.distribution.inrule.com/package',
headers: { 'subscription-key': subscriptionKey, },
formData: {
ruleApplication: {
value: fs.createReadStream(ruleAppFilename),
options: {
filename: ruleAppFilename,
contentType: 'application/octet-stream'
}
}
}
}, (err, response, body) => {
// Validate Response
if (err) {
console.log('error sending request: ' + err.toString());
return;
}
if (response.statusCode == 200) {
console.log("Response: " + body);
var result = JSON.parse(body);
if (result.Status === 'Fail') {
console.log(result.Errors.map(error => '* ' + error.Description + '\n'));
console.log(result.UnsupportedFeatures.map(error => '* ' + error.Feature +
'\n'));
return;
}
// Response valid - Download packaged RuleApplication
var packageFilename = path.basename(ruleAppFilename,
path.extname(ruleAppFilename)) + '.js';
request(result.PackagedApplicationDownloadUrl + '?subscription-key=' +
subscriptionKey).pipe(fs.createWriteStream(packageFilename));
} else {
console.log('error sending request. response code: ' + response.statusCode);
}
});
} catch (error) {
console.log("error: " + error);
}

Note: The Service URI and credentials to the InRule for JavaScript web site are provided with your InRule license. The irDistribution service subscription key is available after login to the web site. If
you are using irAuthor to package your Rule Application, these values are entered when you set
JavaScript options.

Note: The irDistribution service keeps your JavaScript code for a few days only. If you need to
download the JavaScript code after that, a 404 response indicates that your Rule Application has
been removed, and you should upload and package it again

Was this article helpful?

0 out of 0 found this helpful

Comments

0 comments

Please sign in to leave a comment.