+ All Categories
Home > Documents > Ovsc Twp Javascript Guide

Ovsc Twp Javascript Guide

Date post: 21-Apr-2015
Category:
Upload: caglar-cankaya
View: 52 times
Download: 0 times
Share this document with a friend
114
ServiceCenter ® 6.x JavaScript Programming Guide Using JavaScript in ServiceCenter 6.x Tailoring Tools HP ® OpenView ® IT Service Management Introduction ...................................................................................................................................................... 4 Requirements .............................................................................................................................................. 4 How to use this document............................................................................................................................ 4 Introduction to JavaScript in ServiceCenter ..................................................................................................... 4 Language overview...................................................................................................................................... 4 Basic rules of JavaScript.............................................................................................................................. 5 Structure of a JavaScript application ....................................................................................................... 5 Expressions and operators ...................................................................................................................... 5 JavaScript objects and properties ............................................................................................................ 5 Built-in objects and functions ................................................................................................................... 6 Conditional statements ............................................................................................................................ 6 While and loop statements....................................................................................................................... 6 Break and continue statements ............................................................................................................... 7 Use of JavaScript in ServiceCenter ................................................................................................................. 7 Order of execution of JavaScript versus RAD language .............................................................................. 8 The ScriptLibrary ......................................................................................................................................... 9 Using the ScriptLibrary............................................................................................................................. 9 Corresponding JavaScript syntax for RAD language tasks........................................................................ 10 JavaScript global properties....................................................................................................................... 11 Query operators ..................................................................................................................................... 11 JavaScript return code properties .......................................................................................................... 11 Examples of calling JavaScript from different ServiceCenter tools ............................................................ 12 FormatControl ........................................................................................................................................ 12 Triggers.................................................................................................................................................. 13 Links ...................................................................................................................................................... 14 Programmer’s reference ................................................................................................................................ 15 JavaScript global system objects ............................................................................................................... 16 system.files ............................................................................................................................................ 16 system.forms ......................................................................................................................................... 16 system.functions .................................................................................................................................... 17 system.library......................................................................................................................................... 17 system.oldrecord ................................................................................................................................... 18 system.record ........................................................................................................................................ 18 system.sysinfo ....................................................................................................................................... 18 system.threads ...................................................................................................................................... 18 system.user ........................................................................................................................................... 19 system.users.......................................................................................................................................... 19 system.vars............................................................................................................................................ 19 JavaScript global methods ......................................................................................................................... 20 print ........................................................................................................................................................ 20 readFile .................................................................................................................................................. 20
Transcript

ServiceCenter 6.x JavaScript Programming GuideUsing JavaScript in ServiceCenter 6.x Tailoring ToolsHP OpenView IT Service Management

Introduction ......................................................................................................................................................4 Requirements ..............................................................................................................................................4 How to use this document............................................................................................................................4 Introduction to JavaScript in ServiceCenter .....................................................................................................4 Language overview......................................................................................................................................4 Basic rules of JavaScript..............................................................................................................................5 Structure of a JavaScript application .......................................................................................................5 Expressions and operators ......................................................................................................................5 JavaScript objects and properties............................................................................................................5 Built-in objects and functions ...................................................................................................................6 Conditional statements ............................................................................................................................6 While and loop statements.......................................................................................................................6 Break and continue statements ...............................................................................................................7 Use of JavaScript in ServiceCenter .................................................................................................................7 Order of execution of JavaScript versus RAD language ..............................................................................8 The ScriptLibrary .........................................................................................................................................9 Using the ScriptLibrary.............................................................................................................................9 Corresponding JavaScript syntax for RAD language tasks........................................................................10 JavaScript global properties.......................................................................................................................11 Query operators.....................................................................................................................................11 JavaScript return code properties ..........................................................................................................11 Examples of calling JavaScript from different ServiceCenter tools ............................................................12 FormatControl........................................................................................................................................12 Triggers..................................................................................................................................................13 Links ......................................................................................................................................................14 Programmers reference ................................................................................................................................15 JavaScript global system objects...............................................................................................................16 system.files ............................................................................................................................................16 system.forms .........................................................................................................................................16 system.functions ....................................................................................................................................17 system.library.........................................................................................................................................17 system.oldrecord ...................................................................................................................................18 system.record ........................................................................................................................................18 system.sysinfo .......................................................................................................................................18 system.threads ......................................................................................................................................18 system.user ...........................................................................................................................................19 system.users..........................................................................................................................................19 system.vars............................................................................................................................................19 JavaScript global methods.........................................................................................................................20 print........................................................................................................................................................20 readFile..................................................................................................................................................20

writeFile .................................................................................................................................................21 Quit ........................................................................................................................................................21 base64Encode.......................................................................................................................................22 base64Decode.......................................................................................................................................22 xmlstring ................................................................................................................................................23 doHTTPRequest ....................................................................................................................................23 doSOAPRequest ...................................................................................................................................24 makeSCWebURL ..................................................................................................................................25 help ........................................................................................................................................................26 RCtoString .............................................................................................................................................26 execute ..................................................................................................................................................27 compile ..................................................................................................................................................27 JavaScript objects......................................................................................................................................28 Attachment.............................................................................................................................................28 Header ...................................................................................................................................................28 Datum ....................................................................................................................................................29 SCDatum ...............................................................................................................................................30 SCFile ....................................................................................................................................................31 XML .......................................................................................................................................................33 XMLDate................................................................................................................................................34 JavaScript methods for the SCFile, SCDatum, and Datum objects ...........................................................36 SCFile.doAction()...................................................................................................................................36 SCFile.doDelete() ..................................................................................................................................37 SCFile.doInsert()....................................................................................................................................38 SCFile.doRemove() ...............................................................................................................................39 SCFile.doSave() ....................................................................................................................................39 SCFile.doSelect(query) .......................................................................................................................40 SCFile.doUpdate() .................................................................................................................................41 SCFile.getFirst().....................................................................................................................................42 SCFile.getLast().....................................................................................................................................43 SCFile.getNext() ....................................................................................................................................44 SCFile.getPrev() ....................................................................................................................................44 SCFile.getSize().....................................................................................................................................45 SCFile.getText().....................................................................................................................................46 SCFile.getType()....................................................................................................................................47 SCFile.getXML() ....................................................................................................................................48 SCFile.isRecord() ..................................................................................................................................49 SCFile.join() ...........................................................................................................................................50 SCFile.JSDate(dataType) ......................................................................................................................50 SCFile.length() .......................................................................................................................................51 SCFile.pop()...........................................................................................................................................53 SCFile.push(arrayItem)..........................................................................................................................53 SCFile.setType(dataType) .....................................................................................................................54 SCFile.setValue(newValue) ...................................................................................................................55 SCFile.shift() ..........................................................................................................................................56 SCFile.toArray() .....................................................................................................................................57 SCFile.unshift(arrayItem) .......................................................................................................................58 JavaScript methods for the XML object .....................................................................................................59 XML.addAttribute(AttributeName, AttributeValue) .................................................................................59 XML.addElement(String)........................................................................................................................60 XML.appendNode(name).......................................................................................................................62 XML.createNode(type, name, value) .....................................................................................................63 XML.getAttributeNode(Attribute)............................................................................................................64 XML.getAttributeValue(Attribute) ...........................................................................................................66 XML.getDocumentElement()..................................................................................................................67 XML.getFirstAttribute(Element)..............................................................................................................68 XML.getFirstChildElement(Element)......................................................................................................71 XML.getName() .....................................................................................................................................73 XML.getNextAttribute(Element) .............................................................................................................74 XML.getNextSiblingElement(Element)...................................................................................................76 XML.getNodeName() .............................................................................................................................79 XML.getNodeType() ..............................................................................................................................80 XML.getNodeValue() .............................................................................................................................81 XML.getParentNode(Element)...............................................................................................................82 XML.getPrefix()......................................................................................................................................85

XML.getQualifiedName() .......................................................................................................................87 XML.getText() ........................................................................................................................................89 XML.getValue()......................................................................................................................................90 XML.importNode(name).........................................................................................................................92 XML.isDocumentElement() ....................................................................................................................93 XML.setAttributeValue(AttributeName, AttributeValue) .........................................................................95 XML.setContent(String) or XML.setContent("FilePath", IsFile) ..............................................................97 XML.setNodeValue(String) ....................................................................................................................99 XML.setText(String) ............................................................................................................................. 100 XML.setValue(String)........................................................................................................................... 101 XML.toXMLString() .............................................................................................................................. 103 JavaScript methods for the XMLDate object............................................................................................ 103 XMLDate.addDuration(duration) .......................................................................................................... 103 XMLDate.getDate() .............................................................................................................................. 104 XMLDate.getDatum() ........................................................................................................................... 104 XMLDate.getGMTSCDateTimeString()................................................................................................ 104 XMLDate.getISODate()........................................................................................................................ 105 XMLDate.getISODateTimeString() ...................................................................................................... 105 XMLDate.getISODay() ......................................................................................................................... 105 XMLDate.getISOMonth() ..................................................................................................................... 105 XMLDate.getISOTime() ....................................................................................................................... 106 XMLDate.getISOYear()........................................................................................................................ 106 XMLDate.getSCDateTimeString()........................................................................................................ 106 XMLDate.JSDate()............................................................................................................................... 107 XMLDate.toSCDuration(duration) ........................................................................................................ 107 Cross-reference: Index of methods and functions by task .......................................................................... 108 Array handling.......................................................................................................................................... 108 Date/Time handling.................................................................................................................................. 109 Database or file manipulation .................................................................................................................. 110 Basic functionality .................................................................................................................................... 110 Conversions............................................................................................................................................. 111 XML ......................................................................................................................................................... 111 For more information.................................................................................................................................... 114

IntroductionWith the release of ServiceCenter 6.0, system administrators can now use the standard JavaScript scripting language to customize their ServiceCenter applications. JavaScript is a widely supported, industry-standard programming language that eliminates the need for a separate programming skill set, and reduces user reliance on proprietary tools. The introduction of JavaScript into ServiceCenter does not invalidate the current ServiceCenter RAD tool set; instead, the JavaScript interface is an alternative to the RAD language for tailoring.

RequirementsThis document is targeted for ServiceCenter system administrators and assumes that the reader is familiar with object-oriented programming and JavaScript development. It provides an overview of JavaScript functionality in ServiceCenter, using both examples and descriptions of JavaScript's objects, properties, methods, and functions.

How to use this documentThis document is divided into three sections: The section Introduction to JavaScript in ServiceCenter introduces basic rules of JavaScript and describes its use in ServiceCenter. The section Use of JavaScript in ServiceCenter describes the use of the JavaScript language as it relates to ServiceCenter customization and tailoring. It provides detailed examples to aid beginners who are developing their first JavaScript application in ServiceCenter. The Programmers reference is a complete reference for JavaScript in ServiceCenter. It includes information and key examples for all available objects, properties, and methods.

Introduction to JavaScript in ServiceCenterLike RAD, JavaScript in ServiceCenter provides the ability to query, insert, update, and delete database records, and to make use of existing RAD variables and functions. The principal benefit of using JavaScript is that it uses an industry-standard scripting language to execute commands instead of a proprietary language. JavaScript within ServiceCenter is implemented using the Mozilla SpiderMonkey (JavaScriptC) Engine. For detailed information about the syntax of Mozilla SpiderMonkey JavaScript, refer to:http://wp.netscape.com/eng/mozilla/3.0/handbook/javascript/index.html

For information about the SpiderMonkey project refer to:http://www.mozilla.org/js/spidermonkey/

Language overviewJavaScript is a scripting language which is different from programming languages like Java, C++ or Visual Basic. It is a smaller, dynamically typed scripting language that offers programming tools with easy syntax and built-in functionality. Unlike programming languages, scripting languages do not use compilers to create executable program code. Because JavaScript is an interpreted language, each time the script is executed, it is loaded into an interpreter that runs the code. The Compile button in the Script Library does not create an executable load module; it runs a syntax check to verify that the script is executable. JavaScript can be either client-side, server-side, or core language. Core JavaScript is the base JavaScript language with client-side and server-side JavaScript as extensions. Server-side JavaScript is used for accessing and manipulating data, and is the only one available within ServiceCenter.

4

Basic rules of JavaScriptThe following rules apply to the basic syntax of JavaScript: JavaScript is case-sensitive. Statements should end in a semicolon (;). Variables Must be defined before being used. The variable name can contain A Z, a z, underscore or digits and must start with a letter or an underscore (_). Assume the type of the data that is put into the variable. The data type does not have to be explicitly defined. Are global variables when defined outside of a function, and are available anywhere in the current application. Variables created within a function are local variables, and can be used only within that function.

Strings have to be enclosed in quotation marks, either a single or double. For example: print(Hello + world + Country.name) produces the following: Hello world US. Special characters that are displayed literally must be preceded by a backslash character (\). Quotes within a string can be entered preceded by a backslash as well. Seehttp://wp.netscape.com/eng/mozilla/3.0/handbook/javascript/index.html

Part 2, Item 6, "String literals" section for more information. To increment a variable, such as a = a + 1, you can use a++. You can decrement a variable in the same way, as in a--. To enter comments in the script, use "//" to start a single line comment or the combination of "/*" and "*/" to enclose a multi-line comment. Values that are not defined as a data type (string, number, Boolean) may be defined as an object, such as Date, Array, Boolean, String, and Number. As an example you could define: var ArrayList=new Array(test, this, list); Dots in ServiceCenter field names must be replaced by an underscore (_) in JavaScript. For example contact.name becomes contact_name. ServiceCenter field names that are reserved words in JavaScript have to be preceded by an underscore, such as _class for the class field.

Structure of a JavaScript application function () { }

Expressions and operatorsFor more information on this topic refer to:http://wp.netscape.com/eng/mozilla/3.0/handbook/javascript/index.html

See Part 2, Item 7, "Expressions and Operators" section. The list of operators includes assignment operators, comparison operators, arithmetic operators, bitwise operators, logical operators, string operators, and special operators.

JavaScript objects and propertiesThe key to understanding JavaScript is learning the structure of its objects. JavaScript is an objectoriented language with many similarities to the C programming language. Most JavaScript functionality is contained in objects. The objects contain methods, parameters, and events. Each object may contain a set of properties that more closely define the object. JavaScript objects do not have normal class-to-subclass relationships: Subclasses are contained within classes but do not

5

inherit their properties. The syntax you use to call methods and properties is: Object.method or Object.property. For more information on JavaScript objects and properties refer to:http://wp.netscape.com/eng/mozilla/3.0/handbook/javascript/index.html

See Part 2, Item 8, "Object model" section.

Built-in objects and functionsBuilt-in objects described in this section are Array, Boolean, Date, Function, Math, Number, and String. Each of these is described in detail at:http://wp.netscape.com/eng/mozilla/3.0/handbook/javascript/index.html

See Part 2, Item 9, the "Built-in objects and functions" section.

Conditional statementsThe following example returns true if the date entered is within the number of days in a month (here, 30 days); otherwise, it returns false. Note the use of the conditional statement to shorten the "if" expressions. The statement: var return = (parm.Date.getDate 1 ) {

6

ParmNumber = ParmNumber / 2; i++; } return i; } Note: A Do..While loop is available for those instances when you want to execute a statement (or block of statements) at least once. In a Do..While loop the exit condition is checked after the statements are executed.

Break and continue statementsThe break statement terminates a "while" or "for" loop completely. The continue statement terminates execution of the statements within a "while" or "for" loop and continues the loop in the next iteration. The following two examples demonstrate how these statements are used. Note: Both these statements violate the rules of structured programming, but are nonetheless widely used in special cases. function { var i var n while { if { break4error(parmArray, x) = 0; = 0; (i < 10) (isNaN(parmArray[x])) print(parmArray[i].toString + is not numeric. Please repair and run again; break; } n = n + parmArray[i]; i++; } return n; } Modifying the above example, the continue statement would work as follows: function { var i var n while { if { break4error(parmArray, x) = 0; = 0; (i < 10) (isNaN(parmArray[x])) print(parmArray[i].toString + is not numeric. Continuing with next number; i++; continue; } n = n + parmArray[i]; i++; } return n; }

Use of JavaScript in ServiceCenterYou can use JavaScript in the previously discussed tailoring tools in ServiceCenter 6.x and higher. In addition to these areas where JavaScript can be entered directly, the functions entered in the ScriptLibrary can be accessed from anywhere in ServiceCenter where expressions are evaluated, such as on a RAD process panel.

7

Order of execution of JavaScript versus RAD languageThis section lists all tailoring tools in which JavaScript can be directly entered and describes at what point in the process the JavaScript code will be executed. FormatControl The JavaScript is executed after calculations and before validations. JavaScript code in FormatControl is executed via the format.cjavascript RAD. Links JavaScript in links is executed after the (initial) expressions, but before the fill or find is executed. This is done in us.link on evaluate.expressions. The post JavaScript is executed after the fill or find was performed, immediately after the post expressions. This happens in us.fill or us.find, respectively, on the eval.post.expressions panel. Triggers The JavaScript in the triggers file is executed after the RAD application. This is controlled by the server binaries, and not by RAD code. Cascade updates The JavaScript in cascade updates is executed from the RAD application process.update.config.record. The evaluate expressions panel is executed before the evaluate.javascript panel, so that expressions take precedence over JavaScript. Scripts In script.execute on panel exec.statements, RAD expressions are processed before JavaScript expressions. Wizards Wizards use JavaScript in 3 different areas: During File Selection, Actions, and Cancel Expressions. File Selection: The Select $L.file by information is processed first, followed by the Initial Expressions and the JavaScript. Actions: In the Actions tab, the Expressions are run first, then the JavaScript, followed by the information on the Format Control / Process Name tab. Cancel Expressions: Here first the Expressions Executed on Cancel are processed, followed by Javascript Executed on Cancel. Interoperability (ioaction file) The ioaction file executes only JavaScript, and not RAD, expressions. The JavaScript code is executed in the ioevents.process.action application on the panel process.action. Display screens In the display application on the panel prep.screen, the JavaScript expressions are executed after the RAD expressions. Display options Display options have pre- and post-JavaScript and RAD expressions that are executed in the following order:1. 2. 3. 4. 5. 6.

Pre-RAD expression Pre-JavaScript RAD application Post-RAD expression Post-JavaScript Display Action

8

Processes Process records have initial and final JavaScript and RAD expressions that are executed in the following order:1. 2. 3. 4. 5. 6. 7. 8.

Initial RAD expression Initial JavaScript Pre-RAD expressions RAD application(s) Post-RAD expressions Final RAD expression Final JavaScript Next Process (if applicable)

Schedule JavaScript in the schedule record is executed after the RAD application is called, and before the check for deleting or rescheduling the schedule record.

The ScriptLibraryThe ScriptLibrary is a file within ServiceCenter used to create, edit, compile, test, and store scripts and functions that can be called and executed from anywhere within ServiceCenter. Some of these stored JavaScript programs can be used to interface with 3rd party Web Services providers, such as real-time currency conversions. All of these JavaScripts are identified as SOAP packages within the ScriptLibrary. The integration of the Get-Answers product is performed through JavaScript stored in the Script Library as well. Note: Do not use Adminstrative Mode when entering the ScriptLibrary, since functions such as compile and execute are not available in that mode.

Using the ScriptLibraryThe Script Library has several sections. The name of the record is used to call the JavaScript via either system.library.., or via jscall(). The package field is used to group records for easier maintenance. The color-coded script editor is used to enter JavaScript code. The color codes that the script editor uses are: Red: Keywords Green: Objects, methods, and properties Teal: Comments Blue: Strings Black: Default color The screen displayed below shows how all these colors appear in the script editor:

9

When working with the ScriptLibrary, you can compile the JavaScript code to check for syntax errors. Executing the script will compile the code and then execute it. For executing the code, ensure that all input is made available. You can access any script or function in the ScriptLibrary from any tool within ServiceCenter that supports JavaScript, by using the following syntax: system.library..( parameters ) Within a ScriptLibrary record, you can call any function that is defined previously within the same record by simply typing: ( parameters ) To call JavaScript from any RAD process panel, you can use the jscall RAD function. The syntax for this function is: jscall( "script.function" , arg1 , arg2, ... , argN ) The following statements illustrate a JavaScript call to the system library, and a call to the script library via jscall(), respectively: system.library.tzfunctions.getTZforOperator(falcon); jscall(tzfunctions.getTZforOperator, falcon);

Corresponding JavaScript syntax for RAD language tasksMost ServiceCenter tasks can be translated from RAD language to JavaScript by using the following table.ServiceCenter task Create a file variable Select a record Update a record Add a record Delete a record Refer to a field in a file Access an element of an array RAD panel / expression rinit select rupdate radd rdelete result=fieldname in filevariable result=rownumer in arrayname in filevariable JavaScript expression new SCFile(filename) RC=ObjectName.doSelect(Query) RC=ObjectName.doUpdate() RC=ObjectName.doInsert() RC=ObjectName.doRemove() result=ObjectName.fieldname result=ObjectName.arrayname[rownumber]

10

ServiceCenter task Send a message to screen Convert a field / Object to string

RAD panel / expression call message application string()

JavaScript expression print(message) RC=ObjectName.getText()

JavaScript global propertiesGlobal properties are predefined properties that are not part of any object. They are names representing values that are globally defined. The core JavaScript language has several global properties, such as NaN, and ServiceCenter has a number of additional global properties. There are two categories of ServiceCenter-defined global properties: Query operators JavaScript return code properties

Query operatorsThese operators are used solely for constructing query expressions using the Query object. Note: The Query object has been deprecated, but older JavaScript code within the ScriptLibrary still uses the object.Query operator EQ LIKE NEQ GT GE LT LE ISIN Description Equals to Starts with Not equal to Greater than Greater or equal to Lower than Lower or equal to Is an element in the array

Example: var q = new Query("filename", new QueryCond("name", EQ, "ThisFile"));

JavaScript return code propertiesUse these properties (which are represented internally as integer values) to test the values returned by object methods such as SCFile. To print the error message rather than the return code, use the RCtoString function.Return code RC_ERROR RC_SUCCESS RC_CANT_HAVE RC_NO_MORE RC_DUPLICATE_KEY RC_MODIFIED Description Some other error occurred. Examine the contents of the Messages view or the sc.log file for more information. The operation succeeded. The operation failed because the resource is unavailable because some other user or process has the resource locked. No more records are available in the result set. The insert operation failed because the file already contains a record with this unique key value. The update operation failed because the record was modified by another user or process since you read it.

11

Return code RC_DELETED RC_BAD_QUERY RC_NOT_AUTHORIZED

Description The operation failed because the record was deleted by another user or process. The query failed due to incorrect query syntax. The request operation was not performed due to an authorization failure. Check the permissions associated with the user who submitted the request. The operation failed because the data supplied in a field or the record did not pass validity checks performed by the application. The operation failed. Check to make sure the file name is correct, that the file exists, and that it is not read-only. The operation failed. Check to make sure the file name is correct, that the file exists, and that it is not read-only. The operation failed. Check to make sure the file name is correct, that the file exists, and that it is not read-only. The operation failed because the file name is not valid.

RC_VALIDATION_FAILED RC_UNABLE_TO_WRITE_TO_FILE RC_UNABLE_TO_CLOSE_FILE RC_UNABLE_TO_DELETE_FILE RC_INVALID_FILENAME

Example var rc = mySCFile.doInsert(); if ( rc == RC_SUCCESS ) { print( "Insert succeeded" ); } Else throw( "Error " + RCtoString(rc) + " occurred trying to insert a record" );

Examples of calling JavaScript from different ServiceCenter toolsThe following examples offer suggestions about using JavaScript in some of the tailoring tools that support this functionality. Additional JavaScript examples can be found in the Programmers reference section of this document.

FormatControlThe following example can be used to verify whether the operator who was just entered in the assignee.name field in the incident ticket is currently logged in. Otherwise, validation will fail. In the Calculations section of FormatControl, in the initial column enter a condition of true. Then add the following in the calculation column: $assignee.old = nullsub(assignee.name in $file, no assignee) Click the JavaScript tab, enter true for Add and Update, and enter the following statements: var usersXML = system.users; var usersString = usersXML.toXMLString(); var file = system.vars.$file; var newAssignee = file.assignee_name; system.vars.$IsUser=usersString.indexOf(newAssignee); In the Validation section enter the following, in the Add and Update column: assignee.name in $file~=$assignee.old; And the following expression in the Validation column: $IsUser > 0

12

Enter the following in the Validation message field: The new assignee is not logged in at this time. Please try another assignee. This example uses the standard indexOf method for the String Object, and the toXMLString() function, to search for the user who was entered as the new assignee in the XML object containing all logged-in users. Any RAD variable can be set and used by preceding it with system.vars. This lets variable values be exchanged between JavaScript and RAD expressions.

TriggersIn this example a trigger sends a message to the assignment group in an incident ticket that the ticket has been updated, and to whom it is assigned. Then it adds an activity with the information that the message has been sent. var NewRecord=system.vars.$L_new; /* This is the $L.new record passed in from the trigger */ var incNumber=NewRecord.number; var incAssignee=NewRecord.assignee_name; if (incAssignee==null) { incAssignee="no one at the moment"; } /* Insert a message schedule record into the schedule file */ function insertSchedule( incNumber, incAssignee, Adressees) { var newSchedule = new SCFile( "schedule" ); var today=new Date(); newSchedule.application= "message.bg"; newSchedule._class = "problem"; newSchedule.name= "message processor record"; newSchedule.expiration= today; newSchedule.strings[1]="1"; newSchedule.strings[2]="problem update"; newSchedule.strings[3]="Problem " + incNumber + " has been updated. It is assigned to " + incAssignee + "."; newSchedule.strings[5]="pm.main"; newSchedule.strings[6]=" Soap-Windows XP"; newSchedule.strings1=Adressees; var rc = newSchedule.doInsert(); } /* Selects the operators that are members of the assignment group to return to the calling function */ function selectAddressees(assignmentGroup) { var assignment = new SCFile( "assignment" ); var findAssignee = assignment.doSelect( " name=\""+ assignmentGroup + "\"" ); if ( findAssignee == RC_SUCCESS ) { addressList=assignment.operators; return addressList; } else { print( "Could not find assignment group. " + RCtoString( findAssignment ) ); return null; } } /* Inserts an activity with the information that the email notification to the assignment group members has been sent */ function addActivity(incNumber) {

13

var newActivity = new SCFile( "activity" ); var today=new Date(); newActivity.number= incNumber; newActivity.datestamp= today; newActivity.type= "Update"; newActivity.description[0]= "Notification email on the update has been sent to all members of the assignment group."; var result = newActivity.doAction("add"); if (result == RC_CANT_HAVE || result == 51 ) { system.library.activityUpdates.scheduleActivityUpdate ( newActivity, newActivity.type, newActivity.description ); } } /* Selects the operators to send the message to */ Addressees = selectAddressees( NewRecord.assignment ); if (Addressees != null) { /* adds the message to the schedule file for sending */ insertSchedule( incNumber, incAssignee, Addressees); /* adds an activity to inform the user of the email being sent*/ addActivity(incNumber); } The example shows (among other things) how to call a Document Engine Action; how to call a function from the Script Library; and how to insert a new record. In addition, it shows how to use several functions within a single JavaScript and how to call them. Note: Because the class field name in the schedule file is in conflict with the class keyword used in JavaScript, it must be preceded by an underscore (_).

LinksThe following JavaScript code: Queries the configuration item that was previously selected from a fill. Increases a counter in that configuration item called num.issues.on.CI (this new field has to be added in the device file). Adds the new ticket number to an array of issues in the device file called array.incidents. Updates the device record. If the configuration item does not exist, it issues an error message. If the item is currently down, it sends an alert to the person who is opening the ticket. var CI_Record=new SCFile("device"); /* opens the device file */ var CIName=system.vars.$File.logical_name; /* passes in the logical name from $File */ /* Selects the configuration item to update */ function getConfigurationItem( CIName ) { var findCI_RC = CI_Record.doSelect( "logical.name=\""+ CIName + "\"" ); if (findCI_RC==RC_SUCCESS) { return CI_Record; } else { print( "Could not find configuration Item. " + RCtoString( findCI_RC ) ); return null; } } /* Increases the use counter that counts how often this item was affected by an incident ticket and enters the incident ticket number into the array of incidents */

14

function increaseUseCounter(CI) { if (CI.is_down == true) { print("The configuration item is down at the moment. Please check existing tickets if the cause for this issue is related to the down system."); } CI.num_issues_on_CI++; /* increase counter */ var incNumber = system.vars.$File.number; /* get the incident ticket number */ var array_incidents = new Array(); var ind = 0; while(CI.array_incidents[ind] != null) /* convert the SC array into a JS array (see paragraph below) */ { array_incidents[ind]=CI.array_incidents[ind]; ind++; } var j=0; var temp_string = array_incidents.toString(); var i = temp_string.indexOf(incNumber); if (i < 0) /* Check if incident is already in the list */ { /* If not, enter the incident number to the list *? if (array_incidents == null) { j=0; } else { j=array_incidents.length; } array_incidents[j] = incNumber; CI.array_incidents = array_incidents; } CI.doUpdate(); } /* Call previously defined functions to execute code */ CI=getConfigurationItem(CIName); increaseUseCounter(CI); This example shows how to query a record from within ServiceCenter, and how to update fields in that record. Additionally it shows how to transfer an array from ServiceCenter to JavaScript. An array from ServiceCenter cannot be directly copied into a JavaScript array, because the syntax of ServiceCenter {IM1001, IM1002} does not work in JavaScript. Properties such as the length property assume that the value is a function if it is enclosed in curly braces {}. To successfully convert a ServiceCenter array into a JavaScript array, you can either use the SCFile.toArray method, or create a "while" loop or a "for" loop to move through the elements and do an element-byelement transfer, as shown above. Note: In JavaScript it is very important that you handle null values. Functions such as length may not work on null values.

Programmers referenceThis section can be used by JavaScript developers as a reference for: JavaScript global system objects JavaScript global methods JavaScript objects JavaScript methods for the SCFile, SCDatum, and Datum objects JavaScript methods for the XML object JavaScript methods for the XMLDate object

15

JavaScript global system objectsGlobal objects are predefined objects that are always instantiated and cannot be created using the new operator. Objects may have methods and subordinate properties to which you refer using the dot (.) operator. The primary global object is the System object, which acts as a container for an entire hierarchy of global objects, all of which are properties of the System object. Note: None of the ServiceCenter global system objects have constructors. The following is a complete list of global objects, which are exposed as properties of the System object: system.files system.forms system.functions system.library system.oldrecord system.record system.sysinfo system.sysobjects system.threads system.user system.users system.vars Note: All of the alias or shortcut global objects available in ServiceCenter 6.0 are deprecated in version 6.1 because the alias or shortcut is likely to be used as a script variable. Scripts that attempt to use these names as variables may not function as expected. Therefore, you must type out the entire global system object name, for example, system.user instead of user.

system.filesThe system.files JavaScript object is unique to ServiceCenter. It allows you to call a particular ServiceCenter table into memory. Its syntax is: system.files.. There are no arguments and no methods for the system.files object, and the following property is valid for it:Property table name Required Yes Description Specifies the table name you want to initialize for processing.

Example This example sets a variable equal to system.files.contacts and displays the contents of the contacts table It requires a valid ServiceCenter table name (for example, contacts) as sample data: var f = system.files.contacts; print( "The value of system.files.contacts is:\n" + f );

system.formsThe system.forms object allows you to call a particular ServiceCenter form into memory. It is unique to ServiceCenter. Its syntax is: system.forms.form_name. There are no arguments or methods for this object, and the following property is valid for it:

16

Property form_name

Required Yes

Description The name of the form you want to bring into memory.

Example This example sets a variable equal to system.forms.ScriptLibrary, and displays the contents of the ScriptLibrary form. It requires a valid ServiceCenter form name (for example, ScriptLibrary) as sample data: var fm = system.forms.ScriptLibrary; print( "The value of system.forms.ScriptLibrary is:\n" + fm );

system.functionsThis JavaScript object is unique to ServiceCenter. The system.functions object allows you to call a particular ServiceCenter RAD function from JavaScript. Its syntax is: system.functions.RAD function name( RAD function arguments ). The following argument is valid for this object:Argument RAD function arguments Data type String Required Yes Description Contains any arguments required to execute the RAD function.

The following property is valid for this object:PropertyRAD function name

RequiredYes

DescriptionContains the RAD function name you want to bring into memory.

Example This example sets a variable equal to system.functions.date(), and displays the results of the RAD date() function. It requires a valid ServiceCenter RAD function name (for example, date()) as sample data: fn = system.functions.date(); print( "The value of system.functions.date() is:\n" + fn ); A more complex use of system.functions shows how to insert a logical name value into the first positition of the group.members array: joinFile.group_members = system.functions.insert(joinFile.group_members,0,1, system.vars.$L_file.logical_name);

system.libraryThe system.library object allows you to call a particular ServiceCenter script library function. It is unique to ServiceCenter. The syntax for this object is: system.library.script name.function name( function arguments ). The following argument is valid for this function:Argument function arguments Data type String Required Yes Description Contains the function arguments you want to use.

No methods are defined for this object. The following properties are valid for this object:

17

Property script name function name

Required Yes No

Description Contains the name of the script you want to run. Contains the name of the function you want to run.

Example This example calls a script from the Script library. It requires the name of a valid ServiceCenter script (for example, SelfService) as sample data: print( "Runnng script system.library.SelfService..." ) system.library.SelfService.registerEssUser( BOB, HELPDESK, [email protected], 858-555-1212 );

system.oldrecordThe system.oldrecord JavaScript object allows you to call the last ServiceCenter record into memory. It is unique to ServiceCenter. Its syntax is: system.oldrecord. There are no arguments, properties, or methods defined for this object. Example The following example sets a variable equal to system.oldrecord, and displays the results of system.oldrecord. o = system.oldrecord; print( "The value of system.record is:\n" + o );

system.recordThe system.record JavaScript object allows you to call the current ServiceCenter record into memory. It is unique to ServiceCenter. The syntax for this object is: system.record. There are no arguments, properties, or methods defined for this object. Example This example sets a variable equal to system.record, and displays the results of system.record. r = system.record; print( "The value of system.record is:\n" + r );

system.sysinfoThe system.sysinfo JavaScript object allows you to call an XML list of properties about the ServiceCenter server. It is unique to ServiceCenter. Its syntax is: system.sysinfo. There are no arguments, properties, or methods defined for this object. Example This example sets a variable equal to system.sysinfo, and displays the results of system.sysinfo. s = system.sysinfo; print( "The value of system.sysinfo is:\n" + s );

system.threadsThe system.threads JavaScript object allows you to call an XML list of the current ServiceCenter threads into memory. It is unique to ServiceCenter.

18

The syntax is: system.threads There are no arguments, properties, or methods defined for this object. Example This example sets a variable equal to system.threads, and displays the results of system.threads. th = system.threads; print( "The value of system.threads is:\n" + th );

system.userThe system.user JavaScript object allows you to call an XML list of properties of the currently logged on ServiceCenter user. It is unique to ServiceCenter. The syntax is: system.user. There are no arguments, properties, or methods defined for this object. Example This example sets a variable equal to system.user, and displays the results of system.user. u = system.user; print( "The value of system.user is:\n" + u );

system.usersThe system.users JavaScript object allows you to call an XML list of the currently logged on ServiceCenter users into memory. It is unique to ServiceCenter. The syntax of this object is: system.users. There are no arguments, properties, or methods defined for this object. Example This example sets a variable equal to system.users, and displays the results of system.users u = system.users; print( "The value of system.users is:\n" + u );

system.varsThe system.vars JavaScript object allows you to call a particular ServiceCenter variable into memory. It is unique to ServiceCenter. Its syntax is: system.vars.variable name There are no arguments or methods for this object. The following property is valid for this object:Property variable name Required Yes Description Contains the variable name you want to bring into memory.

Example This example sets a variable equal to system.vars.$L_file, and displays the contents of the $L_file variable It requires a valid ServiceCenter variable name (for example, $L_file) as sample data: var v = system.vars.$L_file; print( "The value of system.vars.$L_file is:\n" + t );

19

JavaScript global methodsGlobal methods are functions that are available to any script; they are not methods of any specific object. You can invoke global methods directly, just as with any core JavaScript global function such as parselnt() or eval().

printBoth displays the contents of the argument ("string" or StringVariable) in the client Messages view, and prints it in the ServiceCenter log file. The syntax is: print ("string") Or print(StringVariable). The print method does not return any value and does not have any throws. The following argument is valid for this function:Argument "string" or StringVariable Data type output Required Yes Description Contains the text string or variable value you want the script to print to the Message View and the sc.log file. Enclose literal text strings in quotation marks.

Example var example = "abc123."; print ("The value of example is: " + example); This example created the following output: "The value of example is: abc123."

readFileReads the contents of a local file and returns a string object with the contents of that file. The file can be in either binary or text format, as specified by the binary argument. The syntax for this method is: readFile( path, binary ). The following arguments are valid for this function:Argument path Data type String Required Yes Description Contains the text string or variable value containing the fully qualified path of the file to be read. Enclose literal text strings in quotation marks. Determines whether the file format is binary or text. Use the string "b" or "B" to read a binary file. Use any other value to read a text file.

binary

String

Yes

Example This example reads the contents of a text file, and then reads the contents of a binary file. It requires both a text file and a binary file on the local file system as sample data. var textFile = readFile( "C:\\test.xml", "t" ); print( "The value of textFile is: " + textFile ); var binFile = readFile( "C:\\header_left.gif", "b" ); print( "The value of binFile is: " + binFile );

20

writeFileWrites the contents of the object parameter to a specified path and file, which can be in either binary or text format. It returns the number of bytes written to the file. The syntax for calling this method is: writeFile( path, binary, object ) The following arguments are valid for this function:Argument path Data type String Required Yes Description Contains the text string or variable value containing the fully qualified path of the file to be written. Enclose literal text strings in quotation marks. Specifies whether the file format is binary or text. Use the string "b" or "B" to write a binary file. Use any other value to write a text file. Contains the text string or variable value containing the data you want to write to a file.

binary object

String String

No Yes

Example This example writes the list of currently logged on users to a file. As sample data it needs the list of currently logged on users stored in system.users. var var var var userList = system.users; filePath; isBinary; fileObject;

function writeToFile( path, binary, object ) { print( "Writing " + path + " to file..." ); var output = writeFile( path, binary, object ); print( "The number of bytes written to file was: " + output ); return output; } filePath = "C:\\users.xml"; isBinary = null; fileObject = userList; writeToFile( filePath, isBinary, fileObject );

QuitStops the processing of JavaScript from the point it is called, and returns the failure return code specified in the return code argument. All JavaScript code after the Quit() method call is ignored. The syntax is: Quit( return code ). The following argument is valid for this function:Argument return code Data type Integer Required Yes Description Contains the numeric return code you want the method to return.

Example This example prints a message, quits, and returns a failure return code: print( "Testing the Quit() method..." ); Quit( -1 ); print( "You won't see this message because the JavaScript has already quit" );

21

base64EncodeConverts binary data to a base-64 string format. You can also use this method to encode plain text data in base-64 format. The method returns a string object with the data in base-64 format. The syntax for using this global method is: base64Encode( data ). The following argument is valid for this method:Argument data Data type Binary Required Yes Description Contains the data you want the script to encode in base-64 format.

Example This example reads the contents of a binary file, converts the file to a base-64 string format, and prints the base-64 string. It requires a binary file on the local file system (for example, an image file) as sample data: var source = readFile( "C:\\header_left.gif", "b" ); var encode = base64Encode( source ); print( "The value of encode is:\n" + encode );

base64DecodeConverts base-64 string data to its original format. Returns a binary or string object containing the original data. The syntax for this method is: base64Decode( data ). The following argument is valid for this method:Argument data Data type Binary Required Yes Description Contains the data you want the script to decode to its original format.

Example This example does the following: Reads the contents of a binary file. Converts the file to a base-64 string format. Writes the base-64 string data to a local file. Prints the number of bytes written to the local file system. Reads the contents of a base-64 string format file. Converts the data into a binary file. Writes the binary data to a local file. Prints the number of bytes written to the local file system. This example requires a binary file on the local file system (such as an image file) as sample data: var source = readFile( "C:\\header_left.gif", "b" ); var encode = base64Encode( source ); var encodedFile = writeFile( "C:\\base64EncodedImage.txt", "b", encode ); print( "Wrote " + encodedFile + " bytes to C:\\base64EncodedImage.txt" ); source = readFile( "C:\\base64EncodedImage.txt", "t" ); var decode = base64Decode( source ); var decodedFile = writeFile( "C:\\newImage.gif", "b", decode ); print( "Wrote " + decodedFile + " bytes to C:\\newImage.gif" );

22

xmlstringConverts a JavaScript string to an XML-formatted string. Does not return a value. The syntax is: xmlstring (string) The following argument is valid for this function:Argument string Data type String Required No Description Contains the text string or variable value you want the script to convert to an XML string.

Example var xmldoc = new SCFile ( system.users ); xmlstring ( xmldoc ); print ( xmldoc ); Output: falcon

doHTTPRequestSends an HTTP request to a remote server specified by a URL. This method returns a string containing an HTTP response or an error message. The syntax for this method is: doHTTPRequest( HTTP command, URL, Headers, POST body, Connect timeout, Send timeout, Receive timeout ) The following arguments are valid for it:Argument HTTP command URL Headers POST body Connect timeout Data type String String Array String Integer Required Yes Yes Yes No No Description Specifies a command verb such as GET or POST. Specifies the URL to which the script should send an HTTP request. If the HTTP request requires SSL then the URL must start with https. Contains a JavaScript array of ServiceCenter-defined Header objects or an empty array. See the Header object for more information. Contains the body of a POST command request. Specifies the connection timeout threshold in seconds or milliseconds. Use positive integers for second thresholds and negative integers for millisecond thresholds. Use a value of zero for an infinite connection timeout threshold. Specifies the send timeout threshold in seconds or milliseconds. Use positive integers for second thresholds and negative integers for millisecond thresholds. Use a value of zero for an infinite connection timeout threshold. Specifies the receive timeout threshold in seconds or milliseconds. Use positive integers for second thresholds and negative integers for millisecond thresholds. Use a value of zero for an infinite connection timeout threshold.

Send timeout

Integer

No

Receive timeout

Integer

No

Example This example sends an HTTP request to the ServiceCenter Web Services API, and writes the response to a local file. It requires the URL to the ServiceCenter Web Services API as sample data: var url = "http://localhost:12670/IncidentManagement.wsdl"; var headers = new Array(); var IMWSDL = doHTTPRequest( "GET", url, headers, null, 10, 10, 10 );

23

var reply = writeFile( "C:\\IncidentManagement.wsdl", "text", IMWSDL );

doSOAPRequestIssues a SOAP request to a remote server specified by an URL, and returns the SOAP response in a string or an error message. The syntax for this method is: doSOAPRequest( URL, SOAPAction, XML, SOAP user ID, SOAP password, Connect timeout, Send timeout, Receive timeout, Attachment object ) The following arguments are valid for it:Argument URL SOAPAction XML Data type String String String Required Yes Yes Yes Description Specifies the URL to which the script should send an HTTP request. If the HTTP request requires SSL, then the URL must start with https. Specifies the SOAP request. Contains the XML for an entire SOAP request including the SOAP envelope. Refer to the Web Service's WSDL to determine the proper format of the SOAP request. Contains the user ID to be used for the Basic Authorization HTTP header. Contains the password value to be used for the Basic Authorization HTTP header. Specifies the connection timeout threshold in seconds or milliseconds. Use positive integers for second thresholds and negative integers for millisecond thresholds. Use a value of zero for an infinite connection timeout threshold. Specifies the send timeout threshold in seconds or milliseconds. Use positive integers for second thresholds and negative integers for millisecond thresholds. Use a value of zero for an infinite connection timeout threshold. Specifies the receive timeout threshold in seconds or milliseconds. Use positive integers for second thresholds and negative integers for millisecond thresholds. Use a value of zero for an infinite connection timeout threshold. Contains a JavaScript array of ServiceCenter-defined Attachment objects or an empty array. See the Attachment object for more information.

SOAP user ID SOAP password Connect timeout

String String Integer

No No No

Send timeout

Integer

No

Receive timeout

Integer

No

Attachment object

Array

No

Example This example sends a SOAP request to a delayed stock quote Web service, and prints the SOAP response to the screen. It requires the following sample data: The URL to a Web-based delayed stock quotation service. The stock symbol for the company. var url = "http://ws.cdyne.com/delayedstockquote/delayedstockquote.asmx"; var action = "http://ws.cdyne.com/GetQuote"; var xml = " GOOG 0 "; var uid = null; var pass = null; var attachments = new Array();

24

var quote = doSOAPRequest( url, action, xml, uid, pass, 10, 10, 10, attachments ); print( "The return value is: " + quote );

makeSCWebURLThis method creates and returns a string containing a URL query to the ServiceCenter Web tier. It does not convert any special characters in the URL (such as spaces or quotation marks) to the characer code equivalent in URL format. You can use the encodeURL method to convert any special characters in the URL. The syntax is makeSCWebURL( Web tier URL, docEngine, table name, query, hash key seed, action, title ) The following arguments are valid for this function:Argument Data type Required Description This argument specifies the fully qualified URL to the ServiceCenter Web tier. This URL must include the http:// protocol syntax as well as the server name or IP address and communications port number. This argument specifies that the query should be handled by the ServiceCenter Document Engine. This argument does not accept any other string value. This argument specifies the table where the Document Engine should query for records. This argument specifes the ServiceCenter query you want to use to search for records. The query should be in the ServiceCenter server's system language format. This argument specifies an optional string you want to use to create a unique hash key. The hash key seed does not appear in the final URL produced. This argument specifies the Document Engine action you want the URL query to perform. By default, the URL query performs a search operation. This argument specifies the optional title.

Web tier URL

String

Yes

docEngine

String

Yes

table name

String

Yes

query

String

Yes

hash key seed

String

No

action title

String String

No No

Example This example creates a URL query to the ServiceCenter Web tier and converts any special characters in the URL to valid URI format. It requires the following sample data: The URL to ServiceCenter Web tier A valid ServiceCenter table name (for example, incidents) A valid ServiceCenter query against the table (for example, incident.id="SD1001") function createURLquery( table, query, title ) { var url; var webtier; var webserver; var doceng; var hashkey; var action; webserver = "http:///sc/index.do"; doceng = "docEngine"; hashkey = ""; action = ""; webtier = makeSCWebURL( webserver, doceng, table,

25

query, hashkey, action, title ); print( "Creating URL from information provided..." ); print( "The value of webtier is:\n" + webtier ); print( "Converting special characters in URL to valid URI format..." ); url = encodeURI( webtier ); print( "The value of url is:\n" + url ); return url; } var tablename = "incidents" var SCquery = "incident.id=\"SD1001\"" var titlename = "Interaction SD1001" createURLquery( tablename, SCquery, titlename );

helpDisplays a brief description of a ServiceCenter-defined JavaScript object. Requires the use of the print() method to see the help text string. Returns a brief text string describing the ServiceCenterdefined JavaScript object, or returns null if no help is available. The syntax is: help( object ). The following argument is valid for this function:Argument object Data type ServiceCenter-defined JavaScript object Required Yes Description Contains the ServiceCenter-defined JavaScript object for which you want a brief description.

Example This example displays the help contents of several ServiceCenter-defined JavaScript objects var f = new SCFile(); print( help( f ) ); var x = new XML(); print( help( x ) ); var d = new XMLDate(); print( help( d ) );

RCtoStringConverts a ServiceCenter global return code value into a localized text string. The syntax is: RCtoString( return code ). The following argument is valid for this function:Argument return code Data type Integer Required Yes Description Contains the ServiceCenter global return code value that you want to convert to a localized string.

Example This example searches the contacts table for any contact name you define in the search variable, and displays the contact record as a text string. It requires the following sample data: A valid contact name (such as "FALCON, JENNIFER") and an invalid contact name (such as "NOT A, CONTACT"). var contactName; function findContactName( name ) {

26

print( "Searching for contact: " + name + "..." ); var contactList = new SCFile( "contacts" ); var findContact = contactList.doSelect( "contact.name=\""+ name + "\"" ) if ( findContact == RC_SUCCESS ) { print( "Success. found " + name + " in contact record:\n" + contactList.getText() ); return contactList; } else { print( "Could not find contact. " + RCtoString( findContact ) ); return null; } } contactName = "FALCON, JENNIFER"; findContactName( contactName ); contactName = "NOT A, CONTACT"; findContactName( contactName );

executeValidates the syntax of a JavaScript and displays the message "Successful compilation of JavaScript function or expression" if the JavaScript passes validation; otherwise displays an error message. The compile() method is an alias of the execute() method. The syntax for this method is: execute( script, description ). No throws are defined for it, and the following arguments are valid for it:Argument script description Data type String String Required Yes No Description Contains the name of the script you want to validate. Use this argument to store any comments you want.

Example This example creates a variable to store a JavaScript name, and validates the contents of the script. It requires a valid JavaScript for sample data: var s = "lib.SCFILEgetTextTest"; excute( s, "Testing execute" );

compileValidates the syntax of a JavaScript and displays the message "Successful compilation of JavaScript function or expression" if the JavaScript passes validation; otherwise displays an error message. The compile() method is an alias of the execute() method. The syntax for this method is compile( script, description ). No throws are defined for compile(). The following arguments are valid for it:Argument script description Data type String String Required Yes No Description Contains the name of the script you want to validate. Use this argument to store any comments you want.

Example This example creates a variable to store a JavaScript name, and validates the contents of the script. It requires a valid JavaScript for sample data: var s = "lib.SCFILEgetTextTest"; compile( s, "Testing execute" );

27

JavaScript objectsAttachmentThis object is unique to ServiceCenter and contains attachment data for use with doSOAPRequest methods. You can use the readFile global method to add data to the Attachment object. You can use the push method to add Attachment objects to a JavaScript array. The constructor is: new Attachment(); No arguments are passed into the object. The following properties are valid for it:Property value len href action Data type Binary Integer String String Description Contains the binary data of the attachment. Contains the length of the binary data in bytes. Contains the unique identifier for the attachment in the SOAP request message. Contains the name of action to take with the attachment in ServiceCenter Web Services ServiceCenter API. The following options are available:

name type attachmentType String String String

add Adds the specified attachment. remove Removes the specified attachment. get Retreives the specified attachment. update Updates the specified attachment.

Contains the name of the attachment, which is typically a file name. Contains the MIME type of the attachment. Pertains only to ServiceCenter attachments, and contains the attachment type as defined in ServiceCenter. If present, and if the property has a value of "img," then the attachment must also have a MIME type of "image/bmp".

There are no methods defined for this object. Example var a = new Attachment(); var source = readFile( "C:\\header_left.gif", "b" ); a.value = source; a.name = "C:\\header_left.gif"; print( "The value of a is: " + a ); print( "Setting attachment value to source: " + a.name ); print( "The size of the attachment is: " + a.len + " bytes" );

HeaderWith no arguments, the Header() constructor, new Header(), creates an empty Header object. With the HTTP header arguments, the Header() constructor, new Header(Header type, Header value) creates an Header object containing the provided header types and values. Always enclose header types and header values in quotation marks. This JavaScript object is unique to ServiceCenter. The following arguments are valid for it:Argument Header type Header value Description The HTTP header type, such as "Accept-Encoding" or "Content-Type". The HTTP header value, such as "gzip,deflate" or "text/html".

28

No properties or methods are defined for this object. Example var h = new Header( "Accept-Encoding", "gzip,deflate" ); var hd = new Header(); hd.name = "Content-Type"; hd.value = "text/html"; var headers = new Array(); headers.push( hd );

DatumThe Datum JavaScript object is unique to ServiceCenter. You can use the SCFile or SCDatum objects in place of this object to take advantage of the improved return code values. Note: The Datum Object was deprecated as of ServiceCenter 6.1 because this object's methods can return only Boolean values. It is still often used to access ServiceCenter arrays. With no parameters, the Datum() constructor, new Datum() creates an empty Datum object. When an Object parameter is used with the Datum() constructor, new Datum(Object) creates a ServiceCenter-formatted Datum object containing the specified record, structure, or array. Always enclose table names and arrays in quotation marks. You can use the Datum object as a parameter for RTECall routines that expect ServiceCenter-formatted parameters. The following argument is valid for this object:Argument Object Data type String Description The ServiceCenter table name, record, structure, or array you want to query or update.

This object has no properties. The following methods are valid for it. Note: Detailed instructions for these methods can be found in the section JavaScript methods for the SCFile, SCDatum, and Datum objects.Method Name doAction doDelete doInsert doRemove doSave doSelect doUpdate getFirst getLast getNext getPrev getSize Description Executes a method defined on the object. Synonymous with the doRemove method, this method simply has a more intuitive name. Inserts an object into the database. Removes an object from the database. Inserts a record if it is new, and updates the record if it already exists. Makes a query. It no longer requires that the first argument be the name of the table if the object is constructed with the name of the table. Updates the database. Moves to the first record if the object represents a result set. Moves to the last record if the object represents a result set. Moves to the next record if the object represents a result set. Moves to the previous record if the object represents a result set. Returns the size of the object.

29

Method Name getText getType getXML isRecord join JSDate length pop push setType setValue shift toArray unshift

Description Returns a text representation of the object. Returns the object type. Returns an XML representation of the object. Checks whether an object represents a current table and has a record. Returns a string of all the entries in the array. Returns a JavaScript Date object. Returns the length of the object. Removes an item from an array. Adds an item to an array. Sets the object type. Sets the object to a given value. Returns a string of all the entries in the array. Converts an object to a JavaScript array. Returns a string of all the entries in the array.

Example var q = new Datum("contacts"); if ((q.soSelect('contact.name # "B"')) == true) { print (q.getText()); { else { print("No contacts start with B"); }

SCDatumSCDatum, which is unique to ServiceCenter, is an alias of the SCFile object. When used with no parameters, the SCDatum() constructor, new SCDatum() creates an empty SCDatum object. When used with the object parameter, the SCDatum() constructor, new SCDatum(object) creates an SCDatum object containing the specified record, structure, or array. Always enclose table names and arrays in quotation marks. This object's methods use the ServiceCenter-defined global return codes. The following argument is valid for this object:Argument object Description The table name, record, structure, or array you want to query or update.

No properties are defined for this object. The following methods are valid for it: Note: Detailed instructions for these methods can be found in the section JavaScript methods for theSCFile, SCDatum, and Datum objects.

30

Method Name doAction doDelete doInsert doRemove doSave doSelect doUpdate getFirst getLast getNext getPrev getSize getText getType getXML isRecord join JSDate length pop push setType setValue shift toArray unshift

Description Executes a method defined on the object. Synonymous with the doRemove method, this method simply has a more intuitive name. Inserts an object into the database. Removes an object from the database. Inserts a record if it is new and updates the record if it already exists. Makes a query. It no longer requires that the first argument be the name of the table if the object is constructed with the name of the table. Updates the database. Moves to the first record if the object represents a result set. Moves to the last record if the object represents a result set. Moves to the next record if the object represents a result set. Moves to the previous record if the object represents a result set. Returns the size of the object. Returns a text representation of the object. Returns the object type. Returns an XML representation of the object. Checks whether an object represents a current table and has a record. Returns a string of all the entries in the array. Returns a JavaScript Date object. Returns the length of the object. Removes an item from an array. Adds an item to an array. Sets the object type. Sets the object to a given value. Returns a string of all the entries in the array. Converts an object to a JavaScript array. Returns a string of all the entries in the array.

Example var q = new SCDatum("contacts"); if ((q.doSelect('contact.name # "B"')) == RC_SUCCESS) { print (q.getText()); } else { print("Return code is: " + q.RCtoString); }

SCFileThe SCFile JavaScript object is unique to ServiceCenter. When called with no parameters, the SCFile() constructor, new SCFile()

31

creates an empty SCFile object. When called with an object parameter, the SCFile() constructor, new SCFile(object) creates an SCFile object containing the specified record, structure, or array. Always enclose table names and arrays in quotation marks. This object's methods use the ServiceCenter-defined global return codes. The following argument is valid for this object:Argument object Data type String Description The table name, record, structure, or array you want to query or update.

No properties are defined for this object. The following methods are valid for it: Note: Detailed instructions for these methods can be found in the section JavaScript methods for the SCFile, SCDatum, and Datum objects.Method Name doAction doDelete doInsert doRemove doSave doSelect doUpdate getFirst getLast getNext getPrev getSize getText getType getXML isRecord join JSDate length pop push setType setValue shift Description Executes a method defined on the object. Synonymous with the doRemove method, doDelete simply has a more intuitive name. Inserts an object into the database. Removes an object from the database. Inserts a new record, or updates an existing record. Makes a query. It no longer requires that the first argument be the name of the table if the object is constructed with the name of the table. Updates the database. Moves to the first record if the object represents a result set. Moves to the last record if the object represents a result set. Moves to the next record if the object represents a result set. Moves to the previous record if the object represents a result set. Returns the size of the object. Returns a text representation of the object. Returns the object type. Returns an XML representation of the object. Checks whether an object represents a current table and has a record. Returns a string of all the entries in the array. Returns a JavaScript Date object. Returns the length of the object. Removes an item from an array. Adds an item to an array. Sets the object type. Sets the object to a given value. Returns a string of all the entries in the array.

32

Method Name toArray unshift

Description Converts an object to a JavaScript array. Returns a string of all the entries in the array.

Example var q = new SCFile("contacts"); if ((q.doSelect('contact.name # "B"')) == RC_SUCCESS) { print (q.getText()); } else { print("Return code is: " + q.RCtoString); }

XMLThe XML() constructor, new XML(), creates an empty XML object where you can store and manipulate XML documents. This object's methods do not use the ServiceCenter-defined global return codes. The XML JavaScript object is unique to ServiceCenter. No properties are defined for the method, and it accepts no arguments. The following methods are valid for this object. Note: Detailed instructions for these methods can be found in the section JavaScript methods for the XML object.Method Name addAttribute addElement appendNode createNode getAttributeNode getAttributeValue getDocumentElement getFirstAttribute getFirstChildElement getName getNextAttribute getNextSiblingElement getNodeName getNodeType getNodeValue getParentNode getPrefix getQualifiedName Description Inserts an XML attribute and attribute value into the current element. Inserts an XML element as a child of the current element. Inserts an XML node into an XML object. Creates an XML node from an XML object. Returns an XML object containing an attribute node. Returns the value of the target attribute. Creates an XML object containing the document element and all child elements from an XML object or XML string. Returns an XML object representing the first attribute of the current node. Returns an XML object representing the first child node of the current node. Returns a string representing the name of the current element or attribute. Returns an XML object representing the next attribute of the current node. Returns an XML object representing the next node at the same level in the Document Object Model (DOM) tree as the current node. Returns a string representing the name of the current element or attribute. Evaluates an XML object and returns an integer representing the XML Document Object Model (DOM) type of the current element or attribute. Returns a string representing the value of the current element. Returns an XML object representing the parent node of the current node. Returns a string representing the namespace value of the current element or attribute. Returns a string representing the name of the current element or attribute including any namespace value.

33

Method Name getText getValue importNode isDocumentElement setAttributeValue setContent setNodeValue setText setValue toXMLString

Description Returns a string representing the value of the current element. Returns a string representing the value of the current element. Copies an XML node from one XML document to another. Returns true if the current element is the Document Object Model (DOM) document element. Adds or updates an attribute value. Creates an XML document from a string or file. Adds or updates the value of the current element. Adds or updates the value of the current element. Adds or updates the value of the current element. Converts an XML object into a valid XML string.

Example /* Instantiate an empty XML object */ var xmlObj = new XML(); /* Instantiate a variable containing the path to an XML file */ var xmlFile = "C:\\myxmldoc.xml"; /* Use setContent to make the XML object read and parse the XML file * If the setContent method fails, print an error message */ if ( ! xmlObj.setContent( xmlFile, true ) ) { print( "setContent failed. Unable to parse xml: " + xmlFile ); }

XMLDateThe XMLDate JavaScript object is unique to ServiceCenter. It has no arguments, and the XMLDate() constructor, new XMLDate() creates an empty XMLDate object. When used with a DateObject argument, the XMLDate() constructor, new XMLDate(DateObject) converts a JavaScript date object to an XMLDate object. When used with an ISO8601DateTimeOrDurationString argument, the XMLDate() constructor, new XMLDate(ISO8601DateTimeOrDurationString) converts an XML schema date object to an XMLDate object. When used with a DateTimeDatum argument, the XMLDate() constructor, new XMLDate(DateTimeDatum) converts a ServiceCenter date object to an XMLDate object. This object's methods use the ServiceCenter-defined global return codes. The following arguments are valid for this object:

34

Argument DateObject ISO8601DateTimeOrDurationString DateTimeDatum

Data type JavaScript date object XML schema date ServiceCenter Datum object

Description Passes a JavaScript date object to the XMLDate constructor. Passes an XML schema date, time, datetime, or duration string to the XMLDate constructor. Passes a ServiceCenter datum object formatted as a TIME type to the XMLDate constructor.

Note: Some of the JavaScript date object times / days start with 0 instead of 1; or the year starts with 1900. For example, using the getMonth, getDate and getYear methods, December 31st 2005 would be represented as 11-31-105.Value Seconds and minutes Hours Day Date Months Year Integer 0 through 59 0 through 23 0 through 6 (day of the week) 1 through 31 (day of the month) 0 (January) through 11 (December) Number of years since 1900

No properties are defined for the XMLDate object. The following methods are valid for it: Note: Detailed instructions for these methods can be found in the section JavaScript methods for theXMLDate object.Method Name addDuration(iso8601durationstring) getDate getDatum getGMTSCDateTimeString getISODate getISODateTimeString getISODay getISOMonth getISOTime getISOYear getSCDateTimeString JSDate toSCDuration Description Adds the indicated duration to the contained value in the XMLDate object. Returns a JavaScript date object (same as the JSDate method). Returns an SCDatum object Returns the Greenwich Mean Time (GMT) date time in ServiceCenter format. Returns the indicated portions of the XMLDate value. Passes a JavaScript Date object to the constructor. Returns the indicated portions of the XMLDate value. Returns the indicated portions of the XMLDate value. Returns the indicated portions of the XMLDate value. Returns the indicated portions of the XMLDate value. Returns a date time string in ServiceCenter format. Returns a Javascript date object. Converts an ISO duration string to a ServiceCenter duration.

Example /* Instantiate a new SCFile object with records of the cm3r table */ var changeRequest = new SCFile("cm3r"); /* Set the ServiceCenter fields date.entered and planned.start to today's date.

35

* The dots in ServiceCenter field names must be converted to underscores */ var theXMLDate = new XMLDate( new Date() ); var todaysDate = theXMLDate.getDatum(); changeRequest.header.date_entered = todaysDate; changeRequest.header.planned_start = todaysDate; /* Increment the value of the planned.end field to be a week later. * P is the addDuration parameter for duration * 7D is the addDuration parameter for 7 days * See the addDuration method for additional information */ theXMLDate.addDuration('P7D'); var nextWeeksDate = theXMLDate.getDatum()


Recommended