Trigger Examples

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.

CopyAttachments

Using the triggers script method copyattachment, you can copy the attachment from the ticket description from one ticket to another. For example, this function is useful when you create a new ticket from the original ticket via triggers.

api.CopyAttachments(sourceRecord, destionationRecord);

 

 

Controlling users in local active directory via triggers

In ticket triggers it is possible to use set of api methods which can be used to manipulate with user data into local Active Directory via LDAP connection.

Following methods are available:

-InsertUserIntoAD

-ChangeUserIntoAD

-MoveUserIntoAD

-DisableUserIntoAD

-ChangeUserMembershipsIntoAD

 

Insert user into Active Directory from ticket

With the help of the trigger method InsertUserIntoAD it is possible to add a user from the ticket to the local Active Directory.

api.InsertUserIntoAD(properties, userBaseDN, ldapServerConnectionName, groupsDnMemerOf);

Properties – contains ActiveDirectory user attributes with values.

UserBaseDN – is base DN where will be added a new user.

ldapServerConnectionName – is LDAP Connection name from NSP on which server you will connect.

GroupsDnMemerOf – is list of full DN group path, on every each group user will be member, if you have many groups you need to divide with this semicolon (;).

Example:

api.InsertUserIntoAD({"userPrincipalName":"dzenan102test@nilex.hbg.local", "samAccountName":"dzenan102test", "displayName":"Dzenan Strujic Test 102", "givenName":"Dzenan","sn":"Strujic Test 102","initials":"Dz.S","telephoneNumber":"0725019999","mail":"dzenan101@nilex.se","password":"NilexTest"}, "OU=Bolaget_AB,DC=Nilex,DC=hbg,DC=local", "NilexADConnection", "CN=testtest,OU=Bolaget_AB,DC=Nilex,DC=hbg,DC=local;CN=MinGrupp,OU=Bolaget_AB,DC=Nilex,DC=hbg,DC=local");

If in the list of properties some attributes do not exist, those will be added by default:

displayName: NSP Dynamic user

password: 123456

givenName: NSP

sn: Dynamic User

objectClass: user

DocToHelp: Admin – TriggerScripts

Change User Into AD

Calling this method via trigger you can change user into ActiveDirectory.

Trigger script code example:

With separator ; you can insert more then 1 group into removefromgroups and addingroups. User will be removed from all groups from list and add in groups as will from another list.

var removefromgroups = "CN=Agent,OU=Sec,OU=Groups,OU=Nilex,DC=ad,DC=nilex,DC=se";

var addingroups = "CN=Agent2,OU=Sec,OU=Groups,OU=Nilex,DC=ad,DC=nilex,DC=se";

List of attributes which values you want to change in AD:

var data = {};

data["objectClass"]="user";

data["displayName"]=record.u_displayName;

Method ChangeUserIntoAD needs following arguments: data, identtityField is value for atribute which will find account, identityValue is value for identity field, LDAP server connection name from NSP settings, list of groups to remove membership, list of groups to add membership.

api.ChangeUserIntoAD(data, "mail", record.u_mail, "NilexLDAP", removefromgroups, addingroups);

 

Set Temporary Password on AD account

Calling this method via trigger you can change user password into ActiveDirectory. User password can set as temporary or permanent. In case of temporary use, after first login, Windows will ask to change password.

api.SetUserPasswordIntoAD('mail', '4dzenantestnsp@nilex.se', 'Nilex', {"password":"Test123"}, true);

Method SetUserPasswordIntoAD needs following arguments: identtityField is value for attribute which will find account, identityValue is value for identity field, LDAP server connection name from NSP settings, new password value and flag is temporary or permanent.

Move User Into specific OU in AD

Calling this method, you can move one user from one OU to another OU.

List of arguments for method MoveUserIntoAD is: identityFiled, identityValue, connectionName, newOuDestination.

 

Example:

api.MoveUserIntoAD("mail", record.u_mail, "NilexLDAP", "OU=Temp,OU=Users,OU=Nilex,DC=ad,DC=nilex,DC=se");

     

Disable User Into AD

With this method you have possibility to set on disable account into AD, optional move into another OU as well as remove all group memberships.

Attributes which need to send on this method are: identityField, identityValue, connectionName, newOu, removedAllGroups

Example:

api.DisableUserIntoAD("mail", record.u_mail, "NilexLDAP", "OU=Temp,OU=Users,OU=Nilex,DC=ad,DC=nilex,DC=se", 1)

 

Change User Memberships Into AD

With this method you will be able to manipulate with group memberships into active directory for user. This method needs following parameters: idenntityFiled, identityValue, connectionName, removeFromGroups, addIntoGroups.

Example:

var removefromgroups = "CN=Agent,OU=Sec,OU=Groups,OU=Nilex,DC=ad,DC=nilex,DC=se";

var addingroups = "CN=Agent2,OU=Sec,OU=Groups,OU=Nilex,DC=ad,DC=nilex,DC=se";

api.ChangeUserMembershipsIntoAD("mail", record.u_mail, "NilexLDAP", removefromgroups, addingroups);

 

Business hours calculations in Triggers:

These methods are time calculations using business hours currently in effect on a ticket. By default, these time calculations will exclude all time periods where the ticket has been put on hold, and/or marked as closed.

 

// calculate deadline 2 hours after created date, within business hours:

var aDeadline = api.CalculateDate(record, record.CreatedDate, 120);

 

// calculate time passed between ticket’s registered & closed dates:

record.u_Duration = api.CalculateDuration(record, record.CreatedDate, record.CloseDateTime);

 

// check whether ticket registered inside/outside business hours, assign to field

record.u_CreatedInBusinessHours = api.IsInsideBusinessHours(record, record.CreatedDate);

 

// check whether time right now is within business hours

var openRightNow = api.IsInsideBusinessHours(record, DateTime.UtcNow);

 

 

Execute PowerShell Script

If you run powershell script in synchronous mode, you can get response from power shell script. Also if you run in async mode power shell will just trigger to execute and not wait response from power shell script.

Here is example how can use inside in trigger via api method.

var response = api.ExecutePowerShellScript(record, '{"TypeScript":"SyncPowerShell", "SourceScriptFile":"myscript.ps1", "Parameters": {"servername": "AA", "envname": "V"}, "Arguments": ["A", 1, "b"] }')

inside in object response you will have object Status and Response.

response['Status'] will contains flag true/false if is power shell succesuffuly run or not

response['Response']['Data'] will contains return data from power shell script

response['Response']['Message'] will contains return status massage for error or success message.

OR in Async mode, just fire power shell script

api.ExecutePowerShellScript(record, '{"TypeScript":"AsyncPowerShell", "SourceScriptFile":"myscript.ps1", "Parameters": {"servername": "AA", "envname": "V"}, "Arguments": ["A", 1, "b"]  }')

 

Clon Ticket Comments

By using the ClonComments api method, you can copy all comments from one ticket to another ticket, it is also possible to include the flag whether you want to copy the attachment from the comment to the target ticket.

api.CloneComments(sourceRecord, targetRecord, includeAttachments)

By using the CloneAttachments api method it is possible to copy attachments from one ticket to another ticket.

api.CloneAttachments(sorceRecord, targetRecord)

 

Translation helper methods

The GetPropertyDisplayName api method allows you to get the translated label for a specific property within an entity.

api.GetPropertyDisplayName(sysEntityName, propName, languageId)

The GetDisplayName api method allows you to get the translated text value for a given display name id value.

api.GetDisplayName(displayNameId, languageId)

The GetRecordDisplayName api method allows you to get the translated text value for a specific recordId within an entity.

api.GetRecordDisplayName(sysEntityName, recordId, languageId)

 

Insert Jira issue

The InsertJiraTicket api method allows you to add a new issue within the Jira system from an NSP ticket. To successfully execute this method, you need to have the integration settings for Jira set.

api.InsertJiraTicket(record)