public class GetData : CaptureNode
{
public override void Run()
{
Uri uri = null;
String root="";
try
{
uri = new Uri(Settings.GetStringSetting("URL"));
root = Settings.GetStringSetting("StartElement");
}
catch
{
LogHistory("Unable to parse provided URL: " + Settings.GetStringSetting("URL"));
SetNextNodeByLinkName("Failure");
return;
}
IRestResponse response = null;
try
{
var client = new RestClient(uri.Scheme + "://" + uri.Authority);
var user = Settings.GetStringSetting("User");
var password = Settings.GetStringSetting("Password");
if (!String.IsNullOrEmpty(user))
{
client.Authenticator = new RestSharp.Authenticators.HttpBasicAuthenticator(user, password);
}
var request = new RestRequest(uri.PathAndQuery, DataFormat.Json);
response = client.Get(request);
if(response.StatusCode != System.Net.HttpStatusCode.OK)
{
throw new Exception("Response received: " + response.StatusCode + ' ' + response.Content);
}
}
catch(Exception ex)
{
LogHistory("Unable to communicate with data source. " + ex.Message);
SetNextNodeByLinkName("Failure");
return;
}
try
{
dynamic json = JsonConvert.DeserializeObject(response.Content);
var rootObject = json;
if(!string.IsNullOrEmpty(root))
rootObject = json[root];
if (rootObject is JArray)
rootObject = rootObject[0];
if (rootObject == null)
{
LogHistory("No data returned, or no data for key element " + root);
SetNextNodeByLinkName("Failure");
return;
}
bool propertySet = false;
var propNames = Process.Properties.GetPropertyNames();
foreach (String prop in propNames)
{
String objVal = rootObject[prop];
if (objVal != null)
{
Process.Properties.SetSingleProperty(prop, objVal);
LogHistory(prop + " updating from external data source.");
propertySet = true;
}
}
if(!propertySet)
LogHistory("No data matched cooresponding property.");
SetNextNodeByLinkName("Success");
}
catch(Exception ex)
{
LogHistory("Error parsing response object. " + ex.Message);
SetNextNodeByLinkName("Failure");
return;
}
}
} |