1C:Enterprise 8.3. Developer Guide. Chapter 4. 1C:Enterprise Script

1C:Enterprise 8.3. Developer Guide. Contents


1C:ENTERPRISE SCRIPT

1C:Enterprise is a flexible configurable system that can be used to solve various tasks in the area of enterprise automation. Description of specific configuration algorithms is provided in the 1C:Enterprise Designer or, more specifically, in program modules that contain texts in the 1C:Enterprise script.

4.1. BRIEF DESCRIPTION AND PURPOSE OF 1C:ENTERPRISE SCRIPT

The 1C:Enterprise script is used to specify algorithms of application task execution (at the configuration development stage).

The 1C:Enterprise script is a domain-specific programming language specifically designed for both professional programmers and users. Thus, all 1C:Enterprise script operators can be used both in Russian and in English in the same source text. This book is dedicated to the English language; however, Russian synonyms of operators are also provided.

Although the 1C:Enterprise script is relatively simple, it has some object-oriented features, e.g., access rules for properties and methods of special data types (documents, catalogs, etc.) which resemble properties and methods of objects used in other object-oriented languages. However, you cannot define special data types using 1C:Enterprise script tools. You should use visual mode instead.

Variable types in the 1C:Enterprise script are not fixed, i.e. type of variable depends on its value. You do not need to declare variables explicitly. You can declare a variable indirectly by using it in the left part of an assignment operator. You can also declare variables directly using specific operators. You can use arrays, structures, maps and other universal collections of values.

4.2. SOURCE TEXT FORMAT IN PROGRAM MODULES

4.2.1.             What is a Program Module?

Program modules in 1C:Enterprise configuration are not independent programs in the usual sense, since they are only a part of the entire configuration. A program module is a text in the 1C:Enterprise script that contains procedure and function codes with the required algorithms called by the system when needed. Therefore, program modules have no formal borders of description like: "Begin Module" – "End Module".

The Designer shows location of specific program modules in configuration points that require description of specific functioning algorithms. These algorithms should have the form of procedures or functions called by the system in certain predefined situations (e.g., when the user clicks a button in a dialog box).

Each individual program module is interpreted by the system as a whole; therefore, all procedures and functions of a program module are executed in a single context.

4.2.2. Program Module Execution Context

Each program module is related to the rest of the configuration. This relationship is referred to as module execution context.

There are two types of context:

„ global context

„ local context of specific module execution

4.2.2.1. Global Context

The global context is formed by:

„ values of global context properties and methods

„ system enumerations and system sets of values (e.g., DialogReturnCode and Chars)

The global context is visible to all program modules and acts as a source for the common language environment of the configuration.

4.2.2.2. Local Context

The local context of a module is based on a specific task configuration point which uses the program module. The local context is only visible to the specific program module. It determines a set of objects accessible to the module along with their methods and properties.

4.2.3. Types of Program Modules

The 1C:Enterprise system has several types of program modules. Modules differ by location and available context.

4.2.3.1. Managed Application Module

Managed application module runs automatically when a configuration is loaded during 1C:Enterprise startup in the following modes:

„ thin client

„ web client

„ thick client in the managed application mode

The managed application module is used for processing tasks related to the end user session (primarily for processing session start and end events). The managed application module is inaccessible to procedures working on the server. We recommend using it to implement event handlers only.

Procedures and functions of the managed application module, along with its variables that have the Export keyword in their titles, can be accessed:

„ in non-global common client modules

„ in client procedures and functions of a command module

„ in client procedures and functions of a managed form module

The context of the managed application module makes the following accessible:

„ part of the global context that can be executed in a managed application

„ exported procedures and functions of any common client modules

„ exported procedures and functions of non-global common server modules with the Server call property set

4.2.3.2. External Connection Module

Similar to the application module, the external connection module is located in the root section of the configuration. It contains event handling procedures initialized when the system starts up and closes down in the external connection (CÎÌ-connection) mode.

You can use an external connection module to declare variables as well as declare and describe procedures and functions that are accessible to an external application.

1C:Enterprise objects accessible to external objects via COM-connection:

„ exported variables and procedures/functions of the external connection module „ exported variables and procedures/functions of shared modules:

     including and excluding entire modules by setting common module properties

including and excluding fragments of common modules with preprocessor instructions

„ 1C:Enterprise global context:

     except for the objects that are tightly linked with the client application

(TextDocument, SpreadsheetDocument)

The module is available only in an external connection session.

User interface is completely unavailable in this mode.

4.2.3.3. Session Module

Session module runs automatically when the configuration is loaded during 1C:Enterprise startup.

The session module is used to initialize session parameters and process sessionrelated actions. This common module is always executed in privileged mode at the 1C:Enterprise server.

Session parameters are set in the SessionParametersSetting() event handler.

The session module is executed before the managed application module (external connection module).

The session module can only contain definitions of procedures and functions. It can use procedures from common modules of the configuration and cannot contain exported procedures or functions.

4.2.3.4. Common Modules

Common modules reside in a separate branch of the metadata tree. The main purpose of common modules is to contain common configuration algorithms accessible from different modules. Common modules do not have a variable declaration area and main program area, i.e. they only contain procedural and functional areas (see section "Program Module Structure").

You can declare and describe procedures and functions which will be available to all configuration modules in any common module.

For details on common modules see page 1-174.

4.2.3.5. Application Object Modules

The set of application objects has its own modules. These objects include:

„ constant value managers

„ catalogs

„ documents

„ reports

„ data processors

„ charts of characteristic types

„ charts of accounts

„ charts of calculation types

„ exchange plans

„ business processes

„ tasks

„ registers

Modules reside in the configuration branches that contain the objects. They represent object properties. Each object has its own individual module. These modules can be used to declare variables, procedures and functions that will extend the object context and will be available for working with the object externally using the 1C:Enterprise script.

The context of the application object module grants access to attributes, tabular sections, methods and events of an object.

4.2.3.6. Object Manager Modules

Each application object has a manager that manages this object as a configuration object. Using this manager, you can create objects and work with forms and templates. The manager module allows you to extend the managers' functionality by creating procedures and functions using the 1C: Enterprise script. In fact, this enables you to define methods for a configuration object (e.g., a catalog) that refer to the configuration object in general, rather than to a specific database object instance.

The manager module's context consists of:

„ Properties and methods of the global context;

„ Export procedures and functions of global common modules, if these modules are compiled on the server;

„ Export procedures and functions of non-global common modules, if these modules are compiled on the server; „ The local context of the module.

The manager module cannot have variables or a module body.

If the manager module's procedures and functions are declared as exported, they are accessible through the object's manager.

Look at a sample function description in the Contractors catalog manager module:

Function  GetReceivablesList() Export
…
EndFunction

To call this function from the application code, use the following:

Receivables = Catalog.Contractors.GetReceivablesList();

4.2.3.7. Form Modules

These modules are a part of configuration forms (see page 1-361). Each form has its own module. You can use these modules to declare variables, procedures and functions that will extend form context and will be available for working with the form externally using the 1C:Enterprise script.

The form context is formed by:

„ local context of the form module and attributes of the form that owns the module;

„ properties and methods of the ManagedForm object in the 1C:Enterprise script;

„ properties and methods of the form extension defined by the type of object that has its data stored in the main form attribute;

„ global context, including non-global common modules and exported functions and procedures of global common modules. It's important to match the procedure description in the form module (&AtClient, &AtServer, etc.) and the properties set for the common module (Client (managed application), Server, etc.);

„ exported variables, procedures and functions of the managed application module.

4.2.3.8. Command Modules

Command module describes actions the system performs when a command is called in the 1C:Enterprise script. The command module can only contain descriptions of functions and procedures. It cannot have variables or a module body.

The CommandProcessing() handler should always be preceded by the &AtClient preprocessor instruction, since this is where the command execution starts. Context of client procedures in the command module is formed by the following:

„ global context, including non-global common modules and exported functions and procedures of global common modules. It's important to match the procedure description in the form module (&AtClient, &AtServer, etc.) and the properties set for the common module (Client (managed application), Server, etc.);

„ local context of the command module.

Context of server procedures in the command module is formed by the following:

„ properties and methods of the global context;

„ export procedures and functions of global common modules if these modules are compiled on the server;

„ non-global common modules if these modules are compiled on the server

(export methods of the modules are also available); „ server methods of the command module.

In the command module, you can describe methods using the Export keyword. However, you cannot use them outside the module. You cannot access commands and accordingly their context from the 1C:Enterprise script.

4.2.4. Program Module Format

Program modules consist of the following areas:

„ variable declaration area

„ procedure and function area

„ main program area

Any of these areas may be missing in a particular module.

Variable declaration area occupies space from the beginning of the module text down to the first Procedure or Function operator or any executable operator. This area may contain only variable declaration operators Var.

The procedure and function area occupies space from the first Procedure or Function operator to any executable operator outside this area.

The main program area occupies space from the first executable operator outside the last procedure and function area to the end of the module. This area may contain only executable operators. The main program area is executed during module initialization. The main program area generally contains operators that initialize variables using specific values that should be passed before the first call of any procedure or function in the module.

Source text of program modules may contain operators and comments.

4.2.4.1. Comments

You can use comments to make various notes regarding module work. In programming, a good practice is providing a detailed comment with algorithm description in the source code. In execution mode comments are ignored. In program module text a comment begins with "//" characters and ends at the end of a string. You can start a comment at the beginning of a string or write it after an operator in the same string. You cannot add an operator after the comment in the same string; you have to finish the comment at the end of the string.

A  = B; // This is a comment
//  This is also a comment

4.2.4.2. Operator Format

All operators, except the assignment operator (A = Â;) and syntactic constructs of the 1C:Enterprise script (e.g., For, While, If), look like standard procedure calls. Use semicolons to separate operators. End of string does not mean end of operator, i.e. operators may freely move over several strings and continue in another string.

You can place any number of operators in a string if you separate them with semicolons.

There are two categories of operators in program modules: variable declaration operators and executable operators.

Variable declaration operators create variable names which are used by executable operators.

Any executable operator may have a label that can be used by the GoTo operator.

Generally, language operator format looks like the following:

~label:Operator[(parameters)] [AddKeyWord];

Labels are special identifiers that begin with a tilde character and consist of a sequence of letters, digits and underscore characters. To mark an operator, you should put a label before it followed with a colon.

~label:A=Â;

4.2.4.3. Names of Variables, Procedures and Functions

Variable, procedure and function names may consist of any sequence of letters, digits and underscore characters beginning with a letter or an underscore character. New names cannot be the same as reserved words or names of properties that are directly available in the current context. Variable, procedure and function names are not case sensitive.

4.2.4.4. Program Module Script

The 1C:Enterprise script is bilingual. Almost all reserved words as well as names of value types, properties, methods and events have two names: one in Russian and another in English. The only exception is words that cannot be translated into Russian adequately. You can use both Russian and English names in the same module text without any limitations.

4.2.4.5. Case Sensitivity of Program Module Text

Names of variables, properties, methods, procedures, functions and 1C:Enterprise script functions are not case sensitive.

4.2.4.6. Reserved Words

The following keywords are reserved and cannot be used as names for variables, configuration object attributes and declared procedures and functions:

„ If

„ Then

„ ElseIf

„ Else

„ EndIf

„ For

„ Each

„ In „ To

„ While

„ Do

„ EndDo

„ Procedure

„ Function

„ EndProcedure

„ EndFunction

„ Var

„ Goto

„ Return

„ Continue

„ Break

„ And „ Or

„ Not

„ Try

„ Except „ Raise

„ EndTry

„ New

„ Execute

NOTE

Keyword names are not case sensitive.

4.2.5. Special Characters Used in Source Text

Character

Description

//

Two slashes indicate a comment. All text between this character and the end of the string is considered a comment

|

It is only used in string constants and indicates that this string continues the previous string (line break)

~

Start of operator label

Character

Description

:

End of operator label

;

Character separating operators

( )

Round brackets contain a list of parameters for methods, procedures, functions and/or wizards.

They can also be used in 1C:Enterprise script expressions

[ ]

Square brackets can be used to call object properties based on property name string presentation.

You can also call collection items by index or another parameter

,

It separates parameters in a list of parameters for methods, procedures, functions and/ or wizards

" "

It is used on both sides of string literals

' '

It is used on both sides of date literals

.

Decimal point in numeric literals.

A separator used to call properties and methods of 1C:Enterprise script objects

+

Addition operation.

Operation of string concatenation

-

Subtraction operation

*

Multiplication operation

/

Division operation

%

It retrieves a remainder in division. Fractional values are permitted for a dividend and a divisor

> 

Greater logical operation

>=

Greater or equal to logical operation

< 

Less logical operation

<=

Less or equal to logical operation

=

Assignment operation

Equal to logical operation

<> 

Not equal to logical operation

4.3. PRIMITIVE DATA TYPES

The 1C:Enterprise script supports a set of primitive data types. You can use literal constants for most primitive data types in module text, i.e. directly specify values of a certain type in the module.

//  Example of using String type literal constant
A  = "My String";

//  Example of using Boolean type literal constant
B  = True;

//  Example of using Number type literal constant
  = 12345.6789;

NULL

Description:

Values of this type are used only to specify a missing value for a database, e.g., for joining tables.

Literal constants:

NULL

Boolean

Description:

Values of this type may have two values – True and False specified by corresponding literal constants. Values of this type result from evaluation of logical expressions.

Note:

Comparison operations of the 1C:Enterprise script use logical expressions. It means that you do not have to write the following in a comparison expression:

If  MyVariable = True Then

EndIf;

You can write the following:

If  MyVariable Then

EndIf;

Literal constants:

„ True

„ False

Date

Description:

Values of this type contain date (AD, from January 01, 0001) and time with accuracy up to one second.

Literal constants:

A string of digits enclosed in single quotation marks with a format of 'YYYYMMDDhhmmss', where:

„ YYYY – four digits of a year (including age and millennium)

„ MM – two digits of a month

„ DD – two digits of a date

„ hh – two digits of an hour (in 24-hour format)

„ mm – two digits of a minute

„ ss – two digits of a second

In the 1C:Enterprise script, Date literal constants should contain year, month and day values. To specify the initial date, use '00010101'. You can omit the last characters (seconds, minutes, hours, etc.) in Date type literal constants. If not specified, these values are set to 0 (for time) and 1 (for date).

Various separators are allowed in date literal constants.

Example:

Date('2008.03.23 10:45:23') = "23.03.2008 10:45:23"

Number

Description:

Any decimal number can be represented by numerical type. For numerical types, the main arithmetic operations are defined: addition, subtraction, multiplication and division.

IMPORTANT!

A number cannot have more than 32 digits.

Literal constants:

A set of digits written directly in the source code, with the following syntax:

[+|-]{0|1|2|3|4|5|6|7|8|9}[.{0|1|2|3|4|5|6|7|8|9}]

A period is used to separate the whole and fractional parts.

Example:

A  = 15;
B  = -968.612;

String

Description:

Values of this type contain a string of arbitrary length in Unicode format.

Literal constants:

String type literal constants are sets of values in double quotation marks. To use the " character (double quotation mark) in a string, use two double quotes in a row ("").

Besides, you can use string constants that occupy several lines. To specify a multi-line constant in the source text, you can use one of two methods:

„ There should be no other characters except spaces, line breaks and comment lines between fragments that represent separate lines of a multi-line string.

„ Each part of a multi-line string does not end with a quotation mark, but all lines end in a | character (vertical line). In this case comments are allowed if the string starts with the comment sign, //.

Example:

//  Sample string
MyString  = "This is a correct string";

//  Sample multi-line string 1
MyMultiLineString  = "This
|is a correct
|multi-line
|string";

//  Sample multi-line string 2
MyMultiLineString  = "This is also" // This is a comment
"a correct"
"multi-line"
"string";

//  Sample string 3 with quotation marks
CompanyName  = """Cornflower""Inc";

Displaying or printing the CompanyName line (sample string 3) results in the following:

"Cornflower" Inc

Undefined

Description:

This type of value is used when you need an empty value that does not belong to any other type. For example, this is the initial value received by composite type attributes. There is only one possible value for this type specified by a literal value.

Literal constants: Undefined

Type

Description:

Values of this type are used to identify value types. This is required for type definition and comparison. This type has no literal constants and is returned by TypeOf and Type functions of the 1C:Enterprise script (see below).

4.4. ASSIGNMENT OPERATOR

Assignment Operator (=)

Description:

The assignment operator (= character) indicates assignment of <Source> value to <Assignment> variable.

Syntax:

<Assignment> = <Source>; Parameters:

<Assignment>

Any writable variable or property of 1C:Enterprise script object may act as an assignment.

<Source>

An expression with a value that needs to be assigned.

Example:

A  = Â;
Page1  = "777";
DocumentDate  = '20020717';

4.5. SCRIPT EXPRESSIONS

An expression is a mathematical, logical or string formula consisting of operations that calculate a value. Mathematical and logical expressions may be located to the right of the equality sign in assignment operators or may be a parameter of procedures or functions. Logical expressions can also be conditions in If, While and For control directives. Expressions consist of constants, variables and functions linked with symbols of logical and/or arithmetic operations.

4.5.1. Arithmetic Operations

The following types of arithmetic operations are defined in the 1C:Enterprise script:

Name

Expression

Addition

(Op1 + Op2)

Subtraction

(Op1 – Op2)

Multiplication

(Op1 * Op2)

Division

(Op1 / Op2)

Remainder in Division

(Op1 % Op2)

Unary minus

(-Op1)

Arithmetic operations have one or two operands which determine operation semantics. Semantics of an operation depend on the first operand. If the second operand type does not match the required one, the value is converted into the required type in compliance with type conversion rules. If the type of the first operand does not match any of the valid types, depending on situation, types may be converted or an execution error may occur.

Operation

Description of Action

Addition   is defined for               the following operand types

Number + Number

Date + Number (number of seconds is added to the date)

Subtraction is defined for the following operand types

Number - Number

Date - Number (number of seconds is subtracted from the date)

Date - Date (result is the difference between two dates in seconds)

Multiplication

Number * Number

Division

Number / Number

Remainder in Division

Number % Number

4.5.2. Concatenation Operation

You can use the concatenation operation (+) to attach one string to another. Length of the resulting string equals the total length of the strings attached. If the data type of the second or subsequent operands does not correspond to the string type, their value is converted to the string type in accordance with type conversion rules.

NAME = Last Name + " " + Name + " " + Middle Name;

4.5.3. Logical Operations

A logical operation compares operands and creates a Boolean value: True or False. There are two types of logical operations: comparison operations and Boolean operations. You can use comparison operations to compare two values. Boolean operations are used for Boolean values and implement Boolean algebra. Boolean operation characters may combine forming compound operations.

Comparison operations:

The following comparison operations are defined in the 1C:Enterprise script:

Operation

Operation Expression

Greater

Op1 > Op2

Greater or Equal

Op1 >= Op2

Equal

Op1 = Op2

Not Equal

Op1 <> Op2

Less

Op1 < Op2

Less or Equal

Op1 <= Op2

Comparison operations are defined for the following operand types:

Operation

Operation Expression

Greater

Number > Number

String > String Date > Date

Greater or Equal

Number >= Number

String >= String Date >= Date

Less

Number < Number

String < String Date < Date

Less or Equal

Number <= Number

String <= String Date <= Date

Equal

Any type = Any type

Not Equal

Any type <> Any type

Boolean operations:

The following types of Boolean operations are defined in the 1C:Enterprise script:

AND

Conjunction (Boolean AND)

OR

Disjunction (Boolean OR)

NOT

Logical negation (Boolean negation NOT)

Logical expressions are calculated from left to right. Use round brackets to avoid ambiguity and manage operand sequence.

Logical operation seniority levels:

Level 1

operands in round brackets

Level 2

NOT

Level 3

AND

Level 4

OR

NOTE

When a logical expression is calculated, only its required parts are used. For example, if Price <= 0 in the expression (Price > 0) AND CheckSum(), then CheckSum() function is not called.

4.6. OPERATORS AND SYNTACTIC CONSTRUCTS

? (Calculate Conditional Expression)

Description:

You can use it to calculate one of two specified expressions depending on the logical expression result.

Syntax:

?(<Logical expression>, <Expression 1>, <Expression 2>) Parameters:

<Logical expression>

The evaluated logical expression that defines which of the resulting expressions is calculated. If the evaluation result is True, then <Expression 1> is calculated. If the evaluation result is False, then <Expression 2> is calculated.

<Expression 1>

The resulting expression that is calculated if the logical expression is evaluated as True.

<Expression 2>

The resulting expression that is calculated if the logical expression is evaluated as False.

Return value:

Calculation result for one of the resulting expressions.

Example:

Status  = ?(GetDiscount() > 10,"Preferred Customer", "Regular  Customer");
Warning(Status);

Raise

Description:

This operator form is used to raise a new exception.

Syntax:

Raise <Expression> Parameters:

<Expression>

The expression is evaluated to a string that is used as exception description.

Example:

Raise "Cannot post the document";

See also:

Description of Try operator.

Execute

Description:

This operator is used to execute a code fragment passed as a string value.

IMPORTANT!

It is not recommended to use this method to implement a significant portion of functionality in application solutions.

NOTE

Executable code should not contain separate procedures or functions since the code itself is executed as a procedure or a function which uses this operator.

The code also should not contain explicit declaration of variables.

Syntax:

Execute(<String>) Parameters:

<String>

A string containing executable code text.

Example:

//  Displays the current date in the message window
Execute("Message(CurrentDate())");

AddHandler

Description:

It adds an event handler.

When adding an event handler a check is performed to make sure that the number of event parameters matches the number of parameters for the method assigned as a handler.

Syntax:

AddHandler <Event>, <EventHandler>; Parameters:

<Event>

The event to which the handler is added.

The event is set in the <Expression>.<EventName> form where:

„ <Expression> is any expression in the 1C:Enterprise script. It should result in an object with an event to which the handler is added.

„ <EventName> is the event ID (name).

<EventHandler>

A procedure or function that acts as event handler.

The event handler can be a method of 1C:Enterprise script object. Then <EventHandler> is set as <Expression>.<HandlerName> where:

„ <Expression> is any expression in the 1C:Enterprise script that is evaluated to the object whose method serves as the event handler.

„ <HandlerName> is the event handler method name.

A procedure or function within the scope can be also set as the event handler. In this case the event handler is specified using the name of this procedure or function.

You can subscribe to events that have the same name (in COM objects) and a different number of parameters. To do so, you should create multiple handlers in the 1C:Enterprise script (each with a unique name and the required number of parameters); then the subscription mechanism selects a handler matching a particular subscription.

Example:

DataProcessor  = DataProcessors.DocumentCheck.Create();
Invoice  = Documents.Invoice.CreateDocument();
AddHandler  Invoice.OnWrite, DataProcessor.OnWriteDocument;

msword  = New COMObject("Word.Application");
AddHandler  msword.DocumentChange, OnDocumentChange

Procedure  OnDocumentChange()
Message("Document is changed");
EndProcedure

Example with varying parameters:

//  Handler with no parameters
Procedure  EventProcessing()
EndProcedure

//  Handler with a single parameter
Procedure  EventProcessing2(Parameter)
EndProcedure

//  The object can generate events both with
//  and without parameters
Object  = New COMObject("Test.Events");
AddHandler  Object.TestEvent, EventProcessing
AddHandler  Object.TestEvent, EventProcessing2

For

Description:

For operator is used for loop-like repetition of operators within DoEndDo clause. Before the loop, <Expression 1> value is assigned to <Variable Name> variable. <Variable Name> value automatically increments at each iteration. Incremental step equals 1 for each loop. The loop is executed while <Variable Name> is less or equal to <Expression 2> value. The loop condition is always checked at the beginning before the loop is executed.

Syntax:

For <Variable Name> = <Expression 1> To <Expression 2> Do

// Operators

[Break;]

// Operators

[Continue;]

// Operators EndDo;

Parameters:

<Variable Name>

An ID for a variable (loop counter) whose value is auto-incremented by 1 on each iteration. It is the so-called loop counter.

<Expression 1>

A numeric expression that sets the initial value assigned to the loop counter at the first iteration.

To

Syntax link for the <Expression 2> parameter.

<Expression 2>

Maximum value of the loop counter. When the <Variable Name> variable becomes greater than <Expression 2>, execution of For operator is stopped.

Do

Operators after the Do keyword are executed while the <Variable Name> value is less or equal to <Expression 2>.

// Operators

An executable operator or a sequence of such operators.

Break

It breaks loop execution at any point. After this operator is executed, control is passed to the operator following the EndDo keyword.

Continue

It passes control immediately to the beginning of the loop where loop conditions are evaluated and checked. Operators following this operator in the loop body are skipped in this iteration.

EndDo

Keyword that denotes the end of a loop operator structure.

Example:

//  Cycling through days in the current month
LastMonthDay  = Day(MonthEnd(CurrentDate()));
For  CurDay = 1 To LastMonthDay Do
State("Processing day: "+ CurDay);

// Operators for processing the next day of the month
. . .

EndDo;

For each

Description:

For each operator is used for cycling through a collection of values. Each iteration returns a new collection item. The cycle is running until all collection items are processed. You can use the Break operator to stop the cycle at any time.

Syntax:

For each <Variable Name 1> In <Variable Name 2> Do

// Operators

[Break;]

// Operators

[Continue;]

// Operators EndDo;

Parameters:

<Variable Name 1>

Value of the next collection item is assigned to this variable on each cycle.

In

Syntax link for <Variable Name 2>.

<Variable Name 2>

A variable or an expression that represents a collection. Items of this collection are assigned to <Variable Name 1>.

Do

Operators following the Do keyword are executed until the cycle goes through all collection items.

// Operators

An executable operator or a sequence of such operators.

Break

It breaks loop execution at any point. After this operator is executed, control is passed to the operator following the EndDo keyword.

Continue

It passes control immediately to the beginning of the loop where loop conditions are evaluated and checked. Operators following this operator in the loop body are skipped in this iteration.

EndDo

Keyword that denotes the end of a loop operator structure.

Example:

//  Cycling through lines of a tabular section of the document.
Document  = Documents.Invoice.FindByCode(12345);

//  Check to see whether the required document can be found
If  Not Document.IsEmpty() Then
For each ContentString from Document.Content Do
State("String: " +  Document.Content.Index(ContentString)+1);
// Operators for processing the next string of the tabular section
...
EndDo;
EndIf;

If

Description:

If operator controls program execution based on a result of one or more logical expressions. The operator may contain any number of operator groups within ElseIf – Then clauses.

Syntax:

If <Logical Expression> Then

// Operators

[ElseIf <Logical Expression> Then]

// Operators

[Else]

// Operators EndIf;

Parameters:

<Logical Expression>

A logical expression.

Then

Operators following Then are executed if the result of the logical expression is True.

// Operators

An executable operator or a sequence of such operators.

ElseIf

A logical expression after ElseIf keyword is evaluated only when all conditions in If and all previous ElseIf clauses are False. Operators following ElseIfThen are executed only when the result of the logical expression in this ElseIf is True.

Else

Operators following the Else keyword are executed if all previous If and ElseIf conditions are False.

EndIf

Keyword that ends a conditional execution structure.

Example:

If  WeekDay(CurrentDate()) = 6 Then
Message("It’s Saturday.");
ElseIf  WeekDay(CurrentDate()) = 7 Then
Message("It’s Sunday.");
Else
Message("It’s a working day.");
EndIf;

New

Description:

You can use this operator to create a value of specified type. This operator can be used only for types that allow creation of new values. You should use functional form of the New operator (version 2) for application objects, since module check in the Designer has no types defined for application objects.

Syntax (version 1):

New <Type name>[(<Param 1>, ..., <Param N>)] Parameters:

Type name

It specifies the type name for the new value.

<Param 1>, ..., <Param N>

The type name can be followed by parameters in brackets if they are defined in wizards for this type. A valid number of parameters and their purpose are specified in object wizard descriptions.

Example:

//  Creating a three-item array.
Array  = New Array(3);

Syntax (version 2):

New (<Type>[, <Wizard parameters>]) Parameters:

Type

Type name or Type value.

<Wizard parameters>

Array of wizard parameters.

Example:

ValueType  = Type("StringQualifiers");
Parameters  = New Array(2);
Parameters[0]  = 20;
Parameters[1]  = AllowedLength.Variable;
StrQualif  = New(ValueType, Parameters);

Goto

Description:

Unconditional control transfer to another operator of the program. It transfers control from one operator to another.

The scope of this operator is limited by the program module, procedure or function; this operator cannot pass control outside the program module, procedure or function.

NOTE 1

Label in this operator should not lead to Procedure or Function operator.

NOTE 2

The operator of unconditional transfer cannot be used to pass control to operators within the following clauses from outside: WhileEndDo, ForEndDo, For eachEndDo, IfEndIf, TryExceptEndTry.

Syntax:

Goto <Label>; Example:

Goto  ~Label1;
...
~  Label1: Message("Transferred to label.");

Var

Description:

This operator is used for explicit variable declaration.

Syntax:

Var <Variable name 1> [Export] [, <Variable name 2>, …]; Parameters:

<Variable name 1>[, <Variable name 2>, …]

It sets a name or names of declared variables.

Export

An optional keyword. It means that this variable is exposed when other modules access context of this module. This keyword should be specified individually for each declared variable. It is meaningless in declarations of variables for standalone procedures or functions.

Example:

//  A single variable declaration example
Var  A Export;
Var  B;

//  Example of declaring multiple variables with one operator
Var  A, B Export;

Implicit variable declaration:

It is not mandatory to declare variables explicitly. A variable is declared implicitly when it first appears in the left part of an assignment operator. Variable type depends on the type of its value. Expressions cannot contain variables that have not been declared, either explicitly or implicitly.

Variable scope:

The scope of variables depends on the location of their declarations in the configuration. You can declare variables in three scopes:

„ Variable declaration area of the managed application program module. These are global variables.

„ Variable declaration area in a module. These are module variables.

„ Procedure or function. These are local variables.

Global variables declared with the Export keyword can be used in executable operators, expressions, in any procedure and function of any client program module in the configuration.

Module variables can be used by executable operators, expressions, any procedure or function of the program module where they are declared. If they are declared with the Export keyword, they can be accessed from other modules through context of the module where they are declared.

Local variables are accessible only within a procedure or function where they are declared.

If a variable is defined as global, it can be accessed by any procedure or function of any client program module within the configuration. If a variable is defined within a procedure or function, it is visible only in this procedure or function.

Therefore, if two variables with the same name are used in two different procedures in a module and this name is not defined as a global variable, they are two different local variables used for procedures. If a variable is defined as global, any use of its name calls it.

The only way to create a local variable for a procedure that would have the same name as a global variable is declaring it explicitly using the Var operator.

While

Description:

While operator is used for cyclic repetition of operators within DoEndDo clause. The cycle is running while the logical expression is True. The loop condition is always checked at the beginning before the loop is executed.

Syntax:

While <Logical expression> Do

// Operators

[Break;]

// Operators

[Continue;]

// Operators EndDo; Parameters:

<Logical expression>

A logical expression.

Do

Operators following Do are executed while the result of a logical expression is True.

// Operators

An executable operator or a sequence of such operators.

Break

It breaks loop execution at any point. After this operator is executed, control is passed to the operator following the EndDo keyword.

Continue

It passes control immediately to the beginning of the loop where loop conditions are evaluated and checked. Operators following this operator in the loop body are skipped in this iteration.

EndDo

Keyword that denotes the end of a loop operator structure.

Example:

SelectionDoc  = Documents.Invoice.Select();

//  Cycle through all documents
While  SelectionDoc.Next() Do

// Display the Document in the status bar
State("Processing document No." + SelectionDoc.Number);

// Operators for document processing

EndDo;

Try

Description:

Try operator manages program execution based on error (exceptional) situations and defines how these situations are handled.

Exceptions or error situations are module runtime errors. Custom exceptions are not supported.

If a runtime error occurs while executing a sequence of operators, execution of the operator causing the error stops, and control is passed to the first operator of the exception operator sequence. Control is passed to the operator even if the error was caused by an operator within a procedure or function called from a Try operator. If the error occurred in a procedure or function, it is terminated, and its local variables are destroyed. It applies to any level of nested calls. After the exception operator sequence is executed, control is passed to the operator following the EndTry keyword. If the sequence of Try operators is executed without errors, then the exception operator sequence is skipped, and control is passed to the operator following the EndTry keyword.

TryExceptEndTry clauses can be nested. If an exception is raised, control is passed to the handler where a Try operator caused the error. If Raise operator is executed in the exception operator sequence of this handler, control is transferred to a higher level exception handler and so on. If there is no exception handler at a higher level, the exception is handled by the system, and the program module is terminated.

Built-in ErrorDescription() and ErrorInfo() functions can be useful in troubleshooting (see description of 1C:Enterprise script functions).

Syntax:

Try

// Try operators

Except

// Exception operators

[Raise;]

// Exception operators

EndTry;

Parameters:

// Try operators

An executable operator or a sequence of such operators.

Except

Operators following the Except keyword are executed if a runtime error occurs while executing a sequence of operators.

// Exception operators

An executable operator or a sequence of operators that process an exception.

Raise

This operator allows you to raise an exception in cases when it is required to shut down a module and generate a runtime error, even though the exception has been processed. It is only allowed within the ExceptEndTry clause.

This operator aborts exception operators and searches for an external exception handler (for nested tries). If such an exception handler is found, control is passed to it. Otherwise the exception is handled by the system, a message about the original error is generated, and the module is terminated.

EndTry

Keyword that ends the exception handling clause.

Example:

Procedure  MakeInExcel()
Try
// Trying to call MS Excel
Table = New ComObject("Excel.Application");
Except
Warning(ErrorDescription());
Return;
EndTry;

// Report generation operators
...
EndProcedure

Procedure

Description:

Procedure keyword identifies the beginning of a source code area that can be called from any point of the program module using ProcedureName() operator with a list of parameters (use round brackets even if no parameters are passed). If an application module or a common program module contains the Export keyword in the body of procedure description, it means that this procedure is accessible from all other configuration modules.

When the Return operator is executed, the procedure ends and returns control to the point of call. If procedure text does not contain the Return operator, then an implied Return operator is executed after the last executable operator. The end of the procedure program area is identified by the EndProcedure operator.

Variables declared in the procedure body in Local Variable Declarations area are local variables and therefore they are only available in this procedure (except when they are used as parameters for calling other procedures, functions or methods).

NOTE

Procedure and EndProcedure keywords are not operators; they are operator brackets. Therefore, they should not end with a semicolon (this may cause module execution errors).

Syntax:

Procedure <ProcedureName>([[Val] <Param 1> [=<DefVal>], ...

,[Val] <Param N>[=<DefVal>]])[Export]

// Local Variable Declarations; // Operators; ...

[Return;] // Operators; ...

EndProcedure Parameters:

<ProcedureName>

It assigns a procedure name.

Val

Optional keyword which specifies that the following parameter is passed by value, i. e. changing the formal parameter value does not affect the actual parameter passed during procedure call. If this keyword is not specified, the procedure parameter is passed by reference, i. e. changing the formal parameter value in the procedure will change the actual parameter value.

<Param 1>, ..., <Param N>

Optional list of formal parameters separated by commas. Values of formal parameters should correspond to values of actual parameters passed when the procedure is called. This list defines a name for each parameter as it is used in the procedure text. The list of formal parameters can be empty.

=<DefVal>

Optional setting of default parameter value. You can place parameters with default values anywhere in the list of formal parameters (for more details see section "Passing Procedure and Function Parameters").

Export

Optional keyword specifying that this procedure is accessible from other program modules.

// Local Variable Declarations

It declares local variables that can be referenced within this procedure only (see Var operator description).

// Operators

Executable procedure operators.

Return

Optional keyword that ends the procedure and returns to the point of the program that called the procedure. This operator is not required.

EndProcedure

Required keyword that identifies the end of the source text of the procedure and ends the procedure. It returns to the point of the program that called the procedure.

Example:

Var  Glob;

//  Procedure description
Procedure  MyProcedure(Par1, Par2, Par3) Export
Glob = Glob + Par1 + Par2 + Par3;
Return;
EndProcedure

Glob  = 123;
MyProcedure(5,  6, 7); // Procedure call

RemoveHandler

Description:

It removes an event handler.

When removing an event handler a check is executed to make sure that the number of event parameters matches the number of parameters for the method assigned as handler.

Syntax:

RemoveHandler <Event>, <EventHandler>; Parameters:

<Event>

An event for which the handler is removed.

The event is set in the <Expression>.<EventName> form, where:

„ <Expression> is any expression in the 1C:Enterprise script. It should result in an object with an event for which the handler is removed.

„ <EventName> is the event ID (name).

<EventHandler>

A procedure or function that acts as the event handler.

The event handler can be a method of 1C:Enterprise script object. Then <EventHandler> is set as <Expression>.<HandlerName> where:

„ <Expression> is any expression in the 1C:Enterprise script. It should result in an object whose method is used as the event handler.

„ <HandlerName> is the method name of the event handler.

A procedure or function within the scope can be also set as the event handler. In this case the event handler is specified using the name of this procedure or function.

Example:

RemoveHandler Invoice.OnWrite, DataProcessor.OnWriteDocument;

Function

Description:

Function keyword begins an area in the source text of a function that can be initiated from any point of the program module by specifying FunctionName with a list of parameters (use round brackets, even if no parameters are passed). If an application module or common program module contains Export keyword in the body of function description, it means that this function is accessible from all other configuration modules.

Function execution should end with the Return operator. The difference between functions and procedures is that functions return a ReturnValue. EndFunction operator identifies the end of the function.

You can record any function call in the program module as a procedure call, i. e. it is allowed not to accept a return value from a function.

If the Return keyword is not included in the function body or the module string containing this keyword is not executed, the function returns an Undefined value.

Variables declared in the Local Variable Declarations area of a function body are local for this function and are accessible only in this function (except when they are used as parameters for calling other procedures, functions or methods).

NOTE

Function and EndFunction keywords are not operators; they are operator brackets. Therefore, they should not end with a semicolon (this may cause module execution errors).

Syntax:

Function <FunctionName>([[Val] <Param 1>[=<DefVal>], ... ,[Val]

<Param N>[=<DefVal>]])[Export]

// Local Variable Declarations; // Operators; ...

Return <Return value>; // Operators; ...

EndFunction Parameters:

<FunctionName>

It assigns a function name.

Val

Optional keyword specifying that the following parameter is passed by value, i.e. changing the value of the function parameter does not influence the actual parameter that is passed during function call. If this keyword is not specified, the procedure parameter is passed by reference, i. e. changing the formal parameter value in the procedure will change the actual parameter value.

<Param 1>, ..., <Param N>

Optional list of formal parameters separated by commas. Values of formal parameters should correspond to values of actual parameters passed when the function is called. This list defines a name for each parameter as it is used in the function text. The list of formal parameters can be empty.

=<DefVal>

Optional setting of default parameter value. You can place parameters with default values anywhere in the list of formal parameters (for more details see section "Passing Procedure and Function Parameters").

Export

Optional keyword specifying that this function is accessible from other program modules.

// Local Variable Declarations

It declares local variables that can be referenced in this function (see Var operator description).

// Operators

Executable function operators.

Return <Return value>

Keyword that ends the function and returns the specified value into the caller expression.

The return value can be any expression or variable that has a value containing the function call result.

EndFunction

Keyword that identifies the end of the function source text.

Example:

Var  Glob;

//  Function description
Function  MyFunction(Par1, Par2, Par3) Export
Glob = Glob + Par1 + Par2 + Par3;
Return Glob;
EndFunction

Glob  = 123;
Res  = MyFunction(5, 6, 7); // Function call

4.7.                  MAJOR TECHNIQUES AND PRACTICES

4.7.1. Calls to Object Properties

In addition to point-based calls, the 1C:Enterprise script supports calling object properties using strings with a property name and [] operator (square brackets).

Object Property ([])

Description:

You can use this construct to call object properties in a way similar to pointbased methods.

Syntax:

<Object>[<Property Name>] Parameters:

<Object>

Object with a property being called.

<Property Name>

String type. The name of the property to be called.

Example:

Cat  = Catalogs.Nomenclature.FindByCode(SoughtCode);

//  Calling catalog name using a string with the property name
A  = Cat["Name"];

//  Calling catalog name using the property name
A  = Cat.Name;

//  Both property calls are identical

4.7.2. Enhancement of Object and Form Context

When you call objects and forms from external program modules, you can call module variables, procedures and functions, just as you call properties and methods of objects and forms. You can call variables, procedures and functions declared with the Export keyword. You can also call form attributes (for forms).

Example:

//  Example of using procedure of printing documents from a document
//  journal. Assume you have several documents,
//  each of them with the Print() procedure. The document
//  journal module has the Print button that
//  calls printing procedure for the current document.
Procedure  PrintClick(Item)

// You will get the current document where the cursor is  positioned.
CurDoc = FormElements.LogList.CurrentRow;

// You will get the default form of the current document.
FormCurDoc = CurDoc.GetForm();

// Call the printing procedure located in
// the module of document form.
FormCurDoc.Print();

EndProcedure

4.7.3. Passing Procedure and Function Parameters

Procedure and function parameters are passed using two methods. One method is called passing by reference. Rather than passing a specific parameter value, it passes memory addresses (variable references) where this value is located. Any changes in a passed value in the called procedure or function will change the variable being changed in the calling method.

Another method is called passing by value. This passes a copy of the parameter value. In this case, any changes in a passed value in the called procedure or function will not change the variable being changed in the calling method.

At the same time, the procedure and function parameter passing process depends on the type of call:

„ call without transferring control between the client and the server (only on the client or only on the server);

„ call with control transfer between the client and the server. Let's look at each of the methods in greater detail.

4.7.3.1. Call without Transferring Control from the Client to the Server

If a call is executed without transferring control between the client and the server (the call is executed only on the client side or only on the server side), by default the parameters are passed by reference. In this case, a change in a formal parameter changes the corresponding actual parameter. You can use the Val modifier before a formal parameter name to specify that the parameter is to be passed by value. In this case, you can't change an actual parameter value by assigning a value to a formal parameter.

&AtClient
Procedure  MyProcedure()

A = 100;
ByRef(A);
// Variable (A) = 40, because in the body of the procedure
// the Parameter1 parameter value was changed to 40.
// Variable (A) was modified because the parameter was passed by  reference.

A = 100;
ByValue(A);
// Variable (A) = 100, although that in the body of the procedure
// the Parameter1 value parameter changed to 40.
// Variable (A) was not modified, because parameter passed by  value.

EndProcedure

&AtClient
Procedure  ByRef(Parameter1)

Parameter1 = 40;

EndProcedure

&AtClient
Procedure  ByValue(Val Parameter1)

Parameter1 = 40;

EndProcedure

However, you should note the following: if an aggregate object is passed as a parameter, you cannot assign another value to the actual parameter. But you can modify the passed object. For example, if you pass an array to a procedure by value, you can clear the array using the Clear() method, but you cannot change the parameter value in the calling procedure.

&AtClient
Procedure  MyProcedure()

Array = New Array;
Array.Add(12);
Array.Add(18);

// There are two elements in the array
ByValue(Array);

// Array is empty, but still it's an array, not Number
EndProcedure

//  Parameter is passed by value
&AtClient
Procedure  ByValue(Val Parameter)

// There are two elements in the array
Parameter.Clear();

// There are no elements in the array
// Change formal parameter
Parameter = 14;

// Only formal parameter is value changed
EndProcedure

You also need to consider the specifics of variable storage when calls are implemented:

&AtClient
Procedure  TestProcedure()

ValueA = New Array;
ValueA.Add(1);
ValueA.Add(2);
ValueB = ValueA;

// call to any variable: ValueA or ValueB raises the
// update of one and the same array

MyProcedure(ValueA, ValueB);

// After completion of the call procedure both variables (ValueA  and        //  ValueB) reference at one array.
// There are the following values in the array:
// ValueA[0] = ValueB[0] = "(A)"
// ValueA[1] = ValueB[1] = "B"

EndProcedure

&AtClient
Procedure  MyProcedure(Parameter1, Parameter2)

// Although that there are two parameters, in fact only ine array  is        //  processed

Parameter1[0] = 5;
Parameter1[1] = 6;

Parameter2[0] = "A";
Parameter2[1] = "B";

EndProcedure

In this case you should note that the assignment operation ValueB = ValueA; (in TestProcedure()) will not create a copy of the array in the ValueA variable. Both variables will refer to the same array.

Parameters are passed to MyProcedure() by reference, so if you change two formal parameters, one physical array is changed.

4.7.3.2. Call with Transferring Control from the Client to the Server

Calling procedures and functions while you are transferring control between the client and the server are characterized by the fact that, in general, such calls change the computer where the called method is executed. This happens because the client works on one computer and the server works on another. Thus we can't talk about passing parameters by reference, as a single computer can't get direct access to another computer’s memory. In the file server variant, the client and the server represent one computer, but this does not affect interaction logic. So the parameters are passed as follows in client/server interaction:

„ When control is transferred from the client to a server (and vice versa), parameter copies are always passed. When server procedure or function is called from the client, a copy of an actual parameter is created and transferred to the server side. When control is returned from the server to the client, a copy of an actual parameter (one which was used in the called procedure or function) is also created to transfer it back to the client.

„ If a formal parameter is specified with the Val modifier, the parameter value will be passed only when a procedure or function is called, but it will not be passed back when control is returned to the client.

„ If the same real value is specified for several formal parameters, a number of real value copies will be created that equals the number of formal parameters using the value.

„ If a value of the same variable is specified as formal parameters, then after control is returned from the server this variable value is set as the most proper formal parameter (without the Val modifier) that was changed in the called function.

&AtClient
Procedure  TestProcedure(Command)

ValueA = New Array;
ValueA.Add(1);
ValueA.Add(2);
ValueB = ValueA;

// Call to any variable: ValueA or ValueB raises the
// modification of one and the same array

// a copy of the array for each formal parameter is created
// during the procedure call
ServerProcedure(ValueA, ValueB);

// After completion of the call procedure:
// 1. ValueA and ValueB variables refer to different arrays
// 2. There are different values in the arrays
// ValuA[0] = 5
// ValuA[1] = 6
// ValueB[0] = "(A)"
// ValueB[1] = "B"

EndProcedure

&AtServer
Procedure  ServerProcedure(Parameter1, Parameter2)

// formal parameter at server "its" own array is created  because
// the copies are passed

Parameter1[0] = 5;
Parameter1[1] = 6;

Parameter2[0] = "A";
Parameter2[1] = "B";

// Server will return copies of Parameter1 and Parameter2  variables

EndProcedure

Remember that a copy of the value is created when parameters are passed to a server. This can help avoid hard to diagnose errors in system operation. Let us consider the following example:

&AtClient
Procedure  TestProcedure(Command)

ValueA = New Array;
ValueA.Add(1);
ValueA.Add(2);
ValueB = ValueA;
Structure = New Structure("Key1, Key2", ValueA, ValueA);
ServerProcedure(Structure);
ValueA[0] = 9;
ValueA[1] = 8;
ValueB[0] = "C";
ValueB[1] = "D";

EndProcedure

&AtServer
Procedure  ServerProcedure(Parameter1)

Parameter1.Key1[0] = "0";
Parameter1.Key1[1] = "1";
Parameter1.Key2[0] = "2";
Parameter1.Key2[1] = "3";

EndProcedure

After the TestProcedure() call is completed, the variables will have the following states:

„ The ValueA and ValueB arrays are identical and contain the value "C" in the first element and the value "D" in the second element, since the ValueB variable refers to an array of the ValueA variable, and values of these variables are not passed to the server.

„ The Structure variable will hold two arrays:

with the values "0" and "1" for array elements located in structure element with Key1 key;

with values "2" and "3" for array elements located in the structure element with the Key2 key;

such behavior is due to the fact that when the procedure is called, a copy is created not only for the parameter itself (the Structure variable), but for all the objects in this structure; two arrays that initially referred to one array with 0 and 1 element values.

4.7.3.3. General Considerations for Specifying Parameters

If you specify a default value and if this parameter is last in the list, you can omit it from the list of transferred actual parameters and should not put a comma before this parameter.

Procedure  MyProcedure(Parameter1, Parameter2 = "Default")
…
EndProcedure

//  When next call is performed,
//  Parameter1 parameter value will equal 1,
//  and Parameter2 parameter value – "Default" in procedure
//  "MyProcedure"
MyProcedure(1);

If the parameter does not have a default value, you can omit it in the list of the actual passed parameters when calling a procedure or function, but you should use a comma separator.

If you omit the parameter when calling the procedure, it is either assigned a default value (if any) or the Undefined value.

Procedure  MyProcedure(Parameter1, Parameter2, Parameter3 = "Default")
…
EndProcedure

//  When next call is performed, in procedure "MyProcedure",
//  Parameter1 parameter value will equal 1,
//  Parameter2 parameter value – Undefined,
//  and value parameter Parameter3 – "example"
MyProcedure(1,  , "example");

You still have to use round brackets if you do not pass any parameters during the method, procedure or function call (an empty parameter list). Do not pass data from the client to the server (and vice versa) and do not serialize the data with cyclic references. In this case an error will be shown and the session will be terminated.

When you pass string values from the client to the server and vice versa, remember that these values should not contain characters that are invalid according to the XML version 1.0 specification (http://www.w3.org/TR/xml/).

TIP

You can perform such validation at server side using the FindDisallo- wedXMLCharacters() function.

4.7.4. Work with Collections of Values

Some objects in the 1C:Enterprise script are collections of values. Most collections have similar methods and properties like Count(), Index(), Add(), Delete(), etc. Collection items usually act as collection properties. You can implement cycling through a collection using For eachOfDo clause. In most collections, items can be called using [<Argument>] operator (square brackets). Usually an index of collection items is passed as an argument. Collection item indexing starts from zero. It means that the index of the last item in the collection equals the total number of items in the collection less 1.

If collection items are deleted or modified in any way while the collection is cycled through, subsequent system behavior becomes undefined.

See detailed descriptions of specific objects for more information about specific collections, their properties, methods and use.

4.7.5. Use of Numbers and Indices

Some objects in the 1C:Enterprise script use numbering for their components. Such objects may include a string with numbered characters, a spreadsheet document with numbered rows and columns, etc. To call object components, you can use Numbers. Numbering always starts from 1.

To call collection items, you can use Indices. Indexing of collection items always starts from 0.

4.7.6. Work with System Enumerations

The 1C:Enterprise script uses a concept of system enumerations. These enumerations define specific sets of predefined values. System enumerations are accessed as global context properties of a name. Specific values are separated from the system enumeration name by a period. System enumerations are generally used to set values for system method parameters or object properties and as returnable method values.

4.7.7.            Work with Predefined Values

4.7.7.1. Object Manager

Predefined value can be retrieved at the 1C:Enterprise server side by using manager of the corresponding object. A string that defines the attribute to be obtained looks like the following:

PredefinedValueType.MetadataObjectName.Value

Consider string components in more detail:

„ PredefinedValueType – the following data types can be specified (in their plural forms) to obtain predefined values:

     Catalogs

ChartsOfCharacteristicTypes

ChartsOfAccounts

ChartsOfCalculationTypes

Enumerations

„ MetadataObjectName – specify a metadata object name as it is set in the Designer.

„ Value – it can be one of the following:

     enumeration value name for enumerations

name of predefined value to be obtained as it is set in the Designer

RoutePoints.PointName – point in the business process route

If you want to obtain a route point for a business process, the string describing the value to be obtained will look like the following:

BusinessProcesses.MetadataObjectName.RoutePoints.RoutePointName

Example:

//  Retrieve enumeration value.
Type  = Enums.ProductTypes.Product;

//  Retrieve predefined catalog data.
Item  = Catalogs.Currency.Rouble;

//  Business-process route point
Point  = BusinessProcess.Match.RoutePoints.Approval;

4.7.7.2. PredefinedValue() Function

Since application objects are unavailable at the client side, predefined attributes cannot be retrieved using object manager. Therefore, a global context method, PredefinedValue(), is used instead. This method uses a string that describes the predefined value to be retrieved as its parameter. To describe the predefined value, use syntax of the query language VALUE operator (see page 1-443). The string that defines the attribute to be obtained looks like the following:

PredefinedValueType.MetadataObjectName.Value

Consider string components in more detail:

„ PredefinedValueType – the following data types can be specified (in their singular forms) to obtain predefined values:

     Catalog

ChartOfChartOfCharacteristicTypes

ChartOfChartOfAccounts

ChartOfChartOfCalculationTypes

Enum

BusinessProcess

„ MetadataObjectName – specify a metadata object name as it is set in the Designer.

„ Value – it can be one of the following:

     enumeration value name for enumerations

name of predefined value to be obtained as it is set in the Designer RoutePoint.PointName – point in the business process route EmptyRef, if you want to retrieve an empty reference.

If you want to retrieve a route point for a business process, the string describing the value to be obtained will look like the following:

Example:

//  Retrieve enumeration value.
Type  = PredefinedValue("Enum.ProductTypes.Product");

//  Retrieve empty reference value.
EmptyRef  =
PredefinedValue("Document.Invoice.EmptyRef");

//  Retrieve predefined catalog data.
Item  = PredefinedValue("Catalogs.Currency.Rouble");

//  Business-process route point
Point  = PredefinedValue("BusinessProcess.Match.RoutePoint.Approval");

If you need to get the system enumeration value, the method parameter will appear as follows: SystemEnumerationName.SystemEnumerationValue.

Example:

ChartType = PredefinedValue("ChartType.ConcaveSurface");

4.8. SYSTEM STARTUP VERSIONS

The 1C:Enterprise system can be used in its file mode or client/server mode or as an external connection and Web services (see page 2-819).

The Designer can be used to configure procedures and functions of common modules and object modules for each of the versions.

4.8.1. Execution of Procedures and Functions

Use preprocessor instructions and compiler directives to allow use of procedures and functions from various modules (for information about module types see page 1-115).

4.8.1.1. Differences Between Preprocessor Instructions and Compiler Directives

Preprocessor instructions and compiler directives are used to leave the compiled module with components that are required in a particular context. However, preprocessor instructions affect module source text (i.e. remove invalid text from the module), while compiler directives affect building blocks of the code (i.e. methods including procedures and functions as well as variable declarations).

In practice all program modules in the system can be grouped into two major categories:

„ Modules that exist (and run) in a particular context; e.g., a managed application module can only run at the client side (thin or web client).

„ Modules that exist (and run) in multiple contexts. These include managed form modules, command modules and common modules. For example, a managed form module can have up to 4 instances, each of them gaining control in the process of operation: client-side context module

server-side context module

client-side out-of-context module

server-side out-of-context module

Command modules and common modules cannot have context-dependent instances (unlike form modules). Therefore, certain modules can be compiled multiple times depending on whether the module contains code fragments that can run in a particular context.

Let us review what impact compiler directives and preprocessor instructions have on the source module code while it is being converted to executable code.

Consider a managed form module as an example.

When you create a form, it generates 4 module instances and runs all the required preprocessor instructions for each instance. Then each module instance is processed to remove the text enclosed within preprocessor instructions.

The resulting code is compiled in accordance with the context and compiler directives. This creates an executable module.

Assume the form module source code contains the following construct:

&AtClient
Procedure  WorkWithFiles()

#If WebClient Then

// program code 1
// runs at the web client only
#Else

// program code 2
// runs at other clients
#EndIf

EndProcedure

The following is performed:

„ This procedure is compiled at any client (as the compilation directive goes).

„ At the same time preprocessor instructions define what text is left in the module (i.e. compiled) at what client. In this example the web client will only have program code 1 available, while other clients will have program code 2 available.

However, if the form module uses the following code:

#If  AtServer Then

&AtClient
Procedure  Client()
EndProcedure

#EndIf

The following is performed:

„ Source text of the procedure is stored at the server, but is not compiled as the &AtClient compiler directive prevents the procedure from being used at the server side.

„ The client does not even store the source code of the procedure as it is removed by the preprocessor instruction, i.e. it is neither compiled nor available for calling.

The above procedure explains interaction between directives and instructions as well as their combined application.

Please note that methods marked with &AtClientAtServerNoContext and &AtClientAtServer directives in the program module are included simultaneously in different instances of program modules.

4.8.1.2. Preprocessor Instructions

Preprocessor instructions have the following syntax:

Preprocessor Instruction

#If <Logical expression> Then

#ElseIf <Logical expression> Then

#Else

#EndIf

Logical expression

<Logical expression> = [NOT] <Preprocessor symbol> [<Boolean operation> [NOT] <Preprocessor symbol> [<Boolean operation>

[NOT] <Preprocessor symbol>]…] Preprocessor symbol

<Preprocessor symbol> = { Server | AtServer | Client | AtClient |ThinClient | WebClient | ExternalConnection | MobileAppClient | MobileAppServer }

Boolean operation

<Boolean operation> = {AND | OR}

„ #If

„ #Then

„ #Else

„ #ElseIf

„ #EndIf

„ AND

„ OR

„ NOT

„ Server

„ AtServer

„ Client

„ AtClient

„ ThinClient

„ WebClient

„ ExternalConnection

„ ThickClientManagedApplication

„ ThickClientOrdinaryApplication

„ MobileAppClient

„ MobileAppServer

Below you can see a list of preprocessor instructions with a brief description:

„ Server, AtServer – defines a server.

„ Client, AtClient – defines any client.

„ ThinClient – defines a thin client.

„ WebClient – defines a web client.

„ ExternalConnection – defines an external connection.

„ ThickClientManagedApplication – defines managed application mode for the thick client.

„ ThickClientOrdinaryApplication – defines ordinary mode for the thick client.

„ MobileAppClient – defines the client part of the mobile application.

„ MobileAppServer – defines the server part of the mobile application.

The table below specifies preprocessor instructions defined in various 1C:Enterprise operation modes:

If you are using a non-global common module that is set to be used at any client and at server, then methods enclosed in #If Server Then #EndIf are only available if they are called at the server side. You cannot call these methods at the client side.

Server and AtServer instructions are identical.

Client and AtClient instructions are also identical.

NOTE

Before a program module is passed to a thin or web client, the server processes preprocessor instruction in the module. Code in the 1C:Enterprise script that is not executed at the client side is replaced with white spaces (i.e. removed). However, line break and tab characters are retained.

4.8.1.3. Compiler Directives

Compiler directives have the following syntax.

Compiler Directives

&<Directive>

<Language construct> Directive

<Directive> = { AtClient | AtServer | AtServerNoContext | AtClientAtServerNoContext | AtClientAtServer | Area | EndOfArea

Language construct

<Language construct> = <Variable description> | <Procedure description> | <Function description>

For a detailed description of language constructs see page 1-128.

„ AtClient

„ AtServer

„ AtServerNoContext

„ AtClientAtServerNoContext

„ AtClientAtServer

„ Region

„ EndRegion

Below you can see a list of compiler directives with a brief description:

„ AtClient – method is executed at the client side in a form context.

A variable lives as long as the client-side form.

You can access client variables of the form module from the method. You are allowed to call any methods.

„ AtServer – method is executed at the server side in a form context.

Lifetime of a variable lasts as long as server call execution.

You can access server variables of the form module from the method.

You are allowed to call:

server methods

server out-of-context methods

client/server out-of-context methods

methods of non-global common server modules

„ AtServerNoContext – method is executed at the server outside the form context.

Variables cannot be preceded by this compilation directive.

You cannot access variables of the form module from the method.

You are allowed to call:

     server out-of-context methods

client/server out-of-context methods

methods of non-global common server modules

„ AtClientAtServerNoContext – method is executed both at the client and at the server, outside the form context.

Variables cannot be preceded by this compilation directive.

You cannot access variables of the form module from the method.

You are allowed to call:

     server out-of-context methods

client/server out-of-context methods

methods of non-global common server modules

methods of non-global common modules with Server and Client (managed application) check boxes

„ AtClientAtServer – method is executed both at the client and at the server.

Variables cannot be preceded by this compilation directive.

You are allowed to call:

     server out-of-context methods

client/server out-of-context methods

methods of non-global common server modules

methods of non-global common modules with Server and Client

(managed application) check boxes

„ Region, EndOfRegion – should not be used to specify script code execution location. These directives can be used to highlight a text fragment that can be collapsed (similarly to procedures, functions, etc.). For further information, please see page 2-945.

The table below demonstrates compiler directives available in various 1C:Enterprise modules:

 

Form module

Form module variables

Command module

Common module

AtClient

+

+

+

+

AtServer

+

+

+

+

AtServerNoContext

+

 

 

 

AtClientAtServerNoContext

+

 

 

 

AtClientAtServer

 

 

+

 

4.8.2. Use of Objects, Their Properties and Methods

Every object, method or property in the 1C:Enterprise script (referred to as "object" in this section) is characterized by accessibility level (see Syntax Assistant) that defines where it can be used. Additionally the Syntax Assistant specifies auxiliary data that can be useful to the developer.

Thin client – specifies that the object is available at the thin client.

Web-client – specifies that the object is available at the web client.

Server – specifies that the object is available at the 1C:Enterprise server.

External connection – specifies that the object is available in external connection mode.

Thick client – specifies that the object is available at the thick client.

Mobile application (client) – specifies that the object is available in the client section of the mobile platform.

Mobile application (server) – specifies that the object is available on the server side of the mobile platform.

IMPORTANT!

If you specify that an object is unavailable in one of run modes, its properties and methods are also unavailable. Therefore, it is not mentioned specifically at the property and method description step.

NOTE

If an object is unavailable in a client application, the type of this object is also unavailable in this client application. For instance, if object CatalogObject.Contractors is unavailable within a thin client, Type("CatalogObject.Contractors") is also unavailable in a thin client.

Serializable. It specifies object values can be saved (e.g., parameters of report and data processor forms can be saved using SaveValue() and ValueToFile() methods) and placed into ValueStorage.

The given object may be serialized to/from XML. It specifies 1C:Enterprise data values can be read/written from/to XML. For details see page 2-745.

Exchange with server is possible. It specifies values of this type can be exchanged between the client and the server.

NOTE

In the managed run mode, exchange between the client and the server is allowed for objects which support XDTO serialization.

The given object may be serialized to/from XDTO. It specifies that this type can be mapped to XDTO data model. It also sets a fully qualified name (namespace URI and type name) for a type to which this type is mapped. For example, for the ValueStorage type it is {http://v8.1c.ru/8/data/core}ValueStorage.

The Syntax Assistant includes information about caching the results of some 1C:Enterprise methods. For example, the following information will be specified for the global context method PredefinedValue(): Execution result is cached on first call till the configuration or platform version is changed.

Leave a Reply

Your email address will not be published.

 

1C:Enterprise Developer's Community