InstanceService.UpdateInstance
Reference
DateTime UpdateInstance(Instance instance, DateTime? lastModified)
Use UpdateInstance to modify an existing Type instance by updating its attributes and other properties. This API performs validation, executes triggers, and ensures data consistency while returning the updated modification timestamp.
Parameters
instance: The instance contract containing updated data. Must include a valid Id for the instance to update.Id: Required - The unique identifier of the instance to update.Name: Optional - Updated instance name.Attributes: Optional - Array of attributes to update with new values.ParentAttributes: Optional - Array of parent attribute relationships to update.Geofence: Optional - Geofence data if the instance supports location-based features.
lastModified: Optional timestamp for optimistic concurrency control. If provided, ensures the instance hasn't been modified since this time.
Returns
DateTime: The updated modification timestamp of the instance after successful update.
Error Handling & Caveats
- If the instance does not exist or the user lacks permission, an AccessDeniedException is thrown.
- If the instance has been modified since
lastModifiedtimestamp, a ConcurrencyException is thrown. - If attribute validation fails (e.g., required attributes missing, invalid data types), a ValidationException is thrown.
- If business rule triggers fail, the update is blocked and error details are returned.
- If the instance is locked by another process, an InstanceLockException is thrown.
- Updates are performed atomically - if any part fails, the entire update is rolled back.
- Geofence updates trigger location-based events and validations if configured.
- Parent attribute updates may affect related instances and their relationships.
Usage
using Prorigo.Protrak.API.Contracts.Builders;
try {
var current = InstanceService.GetInstance(existingInstanceId, new[] { "Modified" });
var updatePayload = InstanceBuilder.ForUpdate(existingInstanceId, "Task")
.SetTextAttributeValue("Status", "In Progress")
.Build();
var updatedTimestamp = InstanceService.UpdateInstance(updatePayload, current.Modified);
Console.WriteLine($"Instance updated successfully at {updatedTimestamp}");
} catch (AccessDeniedException ex) {
// Handle permission errors
} catch (ConcurrencyException ex) {
// Handle concurrent modification conflicts
} catch (ValidationException ex) {
// Handle validation errors
foreach (var error in ex.ValidationErrors) {
Console.WriteLine($"Validation error: {error.Message}");
}
}
Example: Updating Date Attributes
try {
var updatePayload = InstanceBuilder.ForUpdate(contract.Id, contract.InstanceTypeName)
.SetDateAttributeValue("RequestedDate", DateTime.UtcNow)
.SetDateAttributeValue("ApprovedDate", DateTime.UtcNow)
.Build();
InstanceService.UpdateInstance(updatePayload, contract.Modified);
Console.WriteLine("Contract dates updated successfully");
} catch (Exception ex) {
Console.WriteLine($"Error updating contract dates: {ex.Message}");
}
Example: Batch Attribute Updates
try {
var instance = InstanceService.GetInstance(projectInstanceId, new[] { "Modified" });
var batchUpdate = InstanceBuilder.ForUpdate(projectInstanceId, "Project")
.SetTextAttributeValue("Status", "Active")
.SetNumericAttributeValue("Progress", 75)
.SetDateAttributeValue("LastReviewed", DateTime.UtcNow)
.SetReferenceAttributeValue("ReviewedBy", new ReferenceValue { Id = currentUserId })
.Build();
var updatedTimestamp = InstanceService.UpdateInstance(batchUpdate, instance.Modified);
Console.WriteLine($"Project attributes updated successfully");
} catch (ConcurrencyException ex) {
// Instance was modified by another user - refresh and retry
Console.WriteLine("Instance was modified by another user. Please refresh and try again.");
} catch (ValidationException ex) {
// Display specific validation errors
Console.WriteLine("Validation failed:");
foreach (var error in ex.ValidationErrors) {
Console.WriteLine($"- {error.AttributeName}: {error.Message}");
}
}
Example: Copying and Updating Related Instance Attributes
using Prorigo.Protrak.API.Contracts.Extensions;
try {
var sourceInstance = InstanceService.GetInstance(sourceInstanceId, new[] { "Category", "Priority" });
var targetInstance = InstanceService.GetInstance(targetInstanceId, new[] { "Modified" });
var updateBuilder = InstanceBuilder.ForUpdate(targetInstanceId, targetInstance.InstanceTypeName);
var category = sourceInstance.GetTextAttributeValue("Category");
var priority = sourceInstance.GetTextAttributeValue("Priority");
if (!string.IsNullOrWhiteSpace(category)) {
updateBuilder.SetTextAttributeValue("DerivedCategory", category);
}
if (!string.IsNullOrWhiteSpace(priority)) {
updateBuilder.SetTextAttributeValue("InheritedPriority", priority);
}
if (!string.IsNullOrWhiteSpace(category) || !string.IsNullOrWhiteSpace(priority)) {
InstanceService.UpdateInstance(updateBuilder.Build(), targetInstance.Modified);
Console.WriteLine("Attributes copied and updated successfully");
}
} catch (Exception ex) {
Console.WriteLine($"Error copying attributes: {ex.Message}");
}
Troubleshooting
- If ConcurrencyException occurs frequently, implement retry logic with fresh lastModified timestamps.
- If ValidationException occurs, check that all required attributes are provided with valid data types and values.
- If InstanceLockException occurs, wait and retry the operation as the instance may be temporarily locked.
- For performance issues with large attribute sets, consider updating only changed attributes rather than the entire instance.
- Always use the correct AttributeType when setting attribute values (Text, Numeric, DateTime, Reference, etc.).
- When adding new attributes, ensure they exist in the instance type schema and are properly typed.
- For date/time attributes, use DateTime.UtcNow for consistency across time zones.
- If triggers are blocking updates, review business rules and ensure all required conditions are met.
- Use
instance.Modifiedfor optimistic concurrency control to prevent overwriting concurrent changes. - When copying attributes between instances, handle type conversions and name mappings appropriately.