Creating a Thing in Service Script
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
}
}

