Set a date to current time
record.u_CustomDate = DateTime.UtcNow;
Set a field value from another field
record.u_Field1 = record.u_Field2;
Convert a number of minutes-value into text with special formatting #1
var duration = TimeSpan.FromMinutes(record.u_TimeMinutes || 0);
// Will set the field u_CustomTime to "0.1:17 (d.hh:mm)"
record.u_CustomTime = duration.ToString("d\\.hh\\:mm") + ' (d.hh:mm)';
Convert a number of minutes-value into text with special formatting #2
var duration = TimeSpan.FromMinutes(record.u_TimeMinutes || 0);
// This will set the field u_Customtime to "0 days 1 hours 17 min"
record.u_CustomTime = String.Format('{0:%d} days {0:%h} hours {0:%m} min', duration);
Load a related entity from database and check its data:
// Set IsMajor automatically to true if requester is marked VIP
if (record.BaseEndUserId != null) {
var endUser = db.Load("Person", record.BaseEndUserId);
if (endUser != null && endUser.IsVIP || false) {
record.IsMajor = true;
}
}
Load an entity and modify it:
In this example, there is a custom field called u_ChangeId which contains a reference to another entity (a Change-record).
// First check so reference field is not empty
if (record.u_ChangeId != null) {
// Load the Change-record:
var changeTicket = db.Load("Change", record.u_ChangeId);
// Copy the priority to the change-record:
changeTicket.PriorityId = record.PriorityId;
// Save the Change-ticket:
changeTicket.Save();
}
Any entity that is loaded from script and then modified need to be explicitly saved by calling “variableName.Save()”. Note that this should not be done on the record-variable, this is already taken care of by NSP.
If subject is empty, copy the first 150 characters in description into subject
// First, strip html because subject/baseheader do not support html-formatting:
var subject = api.HtmlToPlainText(record.BaseDescription);
// Take the first 150 characters:
if (subject.Length > 150)
subject = subject.Substring(0, 150);
// Set string in baseheader
record.BaseHeader = subject;
Automatically reopen ticket when end-user post comment (Event trigger)
Note that this script should work in conjunction that there is a reopen-status with strongname 'ReOpen' and a Trigger condition-rule “End-user comment count => Changed”.
// There are two situations where we do not want to reopen ticket:
// If current user posting the comment is agent (agent can reopen manually)
// If ticket closed less than a minute ago (it might mean end-user just closed ticket and posted a final comment)
if (CurrentUser.Id != record.BaseAgentId && (NowUtc - (record.CloseDateTime || NowUtc)).TotalMinutes > 1)
{
// Find reopen-status to set to ticket, we look for one with strongname “ReOpen”, this depends on NSP-installation:
var reopenStatus = db.QueryFirst("from SysEntityStatus where StrongName = :sname", {sname: 'ReOpen'});
if (reopenStatus != null) {
record.BaseEntityStatusId = reopenStatus.Id;
}
}
Look for an “instruction” in ticket subject to modify end-user: ([requester: realuser@real.com])
In order to override default behaviour where sender of incoming e-mail becomes requester, this script allows to set requester via subject-line.
var startIndex = record.BaseHeader.IndexOf('[requester:');
var stopIndex = record.BaseHeader.IndexOf(']');
if (startIndex == -1 || stopIndex <= startIndex)
return;
var reqAddress = record.BaseHeader.Substring(startIndex + 11, stopIndex - startIndex - 11);
if (reqAddress.IndexOf('@') == -1)
return;
// Found a valid email-adress in subject, fetch corresponding user in db:
var person = db.QueryFirst('from Person where Email = :address', { address: reqAddress.Trim() });
if (person != null)
record.BaseEndUserId = person.Id;
Apply task template to ticket via script
This will create tasks defined in template, start date will be set to current date, and task groups will be set from ticket group.
// Need to know db-id of template (inspect http-call fetching from ui)
var taskTemplateId = 13;
// Method below creates all tasks, this is all that is necessary to call.
Note: Language is the language´s culture-code, e g ‘en-US’, ‘sv-SE’, ‘da_DK’, etc. If you leave out language, task subject and description will be inserted using current OS language.
var tasks = api.ApplyTaskTemplate(record, taskTemplateId, language);
// Optional: for every task created, add a checkbox in a custom html-field called "u_TaskCheckList"
var checkList = "";
for (var i = 0; i < tasks.Count; i++) {
var t = tasks[i];
checkList = checkList + String.Format("<li>{0} - {1}<input type='checkbox'></li>", t.ReferenceNo, t.TaskBaseHeader);
}
record.u_TaskCheckList = String.Format("The following tasks should be completed:<ol>{0}</ol>", checkList);
Create a copy of a ticket, and link it to original ticket:
// create new record of same type
var relatedInstance = db.Create(record.EntityTypeName);
// copy all field values (except CreatedBy, UpdatedBy, Version)
relatedInstance.AssignFromAny(record);
relatedInstance.Save();
// Create associations between original and new ticket
var association = db.Create("SysAssociatedEntity");
association.SourceEntityInstanceId = record.Id
association.SourceEntityTypeId = record.Type.Id;
association.DestinationEntityInstanceId = relatedInstance.Id
association.DestinationEntityTypeId = relatedInstance.Type.Id;
association.Save();
var association2 = db.Create("SysAssociatedEntity");
association2.SourceEntityInstanceId = relatedInstance.Id;
association2.SourceEntityTypeId = relatedInstance.Type.Id;
association2.DestinationEntityInstanceId = record.Id;
association2.DestinationEntityTypeId = record.Type.Id;
association2.Save();
Create CI from ticket trigger and link with record ticket
api.CreateCi(record, {"Name":"MyCI", "Description":"test" });
Update CI from ticket trigger
Second parameter is ID, can be RefNo or ID.
api.UpdateCi(record, "CI0000001",{ "Description":"update description" });
or
api.UpdateCi(record, "1", { "Description":" update description " });
Get list of all linked CIs from record ticket
api. GetLinkedCis(record);
returns list of CI Ids.
Link CI into record ticket
api. LinkCiToTicket(record, "CI0000001") ;
or
api. LinkCiToTicket(record, "1");
Link CI and all CIs related to CI into record ticket
api. LinkCisToTicket (record, "CI0000001");
or
api. LinkCisToTicket (record, "1");
Copy field value from first linked CI into record Ticket field
api. CopyFromFirstLinkedCiToTicket (record, { "CiFieldName":"TicketStorageFieldName" });
Copy field value from record ticket to first or all linked CIs field
api. CopyFromTicketToLinkedCis (record, true, {"TicketStorageFieldName":"CiFieldName" });
or
api. CopyFromTicketToLinkedCis (record, true, {"TicketStorageFieldName":"CiFieldName" });
Second parameter is onlyFirst = true / false.