The following code is best practice when creating any "entity" in Thingworx service script. When a new entity is created (like a Thing) it will be loaded into the JVM memory immediately, but is not committed to disk until a transaction (service) successfully completes. For this reason ALL code in a service must be in a try/catch block to handle exceptions. In order to rollback the create call the catch must call a delete for any entity created. In line comments give further detail.
try {
var params = {
name: "NewThingName",
description: "This Is A New Thing",
thingTemplateName: "GenericThing"
};
Resources["EntityServices"].CreateThing(params);
// Always enable and restart a new thing to make it active on the Platform
Things["NewThingName"].Enable();
Things["NewThingName"].Restart();
//Now Create an Organization for the new Thing
var params = {
topOUName: "NewOrgName",
name: "NewOrgName",
description: "New Orgianization for new Thing",
topOUDescription: "New Org Main"
};
Resources["EntityServices"].CreateOrganization(params);
// Any code that could potentially cause an exception should
// also be included in the try-catch block.
}
catch (err) {
// If an exception is caught, we need to attempt to delete everything
// that was created to roll back the entire transaction.
// If we do not do this a "ghost" entity will remain in memory
// We must do this in reverse order of creation so there are no dependency conflicts
// We also do not know where it failed so we must attempt to remove all of them,
// but also handle exceptions in case they were not created
try {
var params = {name: "NewOrgName"};
Resources["EntityServices"].DeleteOrganization(params);
}
catch(ex2) {//Org was not created
}
try {
var params = {name: "NewThingName"};
Resources["EntityServices"].DeleteThing(params);
}
catch(ex2) {//Thing was not created
}
}
One question,
why do you creating an Organization for a thing? What is the purpose of it?
Tomas
Tomas, it is mostly an example but in some cases where there is a hierarchy to the structure of a model each customer/company/location may have it's own permissions and visibility. In this case if these are modeled as Things it would make sense to have their own organization for setting visibility,
Took me a while to find it,
so if you don´t mind I am going to make a note:
to create properties use:
AddPropertyDefinition
support page here
This code is not current.
Things["NewThingName"].Enable();
Things["NewThingName"].Restart();
Should be
Things["NewThingName"].EnableThing();
Things["NewThingName"].RestartThing();