Data services Version 7.18 This documentation is provided under restrictions on use and are protected by intellectual property laws. Except as expressly permitted in your license agreement or allowed by law, you may not use, copy, reproduce, translate, broadcast, modify, license, transmit, distribute, exhibit, perform, publish or display any part, in any form, or by any means. Reverse engineering, disassembly, or decompilation of this documentation, unless required by law for interoperability, is prohibited.

The information contained herein is subject to change without notice and is not warranted to be error-free. If you find any errors, please report them to us in writing.

© 2021 Creatio. All rights reserved. Table of Contents | 3

Table of Contents

OData 5 OData 4 protocol 5 OData 3 protocol 5 The limitations of OData protocol 7 OData integration examples 8 Stream data type request examples 8 Retrieve data 8 Add data 10 Modify data 15 Delete data 17 Batch request examples 18 Batch request (Content-Type: application/) 19 Batch request (Content-Type: application/json and Prefer: continue-on-error) 22 Batch request (Content-Type: multipart/mixed) 24 Batch request (Content-Type: multipart/mixed and different sets of requests) 27 WCF client request examples 29 Retrieve a contact collection via a LINQ request. 30 Retrieve a contact collection via an implicit request 31 Retrieve a contact collection via an explicit request 31 CRUD operation examples 32 Odata web service (OData 4) 34 Request string 35 Request headers 37 Request body 37 HTTP status code 38 Response body 39 EntityDataService.svc web service (OData 3) 40 Request string 41 Request headers 43 Request body 44 HTTP status code 44 Response body 45 DataService 46 Resctrictions when using DataService 46 Add a button to create a new record in the [Contacts] section 47 Example implementation algorithm 47

© 2021 Creatio. All rights reserved. Table of Contents | 4

Add a button to read records in the [Contacts] section 49 Example implementation algorithm 49 Filter records in the [Contacts] section 52 Example implementation algorithm 52 Filter records in the [Contacts] section using a macro 56 Example implementation algorithm 57 Update a record in the [Contacts] section 60 Example implementation algorithm 60 Delete a record in the [Contacts] section 64 Example implementation algorithm 64 Add and update a record in the [Contacts] section 68 Example implementation algorithm 68 InsertQuery class 72 Properties 73 The ColumnValues class 74 The Parameter class 75 SelectQuery class 76 Properties 78 The SelectQueryColumns class 80 The ColumnExpression class 80 The Parameter class 83 The ServerESQCacheParameters class 84 Filters class 85 The Filters class 85 The BaseExpression class 88 EntitySchemaQueryMacrosType enumeration 91 UpdateQuery class 92 Properties 93 The ColumnValues class 94 The Parameter class 95 The Filters class 96 DeleteQuery class 96 Properties 97 The Filters class 98 Batch queries 98

© 2021 Creatio. All rights reserved. OData | 5

OData

Advanced

OData () is an ISO/IEC-approved OASIS standard. It defines a set of best practices for building and using REST API. Use OData to create REST-based services that let you publish and edit resources using simple HTTP requests. Such resources should be identified with a URL and defined in the . Creatio supports OData 4 and OData 3 protocols. OData 4 provides more features than OData 3. The main difference between the protocols is the data format of the server's response. Learn more about the differences between OData 3 and OData 4 protocols in the official OData documentation. Use OData 4 for Creatio integration.

All external requests to the Creatio application must be authenticated. We recommend using cookie-based authentication (form-based authentication) implemented with AuthService.svc web service for OData requests.

OData 4 protocol

The odata web service provides access to Creatio objects via the OData 4 protocol.

The OData service URL for .NET Framework

https://mycreatio.com/0/odata

The OData service URL for .NET Core

https://mycreatio.com/odata

OData 3 protocol

The EntityDataService.svc web service provides access to Creatio objects via the OData 3 protocol.

The EntityDataService.svc server address

https://mycreatio.com/0/ServiceModel/EntityDataService.svc

Use the EntityDataService.svc service to work with Creatio objects in a WCF client.

Windows Communication Foundation (WCF) is a program framework that handles data exchange between applications. WCF is a part of .NET Framework.

© 2021 Creatio. All rights reserved. OData | 6

The WCF client operates via receiving the service metadata and creating client proxy classes. The client application will communicate with Creatio's EntityDataService.svc service using these mediator classes.

To implement the client application:

1. Create a .NET project where you will implement the Creatio integration.

2. Generate client proxy classes for the EntityDataService.svc service.

3. Create a context instance of the EntityDataService.svc service's runtime environment.

4. Implement the integration's client business logic using the methods of the proxy class instance.

There are several ways to generate the proxy classes for the EntityDataService.svc service:

Using the DataServiceModel Metadata Utility Tool (DataSvcutil.exe) .

From the Visual Studio client application project.

Generate proxy classes using the DataServiceModel Metadata Utility Tool

DataSvcUtil.exe is a command line program provided by WCF Data Services . The utility uses the OData channel and generates the data service's client classes required to access the service from the .NET Framework client application. The data classes are generated using the following metadata sources:

WSDL – the service metadata document. Describes the data model provided by the data service.

CSDL – the data model file. Uses the common schema definition language ( CSDL ). Learn more: [MC–CSDL]: Conceptual Schema Definition File Format.

EDMX – an *.xml file. Create it using programs for working with the EDM model. The programs are included in the Entity Framework . Learn more: [MC–EDMX]: Entity Data Model for Data Services Packaging Format.

The DataSvcUtil.exe tool is usually installed in the C:\Windows\.NET\Framework\v4.0 directory. For 64-bit systems, the respective directory is usually C:\Windows\Microsoft.NET\Framework64\v4.0 .

The DataSvcutil.exe utility calling format

datasvcutil /out:file [/in:file | /uri:serviceuri] [/dataservicecollection] [/language:devlang] [/nologo] [/version:ver] [/help]

Find the detailed information about the DataSvcutil.exe utility in the official MSDN documentation.

Generate proxy classes from the Visual Studio client application project To generate proxy classes from the Visual Studio client application project:

1. Right-click the project where you want to implement Creatio integration and select [ Add Service Reference… ] in the context menu.

2. Enter the complete address of the EntityDataService.svc service in the [ Address ] field.

3. Click [ Go ] and specify the Creatio user credentials. The entities supported by the service will appear in the

© 2021 Creatio. All rights reserved. OData | 7

[ Services ] window upon success. 4. Specify the namespace to include the generated proxy classes in the [ Namespace ] field. For example, CreatioServiceReference . You will also need to link this namespace in the using block of the project.

5. Click [ OK ] to generate the proxy classes. This will add a new Reference.cs code file with the description of proxy classes to the project. Use the classes to call and interact with the data service's resources as objects.

Visual Studio also lets you generate the service's proxy classes from the service metadata file stored on your drive. To do this, enter the complete path to the metadata file, starting from the file:// prefix, in the [ Address ] field.

file://C:/metadata.xml

Visual Studio will link the Microsoft.Data.Services.Client.dll build in the project upon generating the service's proxy classes. This ensures OData 3 protocol support. If the client application requires an earlier version of the protocol, link the corresponding build manually. This client library lets you call the EntityDataService.svc data service using the standard .NET Framework programming templates and the LINQ request language.

Add the using directives to and declare the variable of the OData service address in the project code to ensure successful compilation.

The Using directives

using System; using System.Data.Services.Client; using System.Net; using Terrasoft.Sdk.Examples.CreatioServiceReference; using System.Linq;

Declare the variable of the OData service address

private static Uri serverUri = new Uri("http:////0/ServiceModel/EntityDataService.svc/");

The limitations of OData protocol When using the OData protocol, keep in mind the following limitations:

It is not possible to create system users. It is not possible to specify the culture of the returned data. The culture is determined by the culture of the user on whose behalf you executed the request.

The response body can contain up to 20 000 lines. A batch request can contain up to 100 sub-requests.

© 2021 Creatio. All rights reserved. OData integration examples | 8

OData integration examples

Advanced

View the Creatio API documentation with examples of various CRUD operations to the Creatio via OData 3 and OData 4 protocols on a separate web resource. Stream data type request examples

Advanced

The following elements have the Stream data type:

Images Files

Binaries

Use the following standard methods to work with the Stream data type:

GET – retrieve data

POST – add data

PUT – modify data

DELETE – delete data

Clear the browser cache to display request results when working with the Stream data type.

Retrieve data

Example. Use the OData service to retrieve the “New user” contact's photo.

Implement the example

1. Retrieve the identifier of the “New user” contact's photo

The contact's photo is stored in the [Data] column of the [SysImage] database table. Run the following SQL query to retrieve the identifier of the “New user” contact's photo.

SQL query

select Id from SysImage where Id = (select PhotoId from Contact where Name = 'New user')

© 2021 Creatio. All rights reserved. OData integration examples | 9

Response

29FE7EDF-4DB9-4E09-92B0-018047BA1F71

2. Retrieve the “New user” contact's photo.

Execute the following request to retrieve the “New user” contact's photo.

Request

// Retrieve the [Data] field value for the 29FE7EDF-4DB9-4E09-92B0-018047BA1F71 [Id] object instance in the [SysImage] collection. GET http://mycreatio.com/0/odata/SysImage(29FE7EDF-4DB9-4E09-92B0-018047BA1F71)/Data

Response

Status: 200 OK

Results in Creatio

© 2021 Creatio. All rights reserved. OData integration examples | 10

Add data

Example. Use the OData service to add the “New user” contact. Then, add a photo to the contact.

Implement the example

1. Add the “New user” contact.

Creatio stores all contacts in the [Contact] database table. Execute the following request to add the “New user” contact.

Request

// Add an object instance to the [Contact] collection. POST http://mycreatio.com/0/odata/Contact

Accept: application/json; odata=verbose Content-Type: application/json; odata=verbose; IEEE754Compatible=true BPMCSRF: OpK/NuJJ1w/SQxmPvwNvfO

{ // Write the "New user" contact name to the [Name] field. "Name": "New user" }

Response

Status: 201 Created

{ "@odata.context": "http://mycreatio.com/0/odata/$metadata#Contact/$entity", "Id": "4c63c8fa-467b-48a6-973f-b2069298404f", "Name": "New user", "OwnerId": "410006e1-ca4e-4502-a9ec-e54d922d2c00", "CreatedOn": "2021-01-14T08:33:29.009023Z", "CreatedById": "410006e1-ca4e-4502-a9ec-e54d922d2c00", "ModifiedOn": "2021-01-14T08:33:29.009023Z",

© 2021 Creatio. All rights reserved. OData integration examples | 11

"ModifiedById": "410006e1-ca4e-4502-a9ec-e54d922d2c00", "ProcessListeners": 0, "Dear": "", "SalutationTypeId": "00000000-0000-0000-0000-000000000000", "GenderId": "00000000-0000-0000-0000-000000000000", "AccountId": "00000000-0000-0000-0000-000000000000", "DecisionRoleId": "00000000-0000-0000-0000-000000000000", "TypeId": "00000000-0000-0000-0000-000000000000", "JobId": "00000000-0000-0000-0000-000000000000", "JobTitle": "", "DepartmentId": "00000000-0000-0000-0000-000000000000", "BirthDate": "0001-01-01T00:00:00Z", "Phone": "", "MobilePhone": "", "HomePhone": "", "Skype": "", "Email": "", "AddressTypeId": "00000000-0000-0000-0000-000000000000", "Address": "", "CityId": "00000000-0000-0000-0000-000000000000", "RegionId": "00000000-0000-0000-0000-000000000000", "Zip": "", "CountryId": "00000000-0000-0000-0000-000000000000", "DoNotUseEmail": false, "DoNotUseCall": false, "DoNotUseFax": false, "DoNotUseSms": false, "DoNotUseMail": false, "Notes": "", "Facebook": "", "LinkedIn": "", "Twitter": "", "FacebookId": "", "LinkedInId": "", "TwitterId": "", "[email protected]": "Contact(4c63c8fa-467b-48a6-973f-b2069298404f)/ContactPhoto", "[email protected]": "Contact(4c63c8fa-467b-48a6-973f-b2069298404f)/ContactPhoto", "[email protected]": "application/octet-stream", "TwitterAFDAId": "00000000-0000-0000-0000-000000000000", "FacebookAFDAId": "00000000-0000-0000-0000-000000000000", "LinkedInAFDAId": "00000000-0000-0000-0000-000000000000", "PhotoId": "00000000-0000-0000-0000-000000000000", "GPSN": "", "GPSE": "", "Surname": "user", "GivenName": "New", "MiddleName": "", "Confirmed": true, "IsNonActualEmail": false,

© 2021 Creatio. All rights reserved. OData integration examples | 12

"Completeness": 0, "LanguageId": "6ebc31fa-ee6c-48e9-81bf-8003ac03b019", "Age": 0 }

Results in Creatio

The “New user” contact identifier is “4c63c8fa-467b-48a6-973f-b2069298404f”. 2. Add a photo to the “New user” contact.

The contact photo must be stored in the [Data] column of the [SysImage] database table. Since there is no table record for this contact, you must add it. Execute the following request to add a record to the table.

Request

// Add an object instance to the [SysImage] collection. POST http://mycreatio.com/0/odata/SysImage

Accept: application/json; odata=verbose Content-Type: application/json; odata=verbose; IEEE754Compatible=true BPMCSRF: OpK/NuJJ1w/SQxmPvwNvfO

{ // Write the filename of the contact photo to the [Name] field. "Name": "scr_NewContactPhoto.png", // Write an arbitrary record identifier to the [Id] field of the [SysImage] table. "Id": "410006E1-CA4E-4502-A9EC-E54D922D2C01", // Write the file type of the contact photo to the [MimeType] field. "MimeType": "image/png" }

© 2021 Creatio. All rights reserved. OData integration examples | 13

Response

Status: 201 Created

{ "@odata.context": "http://mycreatio.com/0/odata/$metadata#SysImage/$entity", "Id": "410006e1-ca4e-4502-a9ec-e54d922d2c01", "CreatedOn": "2021-01-14T08:52:47.7573789Z", "CreatedById": "410006e1-ca4e-4502-a9ec-e54d922d2c00", "ModifiedOn": "2021-01-14T08:52:47.7573789Z", "ModifiedById": "410006e1-ca4e-4502-a9ec-e54d922d2c00", "ProcessListeners": 0, "UploadedOn": "0001-01-01T00:00:00Z", "Name": "scr_NewContactPhoto.png", "[email protected]": "SysImage(410006e1-ca4e-4502-a9ec-e54d922d2c01)/Data", "[email protected]": "SysImage(410006e1-ca4e-4502-a9ec-e54d922d2c01)/Data", "[email protected]": "application/octet-stream", "MimeType": "image/png", "HasRef": false, "[email protected]": "SysImage(410006e1-ca4e-4502-a9ec-e54d922d2c01)/PreviewData", "[email protected]": "SysImage(410006e1-ca4e-4502-a9ec-e54d922d2c01)/PreviewData", "[email protected]": "application/octet-stream" }

The record was added to the [SysImage] database table, however the value of the [Data] column is “0x.”

Pass the image in the request body. The image filename must match the value of the [Name] field. Execute the following request to add the contact photo to the [Data] column.

Request

// Update the value of the [Data] field for the 410006e1-ca4e-4502-a9ec-e54d922d2c01 [Id] object instance in the [SysImage] collection. PUT http://mycreatio.com/0/odata/SysImage(410006e1-ca4e-4502-a9ec-e54d922d2c01)/Data

Accept: application/json; text/plain; */* Content-Type: application/octet-stream; IEEE754Compatible=true BPMCSRF: OpK/NuJJ1w/SQxmPvwNvfO

© 2021 Creatio. All rights reserved. OData integration examples | 14

Response

Status: 200 OK

3. Bind the added photo to the “New user” contact.

Link the [Data] field of the [SysImage] table to the [PhotoId] field of the [Contact] table to bind the photo to the “New user” contact. Execute the following request to set up the binding.

Request

// Update the value of the [PhotoId] field for the 4c63c8fa-467b-48a6-973f-b2069298404f [Id] object instance in the [Contact] collection. PATCH http://mycreatio.com/0/odata/Contact(4c63c8fa-467b-48a6-973f-b2069298404f)

Accept: application/json;odata=verbose Content-Type: application/json; odata=verbose; IEEE754Compatible=true BPMCSRF: OpK/NuJJ1w/SQxmPvwNvfO

{ // Write the identifier of the record in the [SysImage] table to the [PhotoId] field. "PhotoId": "410006e1-ca4e-4502-a9ec-e54d922d2c01" }

Response

Status: 204 No Content

Results in Creatio

© 2021 Creatio. All rights reserved. OData integration examples | 15

To add the photo of an existing contact, execute:

1. A POST request to add an object instance to the [SysImage] collection.

2. A PUT request to update the value of the [Data] field for the object instance in the [SysImage] collection.

3. A PATCH request to bind the added photo to the “New user” contact.

Modify data

Example. Use the OData service to update the photo of the existing “New user” contact.

Implement the example

1. Retrieve the identifier of the “New user” contact's photo.

The contact's photo is stored in the [Data] column of the [SysImage] database table. Execute the following SQL query to retrieve the identifier of the “New user” contact's photo.

SQL query

select Id from SysImage where Id = (select PhotoId from Contact where Name = 'New user')

© 2021 Creatio. All rights reserved. OData integration examples | 16

Response

29FE7EDF-4DB9-4E09-92B0-018047BA1F71

2. Update the “New user” contact's photo.

Execute the following request to update the “New user” contact's photo.

Request

// Update the [Data] field for the 29FE7EDF-4DB9-4E09-92B0-018047BA1F71 [Id] object instance in the [SysImage] collection. PUT http://mycreatio.com/0/odata/SysImage(29FE7EDF-4DB9-4E09-92B0-018047BA1F71)/Data

Accept: application/json; text/plain; */* Content-Type: application/octet-stream; IEEE754Compatible=true BPMCSRF: OpK/NuJJ1w/SQxmPvwNvfO

Response

Status: 200 OK

Results in Creatio

© 2021 Creatio. All rights reserved. OData integration examples | 17

Delete data

Example. Use the OData service to delete the photo of the “New user” contact.

Implement the example

1. Retrieve the identifier of the “New user” contact's photo.

The contact's photo is stored in the [Data] column of the [SysImage] database table. Execute the following SQL query to retrieve the identifier of the “New user” contact's photo.

SQL query

select Id from SysImage where Id = (select PhotoId from Contact where Name = 'New user')

Response

29FE7EDF-4DB9-4E09-92B0-018047BA1F71

2. Delete the “New user” contact's photo. Execute the following request to delete the “New user” contact's photo.

Request

© 2021 Creatio. All rights reserved. Batch request examples | 18

// Delete the value of the [Data] field for the 29FE7EDF-4DB9-4E09-92B0-018047BA1F71 [Id] object instance in the [SysImage] collection. DELETE http://mycreatio.com/0/odata/SysImage(29FE7EDF-4DB9-4E09-92B0-018047BA1F71)/Data

Accept: application/json; text/plain; */* Content-Type: application/json; charset=utf-8; IEEE754Compatible=true BPMCSRF: OpK/NuJJ1w/SQxmPvwNvfO

Response

Status: 204 No Content

Results in Creatio

Batch request examples

Advanced

Batch requests combine multiple HTTP requests by specifying each request as a separate object in the batch request's body. The Creatio database server returns a single HTTP response that contains the responses to each request. Use batch requests to improve Creatio performance. The batch requests utilize:

The POST HTTP method.

The $batch parameter.

The Content-Type header.

© 2021 Creatio. All rights reserved. Batch request examples | 19

The values of the Content-Type header:

application/json – restricts the content the server returns for each request within the batch request to a single type.

multipart/mixed – allows you to set unique Content-Type headers for each request in the batch request body.

If one of the requests completes with a 4xx-5xx group response code, the subsequent requests will not be executed. Add the Prefer: continue-on-error header to the main HTTP request to enable the execution of the subsequent requests.

Attention. A batch request can contain up to 100 requests.

Batch request (Content-Type: application/json)

Batch request

POST http://mycreatio.com/0/odata/$batch

Content-Type: application/json; odata=verbose; IEEE754Compatible=true Accept: application/json BPMCSRF: OpK/NuJJ1w/SQxmPvwNvfO ForceUseSession: true

{ "requests": [ { // Add an object instance to the City collection. "method": "POST", "url": "City", "id": "t3", "body": { // Add the Burbank value to the Name field. "Name": "Burbank" }, "headers": { "Content-Type": "application/json;odata=verbose", "Accept": "application/json;odata=verbose", "Prefer": "continue-on-error" } }, { // Add an object instance to the City collection. "method": "POST", "atomicityGroup": "g1", "url": "City",

© 2021 Creatio. All rights reserved. Batch request examples | 20

"id": "t3", "body": { // Add the 62f9bc01-57cf-4cc7-90bf-8672acc922e3 value to the Id field. "Id": "62f9bc01-57cf-4cc7-90bf-8672acc922e3", // Add the Spokane value to the Name field. "Name": "Spokane" }, "headers": { "Content-Type": "application/json;odata=verbose", "Accept": "application/json;odata=verbose", "Prefer": "continue-on-error" } }, { // Update the 62f9bc01-57cf-4cc7-90bf-8672acc922e3 id object instance in the City collection. "method": "PATCH", "atomicityGroup": "g1", "url": "City/62f9bc01-57cf-4cc7-90bf-8672acc922e3", "id": "t2", "body": { // Change the value of the Name field to Texas. "Name": "Texas" }, "headers": { "Content-Type": "application/json;odata=verbose", "Accept": "application/json;odata=verbose", "Prefer": "continue-on-error" } } ] }

Response

Status: 200 OK

{ "responses": [ { "id": "t3", "status": 201, "headers": { "location": "https://mycreatio.com/0/odata/City(b6a05348-55b1-4314-a228-436ba305d2f3)", "content-type": "application/json; odata.metadata=minimal", "odata-version": "4.0" }, "body": {

© 2021 Creatio. All rights reserved. Batch request examples | 21

"@odata.context": "https://mycreatio.com/0/odata/$metadata#City/$entity", "Id": "b6a05348-55b1-4314-a228-436ba305d2f3", "CreatedOn": "2020-05-18T17:50:39.2838673Z", "CreatedById": "dad159f3-6c2d-446a-98d2-0f4d26662bbe", "ModifiedOn": "2020-05-18T17:50:39.2838673Z", "ModifiedById": "dad159f3-6c2d-446a-98d2-0f4d26662bbe", "Name": "Burbank", "Description": "", "CountryId": "00000000-0000-0000-0000-000000000000", "RegionId": "00000000-0000-0000-0000-000000000000", "TimeZoneId": "00000000-0000-0000-0000-000000000000", "ProcessListeners": 0 } }, { "id": "t3", "atomicityGroup": "c59e36b2-2aa9-44fa-86d3-e7d68eecbfa0", "status": 201, "headers": { "location": "https://mycreatio.com/0/odata/City(62f9bc01-57cf-4cc7-90bf-8672acc922e3)", "content-type": "application/json; odata.metadata=minimal", "odata-version": "4.0" }, "body": { "@odata.context": "https://mycreatio.com/0/odata/$metadata#City/$entity", "Id": "62f9bc01-57cf-4cc7-90bf-8672acc922e3", "CreatedOn": "2020-05-18T17:50:39.361994Z", "CreatedById": "dad159f3-6c2d-446a-98d2-0f4d26662bbe", "ModifiedOn": "2020-05-18T17:50:39.361994Z", "ModifiedById": "dad159f3-6c2d-446a-98d2-0f4d26662bbe", "Name": "Spokane", "Description": "", "CountryId": "00000000-0000-0000-0000-000000000000", "RegionId": "00000000-0000-0000-0000-000000000000", "TimeZoneId": "00000000-0000-0000-0000-000000000000", "ProcessListeners": 0 } }, { "id": "t2", "atomicityGroup": "c59e36b2-2aa9-44fa-86d3-e7d68eecbfa0", "status": 204, "headers": { "odata-version": "4.0" } } ] }

© 2021 Creatio. All rights reserved. Batch request examples | 22

Batch request (Content-Type: application/json and Prefer: continue-on-error)

Batch request

POST http://mycreatio.com/0/odata/$batch

Content-Type: application/json; odata=verbose; IEEE754Compatible=true Accept: application/json BPMCSRF: OpK/NuJJ1w/SQxmPvwNvfO ForceUseSession: true Prefer: continue-on-error

{ "requests": [ { // Add an object instance to the City collection. "method": "POST", "url": "City", "id": "t3", "body": { // Add the Burbank value to the Name field. "Name": "Burbank" }, "headers": { "Content-Type": "application/json;odata=verbose", "Accept": "application/json;odata=verbose", "Prefer": "continue-on-error" } }, { // Update the 62f9bc01-57cf-4cc7-90bf-8672acc922e3 id object instance in the City collection. "method": "PATCH", "atomicityGroup": "g1", "url": "City/62f9bc01-57cf-4cc7-90bf-8672acc922e2", "id": "t2", "body": { // Change the value of the Name field to Indiana. "Name": "Indiana" }, "headers": { "Content-Type": "application/json;odata=verbose", "Accept": "application/json;odata=verbose", "Prefer": "continue-on-error"

© 2021 Creatio. All rights reserved. Batch request examples | 23

} }, { // Add an object instance to the City collection. "method": "POST", "atomicityGroup": "g1", "url": "City", "id": "t3", "body": { // Write the 62f9bc01-57cf-4cc7-90bf-8672acc922a1 value to the Id field. "Id": "62f9bc01-57cf-4cc7-90bf-8672acc922a1", // Write the Iowa value to the Name field. "Name": "Iowa" }, "headers": { "Content-Type": "application/json;odata=verbose", "Accept": "application/json;odata=verbose", "Prefer": "continue-on-error" } } ] }

Response

Status: 200 OK

{ "responses": [ { "id": "t3", "status": 201, "headers": { "location": "https://mycreatio.com/0/odata/City(2f5e68f8-38bd-43c1-8e15-a2f13b0aa56a)", "content-type": "application/json; odata.metadata=minimal", "odata-version": "4.0" }, "body": { "@odata.context": "https://mycreatio.com/0/odata/$metadata#City/$entity", "Id": "2f5e68f8-38bd-43c1-8e15-a2f13b0aa56a", "CreatedOn": "2020-05-18T18:06:50.7329808Z", "CreatedById": "dad159f3-6c2d-446a-98d2-0f4d26662bbe", "ModifiedOn": "2020-05-18T18:06:50.7329808Z", "ModifiedById": "dad159f3-6c2d-446a-98d2-0f4d26662bbe", "Name": "Burbank", "Description": "", "CountryId": "00000000-0000-0000-0000-000000000000",

© 2021 Creatio. All rights reserved. Batch request examples | 24

"RegionId": "00000000-0000-0000-0000-000000000000", "TimeZoneId": "00000000-0000-0000-0000-000000000000", "ProcessListeners": 0 } }, { "id": "t2", "atomicityGroup": "0c1c4019-b9fb-4fb3-8642-2d0660c4551a", "status": 204, "headers": { "odata-version": "4.0" } }, { "id": "t3", "atomicityGroup": "0c1c4019-b9fb-4fb3-8642-2d0660c4551a", "status": 201, "headers": { "location": "https://mycreatio.com/0/odata/City(62f9bc01-57cf-4cc7-90bf-8672acc922a1)", "content-type": "application/json; odata.metadata=minimal", "odata-version": "4.0" }, "body": { "@odata.context": "https://mycreatio.com/0/odata/$metadata#City/$entity", "Id": "62f9bc01-57cf-4cc7-90bf-8672acc922a1", "CreatedOn": "2020-05-18T18:06:50.7954775Z", "CreatedById": "dad159f3-6c2d-446a-98d2-0f4d26662bbe", "ModifiedOn": "2020-05-18T18:06:50.7954775Z", "ModifiedById": "dad159f3-6c2d-446a-98d2-0f4d26662bbe", "Name": "Iowa", "Description": "", "CountryId": "00000000-0000-0000-0000-000000000000", "RegionId": "00000000-0000-0000-0000-000000000000", "TimeZoneId": "00000000-0000-0000-0000-000000000000", "ProcessListeners": 0 } } ] }

Batch request (Content-Type: multipart/mixed)

Batch request

POST http://mycreatio.com/0/odata/$batch

© 2021 Creatio. All rights reserved. Batch request examples | 25

Content-Type: multipart/mixed;boundary=batch_a685-9724-d873; IEEE754Compatible=true BPMCSRF: OpK/NuJJ1w/SQxmPvwNvfO ForceUseSession: true

--batch_a685-9724-d873 Content-Type: multipart/mixed; boundary=changeset_06da-d998-8e7e

--changeset_06da-d998-8e7e Content-Type: application/http Content-Transfer-Encoding: binary

// Add an object instance to the City collection. POST City HTTP/1.1 Content-ID: 1 Accept: application/atomsvc+xml;q=0.8, application/json;odata=verbose;q=0.5, */*;q=0.1 Content-Type: application/json;odata=verbose

// Write the Gilbert value to the Name field. {"Name": "Gilbert"}

--changeset_06da-d998-8e7e Content-Type: application/http Content-Transfer-Encoding: binary

// Update the 62f9bc01-57cf-4cc7-90bf-8672acc922e2 id object instance in the City collection. PATCH City/62f9bc01-57cf-4cc7-90bf-8672acc922e2 HTTP/1.1 Content-ID: 2 Accept: application/atomsvc+xml;q=0.8, application/json;odata=verbose;q=0.5, */*;q=0.1 Content-Type: application/json;odata=verbose

// Change the value of the Name field to Lincoln. {"Name": "Lincoln"}

--changeset_06da-d998-8e7e Content-Type: application/http Content-Transfer-Encoding: binary

// Delete the 62f9bc01-57cf-4cc7-90bf-8672acc922e2 id object instance from the City collection. DELETE City/62f9bc01-57cf-4cc7-90bf-8672acc922e2 HTTP/1.1 Content-ID: 3 Accept: application/atomsvc+xml;q=0.8, application/json;odata=verbose;q=0.5, */*;q=0.1 Content-Type: application/json;odata=verbose

Response

© 2021 Creatio. All rights reserved. Batch request examples | 26

Status: 200 OK

--batchresponse_e17aace9-5cbb-49bd-b7ad-f1be8cc8c9d8 Content-Type: multipart/mixed; boundary=changesetresponse_a08c1df6-4b82-4a9b-be61-7ef4cc7b23ba

--changesetresponse_a08c1df6-4b82-4a9b-be61-7ef4cc7b23ba Content-Type: application/http Content-Transfer-Encoding: binary Content-ID: 1

HTTP/1.1 201 Created Location: https://mycreatio.com/0/odata/City(fbd0565f-fa8a-4214-ae89-c976c5f3acb4) Content-Type: application/json; odata.metadata=minimal OData-Version: 4.0

{ "@odata.context": "https://mycreatio.com/0/odata/$metadata#City/$entity", "Id": "fbd0565f-fa8a-4214-ae89-c976c5f3acb4", "CreatedOn": "2020-05-18T18:41:57.0917235Z", "CreatedById": "dad159f3-6c2d-446a-98d2-0f4d26662bbe", "ModifiedOn": "2020-05-18T18:41:57.0917235Z", "ModifiedById": "dad159f3-6c2d-446a-98d2-0f4d26662bbe", "Name": "Gilbert", "Description": "", "CountryId": "00000000-0000-0000-0000-000000000000", "RegionId": "00000000-0000-0000-0000-000000000000", "TimeZoneId": "00000000-0000-0000-0000-000000000000", "ProcessListeners": 0 } --changesetresponse_a08c1df6-4b82-4a9b-be61-7ef4cc7b23ba Content-Type: application/http Content-Transfer-Encoding: binary Content-ID: 2

HTTP/1.1 204 No Content OData-Version: 4.0

--changesetresponse_a08c1df6-4b82-4a9b-be61-7ef4cc7b23ba Content-Type: application/http Content-Transfer-Encoding: binary Content-ID: 3

HTTP/1.1 204 No Content

--changesetresponse_a08c1df6-4b82-4a9b-be61-7ef4cc7b23ba--

© 2021 Creatio. All rights reserved. Batch request examples | 27

--batchresponse_e17aace9-5cbb-49bd-b7ad-f1be8cc8c9d8--

Batch request (Content-Type: multipart/mixed and different sets of requests)

Batch request

POST http://mycreatio.com/0/odata/$batch

Content-Type: multipart/mixed;boundary=batch_a685-9724-d873; IEEE754Compatible=true Accept: application/json BPMCSRF: OpK/NuJJ1w/SQxmPvwNvfO ForceUseSession: true

--batch_a685-9724-d873 Content-Type: multipart/mixed; boundary=changeset_06da-d998-8e7e

--changeset_06da-d998-8e7e Content-Type: application/http Content-Transfer-Encoding: binary

// Add an object instance to the City collection. POST City HTTP/1.1 Content-ID: 1 Accept: application/atomsvc+xml;q=0.8, application/json;odata=verbose;q=0.5, */*;q=0.1 Content-Type: application/json;odata=verbose

// Write the d6bc67b1-9943-4e47-9aaf-91bf83e9c285 value to the Id field. // Write the Nebraska value to the Name field. {"Id": "d6bc67b1-9943-4e47-9aaf-91bf83e9c285", "Name": "Nebraska"}

--batch_a685-9724-d873 Content-Type: multipart/mixed; boundary=changeset_06da-d998-8e71

--changeset_06da-d998-8e71 Content-Type: application/http Content-Transfer-Encoding: binary

// Add an object instance to the City collection. POST City HTTP/1.1 Content-ID: 2 Accept: application/atomsvc+xml;q=0.8, application/json;odata=verbose;q=0.5, */*;q=0.1 Content-Type: application/json;odata=verbose

© 2021 Creatio. All rights reserved. Batch request examples | 28

// Write the d6bc67b1-9943-4e47-9aaf-91bf83e9c286 value to the Id field. // Add the Durham value to the Name field. {"Id": "d6bc67b1-9943-4e47-9aaf-91bf83e9c286", "Name": "Durham"}

Response

Status: 200 OK

{ "responses": [ { "id": "1", "atomicityGroup": "e9621f72-42bd-47c1-b271-1027e4b68e3b", "status": 201, "headers": { "location": "https://mycreatio.com/0/odata/City(d6bc67b1-9943-4e47-9aaf-91bf83e9c285)", "content-type": "application/json; odata.metadata=minimal", "odata-version": "4.0" }, "body": { "@odata.context": "https://mycreatio.com/0/odata/$metadata#City/$entity", "Id": "d6bc67b1-9943-4e47-9aaf-91bf83e9c285", "CreatedOn": "2020-05-18T18:49:16.3766324Z", "CreatedById": "dad159f3-6c2d-446a-98d2-0f4d26662bbe", "ModifiedOn": "2020-05-18T18:49:16.3766324Z", "ModifiedById": "dad159f3-6c2d-446a-98d2-0f4d26662bbe", "Name": "Nebraska", "Description": "", "CountryId": "00000000-0000-0000-0000-000000000000", "RegionId": "00000000-0000-0000-0000-000000000000", "TimeZoneId": "00000000-0000-0000-0000-000000000000", "ProcessListeners": 0 } }, { "id": "2", "atomicityGroup": "960e2272-d8cb-4b4d-827c-0181485dd71d", "status": 201, "headers": { "location": "https://mycreatio.com/0/odata/City(d6bc67b1-9943-4e47-9aaf-91bf83e9c286)", "content-type": "application/json; odata.metadata=minimal", "odata-version": "4.0" }, "body": { "@odata.context": "https://mycreatio.com/0/odata/$metadata#City/$entity", "Id": "d6bc67b1-9943-4e47-9aaf-91bf83e9c286", "CreatedOn": "2020-05-18T18:49:16.4078852Z",

© 2021 Creatio. All rights reserved. WCF client request examples | 29

"CreatedById": "dad159f3-6c2d-446a-98d2-0f4d26662bbe", "ModifiedOn": "2020-05-18T18:49:16.4078852Z", "ModifiedById": "dad159f3-6c2d-446a-98d2-0f4d26662bbe", "Name": "Durham", "Description": "", "CountryId": "00000000-0000-0000-0000-000000000000", "RegionId": "00000000-0000-0000-0000-000000000000", "TimeZoneId": "00000000-0000-0000-0000-000000000000", "ProcessListeners": 0 } } ] }

WCF client request examples

Advanced

Use the DataServiceQuery universal class to retrieve the service's object collection. This class is a request to the service that retrieves the collection of a specific type of entities.

Create a context object instance of the Creatio application environment to execute a request to EntityDataService.svc .

The examples in this article will use the forms authentication.

To implement the forms authentication:

1. Create a LoginClass class.

2. Implement the authServiceUri (a string that requests the Login method of the AuthService.svc authentication service) and AuthCookie (Creatio's authentication cookies) fields.

3. Implement the TryLogin(string userName, string userPassword) method that authenticates the user and saves the server's response to the AuthCookie field.

4. Implement the OnSendingRequestCookie(object sender, SendingRequestEventArgs e) method that will be called in response to an event of the SendingRequest context instance (creating a new HttpWebRequest instance).

The OnSendingRequestCookie method authenticates the user and adds the cookies received in response to the data request.

OnSendingRequestCookie

static void OnSendingRequestCookie(object sender, SendingRequestEventArgs e) { // Call the method of the LoginClass class that authenticates the user's method passed in the parameters. LoginClass.TryLogin("CreatioUserName", "CreatioUserPassword"); var req = e.Request as HttpWebRequest;

© 2021 Creatio. All rights reserved. WCF client request examples | 30

// Add the received authentication cookies to the data request. req.CookieContainer = LoginClass.AuthCookie; e.Request = req; }

There are several ways to execute the service request:

A LINQ request to the named DataServiceQuery object received from the service context.

Implicit enumeration of the DataServiceQuery object received from the service context.

Explicit call of the Execute method of the DataServiceQuery object. Call the BeginExecute method for asynchronous execution.

Retrieve a contact collection via a LINQ request.

Example. Define and implement the LINQ request that returns all contact entities of the EntityDataService.svc service.

Implement the example

The LINQ request

public static void GetOdataCollectioByLinqWcfExample() { // Create the Creatio application context. var context = new Creatio(serverUri); // Define the method that adds authentication cookies upon creating a new request. context.SendingRequest += new EventHandler(OnSendingRequestCookie); try { // Build a LINQ request to retrieve the contact collection. var allContacts = from contacts in context.ContactCollection select contacts; foreach (Contact contact in allContacts) { // Execute the contact actions. } } catch (Exception ex) { // Process errors. } }

© 2021 Creatio. All rights reserved. WCF client request examples | 31

Retrieve a contact collection via an implicit request

Example. Use context to execute an implicit request that retrieves all contact entities of the EntityDataService.svc service.

Implement the example

GetOdataCollectionByImplicitRequestExample()

public static void GetOdataCollectionByImplicitRequestExample() { // Create the Creatio application context. var context = new Creatio(serverUri); // Define the method that adds authentication cookies upon creating a new request. context.SendingRequest += new EventHandler(OnSendingRequestCookie); try { // Define an implicit request that retrieves the contact collection from the service. DataServiceQuery allContacts = context.ContactCollection; foreach (Contact contact in allContacts) { // Execute the actions with contacts. } } catch (Exception ex) { // Process errors. } }

Retrieve a contact collection via an explicit request

Example. Use the DataServiceContext context to execute an explicit request that retrieves all contact entities of the EntityDataService.svc service.

Implement the example

GetOdataCollectionByExplicitRequestExample()

public static void GetOdataCollectionByExplicitRequestExample()

© 2021 Creatio. All rights reserved. WCF client request examples | 32

{ // Define the Uri of the service request that returns the contact collection. Uri contactUri = new Uri(serverUri, "ContactCollection"); // Create the Creatio application context var context = new Creatio(serverUri); // Define the method that adds authentication cookies upon creating a new request. context.SendingRequest += new EventHandler(OnSendingRequestCookie); try { // Call the Execute<>() method to execute an explicit request to the service. foreach (Contact contact in context.Execute(contactUri)) { // Execute the contact actions. } } catch (Exception ex) { // Process errors. } }

CRUD operation examples

Retrieve an object

public static void GetOdataObjectByWcfExample() { // Create the Creatio application context. var context = new Creatio(serverUri); // Define the method that adds authentication cookies upon creating a new request. context.SendingRequest += new EventHandler(OnSendingRequestCookie); // var contact = context.ContactCollection.Where(c => c.Name.Contains("User")).First(); // Execute the contact actions. }

Create an object

public static void CreateCreatioEntityByOdataWcfExample() { // Create a new contact and initialize its properties. var contact = new Contact() { Id = Guid.NewGuid(),

© 2021 Creatio. All rights reserved. WCF client request examples | 33

Name = "New Test User" }; // Create a new account to which the contact is connected and initialize the account's properties. var account = new Account() { Id = Guid.NewGuid(), Name = "Some Company" }; contact.Account = account; // Create the Creatio application context. var context = new Creatio(serverUri); // Define the method that adds authentication cookies upon creating a new request. context.SendingRequest += new EventHandlerl(OnSendingRequestCookie); // Add the contact to the service data model's contact collection. context.AddToAccountCollection(account); // Add the account to the service data model's account collection. context.AddToContactCollection(contact); // Connect the contact to the account in the service data model. context.SetLink(contact, "Account", account); // Save the changes to Creatio in a single request. DataServiceResponse responces = context.SaveChanges(SaveChangesOptions.Batch); // Process the server's responses. }

Update an object

public static void UpdateCreatioEntityByOdatetWcfExample() { // Create the Creatio application context. var context = new Creatio(serverUri); // Define the method that adds authentication cookies upon creating a new request. context.SendingRequest += new EventHandler(OnSendingRequestCookie); // Select a collection's contact to update. var updateContact = context.ContactCollection.Where(c =< c.Name.Contains("Test")).First(); // Update the contact's properties. updateContact.Notes = "New updated description for this contact."; updateContact.Phone = "123456789"; // Save the changes to the service data model. context.UpdateObject(updateContact); // Save the changes to Creatio in a single request. var responces = context.SaveChanges(SaveChangesOptions.Batch); }

Delete an object

© 2021 Creatio. All rights reserved. Odata web service (OData 4) | 34

public static void DeleteCreatioEntityByOdataWcfExample() { // Create the Creatio application context. var context = new Creatio(serverUri);

context.SendingRequest += new EventHandler(OnSendingRequestCookie); // Select a contact collection's object to delete. var deleteContact = context.ContactCollection.Where(c => c.Name.Contains("Test")).First(); // Delete the object from the service data model. context.DeleteObject(deleteContact); // Save the changes to Creatio in a single request. var responces = context.SaveChanges(SaveChangesOptions.Batch); // Process the server's responses. }

Odata web service (OData 4) A PI

Advanced

Depending on the request type, OData 4 protocol can return different data. Learn more about the request and response structure below.

Request structure

// Request string. method Creatio_application_address/0/odata/objects_collection(object_id)/object_field?$parameters

// Request headers. Accept: application/json Content-Type: application/json; charset=utf-8; IEEE754Compatible=true ForceUseSession: true BPMCSRF: authentication_cookie_value

// Request body (for POST and PATCH requests). { "field1": "value1", "field2": "value2", ... }

Response structure

// The status code.

© 2021 Creatio. All rights reserved. Odata web service (OData 4) | 35

Status: code

// Response body (available in GET and post requests). { "@odata.context": "http://Creatio_application_address/0/odata/$metadata#data_resource", "value": [ { "object1 field1": "object1 field_value1", "object1 field2": "object1 field_value2", ... }, { "object2 field1": "object2 field_value1", "object2 field2": "object2 field_value2", ... }, ... ] }

Request string

method required

Creatio supports the following request methods:

GET – retrieve data

POST – add data

PATCH – modify data

DELETE – delete data

Creatio_application_address required

Creatio application URL.

odata required

OData 4 protocol's web service URL. Unmodifiable part of the request.

objects_collection required

Name of the database table (the name of the object collection). Run the authentication and execute one of the requests to retrieve the list of database tables.

© 2021 Creatio. All rights reserved. Odata web service (OData 4) | 36

JSON

// The result will be received in JSON. GET Creatio_application_address/0/odata/

// Request headers. ForceUseSession: true BPMCSRF: authentication_cookie_value

XML

// The result will be received in XML. GET Creatio_application_address/0/odata/$metadata

// Request headers. ForceUseSession: true BPMCSRF: authentication_cookie_value

[SysSchema] table data

// The result will be received from the [SysSchema] database table in JSON. GET Creatio_application_address/0/odata/SysSchema?$filter=ManagerName eq 'EntitySchemaManager'

// Request headers. ForceUseSession: true BPMCSRF: authentication_cookie_value

object_id optional

Identifier of the database table record string (the identifier of the collection object instance).

object_field optional

Database table record field (the field of the collection object instance).

parameters optional

Optional OData 4 parameters you can use in the GET Creatio request string. Use the ? Operator to specify the parameters. Add the parameter name after the $ operator. Use the & operator to use two or more parameters.

© 2021 Creatio. All rights reserved. Odata web service (OData 4) | 37

Available parameters

$value The field value.

$count $count=true The number of elements in the selection.

$skip $skip=n The first n elements that must be excluded from the selection.

$top $top=n The first n elements that must be included in the selection.

$select $select=field1,field2,... A set of fields that must be included in the selection.

$orderby $orderby=field asc or How to sort the field values in the selection. $orderby=field desc

$expand $expand=field1,field2,... Extension of the connected fields.

$filter $filter=field template How to filter the fields in the selection. 'field_value'

Request headers

Accept application/json required

Data type to expect in the server response. Optional for GET requests.

Content-Type application/json; charset=utf-8; IEEE754Compatible=true required

Encoding and type of the resource passed in the request body. Optional for GET requests.

ForceUseSession true required

ForceUseSession header forces the use of an existing session.

BPMCSRF authentication_cookie_value required

Authentication cookie.

Request body

field1, field2, ... required

© 2021 Creatio. All rights reserved. Odata web service (OData 4) | 38

field1, field2, ... required

The field names passed in the request body.

value1, value2, ... required

Values of the field1, field2, … fields passed in the request body.

HTTP status code

code

Response status code.

Available status codes

200 OK A request that does not create a resource was completed successfully, and the resource's value does not equal 0. In this case, the response body should contain the value of the resource specified in the request URL. The information in the response depends on the request method: GET – the resource was found and passed in the response body.

POST – the resource with the description of server actions caused by the request was passed in the response body.

201 Created A request that creates a resource successfully. The response body should contain the created resource. Used for POST requests that create a collection, create a multimedia object (e. g., a photo), or call an action through import.

202 Accepted Data request processing has started but has not finished yet. There is no guarantee that the request will be completed successfully (asynchronous request processing).

204 No content The request was processed successfully, but there is no need to return any data. The value of the requested resource is 0. The response will pass only the headers, the response body should be empty.

3xx Redirection Redirection means the client must take further actions to execute the request. The response should contain the Location header with the URL that can be used to retrieve the result. The response can also contain the Retry-After header that displays time, in seconds. The time specifies how long the client can wait before executing another request to the resource in the Location header.

© 2021 Creatio. All rights reserved. Odata web service (OData 4) | 39 header.

304 Not modified The client executes a GET request with the If-None-Match header, and the content remains unchanged. The response should not contain any other headers.

403 Forbidden The request is correct, but the server refused to authorize it. This means the client lacks permissions to work with the resource. This may be caused by an invalid BPMCSRF cookie.

404 Not Found The server cannot find the resource specified in the URL. The response body may contain additional information.

405 Method Not Allowed The resource specified in the request URL does not support the specified request method. The response should contain the Allow header with the list of request methods the resource supports.

406 Not Acceptable The resource specified in the request URL does not have any current view that is acceptable for the client as per Accept , Accept-Charset , and Accept-Language request headers. The service does not provide a default view.

410 Gone The requested resource is no longer available. The resource had used the specified URL but was deleted and is no longer available.

412 Prediction Failed The client specified a request header condition the resource cannot process.

424 Failed Dependency The current request cannot be processed because the requested action depends on another action that could not be executed. The request has not been executed due to dependency failure.

501 Not Implemented The client is using a request method that is not implemented in OData 4 protocol and cannot be processed. The response body should contain the description of the unimplemented functionality.

Response body

@odata.context

Information about the type of the returned data. Besides the data source path, the data_resource element can contain the $entity parameter. This parameter indicates that the response returned a single instance of the collection object. Available only for GET and POST requests.

© 2021 Creatio. All rights reserved. EntityDataService.svc web service (OData 3) | 40

value

Contains the object collection. Not available if the response contains a single collection object instance. Available only for GET requests.

[]

Object collection. Available only for GET requests.

{}

Collection object instances. Available only for GET and POST requests.

object1 field1, object1 field2, ..., object2 field1, object2 field2, ...

The names of the field1, field2, … fields in the object1, object2, … collection object instances. Available only for GET and POST requests.

object1 field_value1, object1 field_value2, ..., object2 field_value1, object2 field_value2, ...

The values of the field1, field2, … fields in the object1, object2, … collection object instances. Available only for GET and POST requests. EntityDataService.svc web service (OData

3) A PI

Advanced

Depending on the request type, OData 3 protocol can return different data. Learn more about the request and response structure below.

Request structure

// Request string. method Creatio_application_address/0/ServiceModel/EntityDataService.svc/objects_collectionCollection

// Request headers. Accept: application/+xml; type=entry Content-Type: application/json; odata=verbose ForceUseSession: true BPMCSRF: authentication_cookie_value

// Request body (for POST and PATCH requests).

© 2021 Creatio. All rights reserved. EntityDataService.svc web service (OData 3) | 41

{ "field1": "value1", "field2": "value2", ... }

Response structure

// The status code. Status: code

// Response body (available in GET and POST requests). http://mycreatio.com/0/ServiceModel/EntityDataService.svc/data_resource data_resource date and time of request metadata_data object1 field_value1 object1 field_value2 ... metadata_data object2 field_value1 object2 field_value2 ... ...

Request string

© 2021 Creatio. All rights reserved. EntityDataService.svc web service (OData 3) | 42

method required

Creatio supports the following request methods:

GET – retrieve data

POST – add data

PATCH – modify data

DELETE – delete data

Creatio_application_address required

Creatio application URL.

ServiceModel required

OData 3 protocol’s web service URL. Unmodifiable part of the request.

EntityDataService.svc required

OData 3 protocol’s web service URL. Unmodifiable part of the request.

objects_collectionCollection required

Name of the database table (name of the object collection). When using the OData 3 protocol, add Collection to the first name of the object collection in the request string (e.g., ContactCollection ). Run a query to receive the list of database tables.

MySQL

SELECT * FROM INFORMATION_SCHEMA.TABLES

Oracle

SELECT * FROM ALL_TABLES

PostgreSQL

SELECT table_name FROM information_schema.tables

© 2021 Creatio. All rights reserved. EntityDataService.svc web service (OData 3) | 43

guid'object_id' optional

The identifier of the database table record string (identifier of the collection object instance). For example, guid'00000000-0000-0000-0000-000000000000' ).

object_field optional

The database table record field (field of the collection object instance).

parameters optional

Optional OData 3 parameters you can use in the GET Creatio request string. Use the ? operator to specify the parameters. Add the parameter name after the $ operator. Use the & operator to use two or more parameters.

Available parameters

$value The field value.

$count $count=true The number of elements in the selection.

$skip $skip=n The first n elements that must be excluded from the selection.

$top $top=n The first n elements that must be included in the selection.

$select $select=field1,field2,... The set of fields that must be included in the selection.

$orderby $orderby=field asc or How to sort the field values in the selection. $orderby=field desc

$expand $expand=field1,field2,... Extension of the connected fields.

$filter $filter=field template How to filter the fields in the selection. 'field_value'

Request headers

Accept application/atom+xml; type=entry required

Data type to expect in the server response. The server returns the response in XML. Optional for GET requests.

© 2021 Creatio. All rights reserved. EntityDataService.svc web service (OData 3) | 44

Content-Type application/json; odata=verbose required

Ecoding and type of the resource passed in the request body. Optional for GET requests.

ForceUseSession true required

The ForceUseSession header forces the use of an existing session. You do not need to use AuthService.svc in your request to the authentication service.

BPMCSRF authentication_cookie_value required

Authentication cookie.

Request body

field1, field2, ... required

The names of the fields passed in the request body.

value1, value2, ... required

The values of the field1, field2, … fields passed in the request body.

HTTP status code

code

Response status code.

Available status codes

© 2021 Creatio. All rights reserved. EntityDataService.svc web service (OData 3) | 45

200 OK GET , PUT , MERGE , or PATCH request was completed successfully. The response body should contain the value of the object or properly specified in the request URL.

201 Created POST request created an object or a link successfully. The response body should contain the updated object.

202 Accepted Processing of the data update request has started but has not finished yet. The response body should contain the Location header and the Retry-After header. The response body should be empty. The server should return the 303 response code with the Location header that contains the final URL that can be used to retrieve the result. The body and the header of the final URL should be formatted similar to the initial data update request.

204 No content Data update request. The value of the requested resource is 0. The response body should be empty.

3xx Redirection Data update request. The redirection means the client must take further actions to execute the request. The response should contain the Location header with the URL that can be used to retrieve the result.

4xx Client Error Incorrect requests. The server returns this code in response to client errors and requests to non-existent resources, such as entities, entity collections, or properties. If the response body is defined for the error code, the error body will be as defined for the corresponding format.

404 Not Found The object or collection specified in the URL does not exist. The response body should be empty.

Response body

entry

The instance of the collection object.

metadata_data

The metadata of the collection object instance.

object1 field1, object1 field2, ..., object2 field1, object2 field2, ...

The names of the field1, field2, … fields in the object1, object2, … collection object instances.

© 2021 Creatio. All rights reserved. DataService | 46

object1 field_value1, object1 field_value2, ..., object2 field_value1, object2 field_value2, ...

The values of the field1, field2, … fields in the object1, object2, … collection object instances. DataService

Advanced

The Creatio DataService web service is a RESTfull service. RESTful is a quite simple information management interface that doesn't use any additional internal layers, i.e., the data doesn't need to be converted to any third- party format, such as XML. In a simple RESTful service, each record is uniquely identified by a global identifier such as URL. Each URL, in turn, has a strictly specified format. However, this service is not always convenient for transferring large amounts of data. With the use of the DataService, the data can be automatically configured in various data formats such as XML, JSON, HTML, CSV, and JSV. The data structure is determined by data contracts. The full list and description of the DataService data contracts is displayed on table.

The Creatio application DataService services

Service Description

InsertQuery Add section record query class.

UpdateQuery Update section record query class.

DeleteQuery Delete section record query class.

SelectQuery Select section record query class.

BatchQuery Package query class.

Filters Filter class.

Resctrictions when using DataService When using DataService, take into account the following restrictions:

1. Maximum number of records that you can obtain by request is specified in the [ MaxEntityRowCount ] (the default value is 20000). You can change the system setting value in the .\Terrasoft.WebApp\Web.config file.

Attention. We do not recommend changing the [ MaxEntityRowCount ] system setting. This may lead to performance issues. We recommend using the page-oriented display implemented in the " IsPageable " and " RowCount " properties of the SelectQuery data contract.

2. The number of requests is unlimited.

© 2021 Creatio. All rights reserved. Add a button to create a new record in the [Contacts] section | 47

Add a button to create a new record in the [Contacts] section

Advanced

Example. Add to the [ Contacts ] section a button that when clicked invokes a method, using the InsertQuery class that adds a record with the following data:

Full name — John Best;

Full job title — Developer;

Business phone — +12 345 678 00 00.

Example implementation algorithm

1. Add button to the [ Contacts ] section For this particular case, you need to create a replacement client module of the [ Contacts ] section.

In the created client schema, add the InsertQueryContactButtonCaption localizable string, and set the "Add contact" value to it.

Add a configuration object with the button location settings to the diff array.

© 2021 Creatio. All rights reserved. Add a button to create a new record in the [Contacts] section | 48

diff

diff: /**SCHEMA_DIFF*/[ // Metadata to be added to the custom button section. { // The element is added to the page. "operation": "insert", // Parent interface element name to which the button is added. "parentName": "ActionButtonsContainer", // The button is added to the interface element collection // of the parent element (its metaname is specified in parentName). "propertyName": "items", // Added button metaname. "name": "InsertQueryContactButton", // Additional element properties. "values": { // Added element type — button. itemType: Terrasoft.ViewItemType.BUTTON, // Binding button caption to the localizable schema string. caption: { bindTo: "Resources.Strings.InsertQueryContactButtonCaption" }, // Binding method of processing the button click. click: { bindTo: "onInsertQueryContactClick" }, "layout": { "column": 1, "row": 6, "colSpan": 1 } } } ]/**SCHEMA_DIFF*/

2. Add the processing method for the button click event In order for a record with the necessary data to be added when a button created in the section is clicked, add the following method to the methods section of the replacement client schema:

methods

methods: { // Method of processing the button click. onInsertQueryContactClick: function() { // Creating the Terrasoft.InsertQuery class instance. var insert = Ext.create("Terrasoft.InsertQuery", { // Root schema name. rootSchemaName: "Contact" });

© 2021 Creatio. All rights reserved. Add a button to read records in the [Contacts] section | 49

// Setting the Terrasoft.ParameterExpression value-parameters. // A value-parameter instance is created and added to the column value collection. // Creating a value-parameter instance for the [Job title] column. insert.setParameterValue("Name", "John Best", Terrasoft.DataValueType.TEXT); // Creating a value-parameter instance for the [Business phone] column. insert.setParameterValue("Phone", "+12 345 678 00 00", Terrasoft.DataValueType.TEXT); // Creating a value-parameter instance for the [Job title] column. insert.setParameterValue("Job", "11D68189-CED6-DF11-9B2A-001D60E938C6", Terrasoft.DataValueType.GUID); // Data update query. insert.execute(function(response) { // Displaying server answer window.console.log(response); }); // Updating list data. this.reloadGridData(); } }

Attention. Unlike the previous example, authorization is not required because the code is executed directly in the Creatio application.

The implementation of the InsertQuery class for the client part of the application kernel is different from the implementation of the InsertQuery in its back end. So, to create the parameters, the setParameterValue method is used, and for the query execution — the execute method. Learn about all the available properties and methods of the InsertQuery class implemented in the kernel client part in the API documentation. Add a button to read records in the [Contacts] section

Advanced

Example. In the [ Contacts ] section, add a button which will open the method that will use DataService to read records in the [ Contacts ] section with the following columns:

Id ;

Full name ;

Number of activities — aggregate column, which displays the number of activities of this contact.

Example implementation algorithm

© 2021 Creatio. All rights reserved. Add a button to read records in the [Contacts] section | 50

1. Add a button in the [ Contacts ] section Create a replacing client module of the [ Contacts ] section.

In the created client schema, add SelectQueryContactButtonCaption localizable string and set its value to Select contacts.

Add a configuration object with the settings determining the button position to the diff array.

diff

//Setup of section button display. diff: /**SCHEMA_DIFF*/[ // Metadata for adding a custom button in a section. { // Indicates that an elementis added on a page. "operation": "insert", // Meta name of the parent control element where the button is added. "parentName": "ActionButtonsContainer", // Indicates that the button is added to the control element collection // of parent element (meta-name specified in parentName). "propertyName": "items", // Meta-name of the added button. "name": "SelectQueryContactButton", // Additional properties of the element. "values": { // Type of added element - button. itemType: Terrasoft.ViewItemType.BUTTON, // Binding button title to a schema localizable string.

© 2021 Creatio. All rights reserved. Add a button to read records in the [Contacts] section | 51

caption: { bindTo: "Resources.Strings.SelectQueryContactButtonCaption" }, // Binding of the button pressing handler method. click: { bindTo: "onSelectQueryContactClick" }, "layout": { "column": 1, "row": 6, "colSpan": 1 } } }

]/**SCHEMA_DIFF*/

2. Add handler method for the button pressing event

To enable reading the records when the button is clicked, add the following method to the methods section of the replacing client schema:

methods

methods: { // Handler method for button click. onSelectQueryContactClick: function() { // Creating an instance of the Terrasoft.InsertQuery class. var select = Ext.create("Terrasoft.EntitySchemaQuery", { // Root schema name. rootSchemaName: "Contact" }); // Adding the [Full name] column to query. select.addColumn("Name"); // Adding [Number of activities] aggregate column to a query. select.addAggregationSchemaColumn( // Path to column in relation to the root schema. "[Activity:Contact].Id", // Aggregation type — quantity. Terrasoft.AggregationType.COUNT, // Column title. "ActivitiesCount", // Aggregation function scope - for all elements. Terrasoft.AggregationEvalType.ALL); // Update query to server // Getting whole collection of records and displaying it in the browser console. select.getEntityCollection(function(result) { if (!result.success) { // Processing/logging of error. this.showInformationDialog("Data query error");

© 2021 Creatio. All rights reserved. Filter records in the [Contacts] section | 52

return; } // Displayed message. var message = ""; // Analyzing resulting collection and generating displayed message. result.collection.each(function(item) { message += "Full name: " + item.get("Name") + ". Number of activities: " + item.get("ActivitiesCount") + "\n"; }); // Displaying message in console. window.console.log(message); }, this); } }

Note. Unlike the previous example, authentication is not needed in this case, because the program code is executed by Creatio directly.

In the client of the application core, there is not a class like the server core SelectQuery class. To select data from a section, use the Terrasoft.EntitySchemaQuery class. For more information on this class methods and properties are described in the API documentation. Filter records in the [Contacts] section

Advanced

Example. Create a console application that will read the following data from the [ Contacts ] section using the DataService service:

Id ;

Full name ;

Number of activities is an aggregating column that shows the number of activities of this contact.

It is necessary to filter the data so that only those contacts whose number of activities is in the range of 1 to 3, and the [ Full name ] column value starting with "H" are read.

Example implementation algorithm

1. Сreate and configure a C# console application project that reads records To perform this step, you must perform the example of reading records in a third-party application.

© 2021 Creatio. All rights reserved. Filter records in the [Contacts] section | 53

The result of the query class implementation instance to read the records with the columns in an abbreviated form:

SelectQuery()

// Query class instance. var selectQuery = new SelectQuery () { // Root schema name. RootSchemaName = "Contact", // Adding columns to query. Columns = new SelectQueryColumns () { // Column collection. Items = new Dictionary () { // Column [Full name]. { // Key. "Name", // Value. new SelectQueryColumn () { // An expression that specifies the column type. Expression = new ColumnExpression () { // Expression type - schema column. ExpressionType = EntitySchemaQueryExpressionType.SchemaColumn, // Path to the column. ColumnPath = "Name" } } } // Column [Number of activities]. { "ActivitiesCount", new SelectQueryColumn () { Expression = new ColumnExpression () { // Expression - subquery. ExpressionType = EntitySchemaQueryExpressionType.SubQuery, // Path to the column relative to the root schema. ColumnPath = "[Activity: Contact] .Id", // Function type - aggregating. FunctionType = FunctionType.Aggregation, // Aggregation type - number. AggregationType = AggregationType.Count

© 2021 Creatio. All rights reserved. Filter records in the [Contacts] section | 54

} } } } } };

2. Add filter implementation

In order to filter data, you must create an instance of the Filters collection class instance, fill in the necessary properties, and then pass the link to this instance to the Filters property of the query class instance that you created in the previous step.

Filter collection class implementation example

// Query filters. var selectFilters = new Filters () { // Filter Type - group. FilterType = Terrasoft.Nui.ServiceModel.DataContract.FilterType.FilterGroup, // Filter collection. Items = new Dictionary { // Filter Implementation. } }; // Adding filter to query. selectQuery.Filters = selectFilters; // Query class instance serialization to read data from the JSON string. var json = new JavaScriptSerializer () Serialize (selectQuery).;

The Items property must contain the key-value type collection. The key is a string containing the filter name, and the value is an instance of the Filter class that contains a direct implementation of the filter.

To implement a filter that selects only those contacts that have a number of activities within a range of 1 to 3, you must add the following instance to the collection of filters:

Example of the instance to the collection of filters

// Filtration by activity. { // Key. "FilterActivities", // Value. new Filter {

© 2021 Creatio. All rights reserved. Filter records in the [Contacts] section | 55

// Filter type - range filter. FilterType = Terrasoft.Nui.ServiceModel.DataContract.FilterType.Between, // Comparison type - range. ComparisonType = FilterComparisonType.Between, // An expression to be tested. LeftExpression = new BaseExpression () { // Expression type - subquery. ExpressionType = EntitySchemaQueryExpressionType.SubQuery, // Path to the column relative to the root schema. ColumnPath = "[Activity: Contact] .Id", // Function type - aggregating. FunctionType = FunctionType.Aggregation, // Aggregation type - number. AggregationType = AggregationType.Count } // Filter range final expression. RightGreaterExpression = new BaseExpression () { // Expression type - parameter. ExpressionType = EntitySchemaQueryExpressionType.Parameter, // Expression parameter. Parameter = new Parameter () { // Parameter data type - integer. DataValueType = DataValueType.Integer, // Parameter value. Value = 3 } } // Filter range initial expression. RightLessExpression = new BaseExpression () { ExpressionType = EntitySchemaQueryExpressionType.Parameter, Parameter = new Parameter () { DataValueType = DataValueType.Integer, Value = 1 } } } }

Add the following instance to the filter collection to filter contact records where the [ Full name ] column value begins with "H":

Example of the instance to the filter collection

© 2021 Creatio. All rights reserved. Filter records in the [Contacts] section using a macro | 56

// Filtering by name. { // Key. "FilterName", // Value. new Filter { // Filter type - comparison filter. FilterType = Terrasoft.Nui.ServiceModel.DataContract.FilterType.CompareFilter, // Comparison type - starts with an expression. ComparisonType = FilterComparisonType.StartWith, // Expression to be tested. LeftExpression = new BaseExpression () { // Expression type - schema column. ExpressionType = EntitySchemaQueryExpressionType.SchemaColumn, // Path to the column. ColumnPath = "Name" } // Filtration expression. RightExpression = new BaseExpression () { // Expression type - parameter. ExpressionType = EntitySchemaQueryExpressionType.Parameter, // Expression parameter. Parameter = new Parameter () { // Parameter data type - text. DataValueType = DataValueType.Text, // Parameter value. Value = "CH" } } } }

Filter records in the [Contacts] section using a macro

Advanced

Example. Create a console application that uses DataService to read records from the [ Contacts ] section with the following columns:

Id ;

© 2021 Creatio. All rights reserved. Filter records in the [Contacts] section using a macro | 57

Full name ;

Birth date .

The data must be filtered, so that only contacts who were born in 1992 are shown.

Example implementation algorithm

1. Create and set up a C# application project that reads records To execute this step, execute the record reading example. The result of implementing an instance of query class for reading records:

SelectQuery()

// Instance of query class. var selectQuery = new SelectQuery() { // Root schema name. RootSchemaName = "Contact", // Adding columns to query. Columns = new SelectQueryColumns() { // Collection of columns. Items = new Dictionary() { //Column [Full name]. { // Key. "Name", // Value. new SelectQueryColumn() { // Expression that specifies the column type. Expression = new ColumnExpression() { // Type of expression - schema column. ExpressionType = EntitySchemaQueryExpressionType.SchemaColumn, // Pat to column. ColumnPath = "Name" } } }, // Column [Number of activities]. { "ActivitiesCount",

© 2021 Creatio. All rights reserved. Filter records in the [Contacts] section using a macro | 58

new SelectQueryColumn() { Expression = new ColumnExpression() { // Expression type — subquery. ExpressionType = EntitySchemaQueryExpressionType.SubQuery, // Path to column relative to the oot schema. ColumnPath = "[Activity:Contact].Id", // Function tyoe — aggregation. FunctionType = FunctionType.Aggregation, // Aggregation type — quantity. AggregationType = AggregationType.Count } } } } } };

2. Add a filter implementation with macros

To filter the data, create an instance of the Filters collection class, fill out the properties with corresponding values, and then pass the instance link to the Filters property of the query class created on the previous step.

An example of filter collection class implementation

// Query filters. var selectFilters = new Filters() { // Filter type — group. FilterType = Terrasoft.Nui.ServiceModel.DataContract.FilterType.FilterGroup, // Filter collection. Items = new Dictionary {

// Filter by year of birth. { // Key. "FilterYear", // Value. new Filter { // Filter type — comparison. FilterType = Terrasoft.Nui.ServiceModel.DataContract.FilterType.CompareFilter, // Comparison type — equal. ComparisonType = FilterComparisonType.Equal, // Expression to check.

© 2021 Creatio. All rights reserved. Filter records in the [Contacts] section using a macro | 59

LeftExpression = new BaseExpression() { // Expression type — schema column. ExpressionType = EntitySchemaQueryExpressionType.SchemaColumn, // Path to schema. ColumnPath = "BirthDate" }, // Expression with which the checked value is compared. RightExpression = new BaseExpression { // Expression type — function. ExpressionType = EntitySchemaQueryExpressionType.Function, // Function type — macro. FunctionType = FunctionType.Macros, // Macro type — year. MacrosType = EntitySchemaQueryMacrosType.Year, // Function argument. FunctionArgument = new BaseExpression { // Type of expression that determines the argument — parameter. ExpressionType = EntitySchemaQueryExpressionType.Parameter, // Parameter initialization. Parameter = new Parameter { // Parameter type — integer. DataValueType = DataValueType.Integer, // Parameter value. Value = "1992" } } } } } } }; // Adding filters to query. selectQuery.Filters = selectFilters; // Serialization of select query class instance in a JSON string. var json = new JavaScriptSerializer().Serialize(selectQuery);

The collection contains a single filter with the FilterYear key. Because only those records that have their year of birth equal to 1992 must be selected from the collection, the type of filter is set as a comparison filter. The type of comparison is set as an equality of values. As a verified expression, set the [ Date of birth ] column. Specify the macro function as the expression to compare with.

In this case using a macro is optimal because the birth date is stored in the database in YYYY-MM-DD format. The macro automatically determines the year value, so the developer does not need to write additional program code.

Because the EntitySchemaQueryMacrosType.Year macro is parametric, the FunctionArgument property must be

© 2021 Creatio. All rights reserved. Update a record in the [Contacts] section | 60

initialized and assigned a link to an instance of the BaseExpression class. In it, the integer parameter with value "1992" is defined. Update a record in the [Contacts] section

Advanced

Example. Create a console application that used DataService to update the "John Smith" record added in the example. Add "[email protected]" as the value in the [ Email ] column of this record.

Example implementation algorithm

1. Create and set up a C# application project Using the development environment (version 2017 and up), create a Visual C# console application project and specify project name, for example, DataServiceUpdateExample . Set ".NET Framework 4.7" for the project property Target framework .

In the References section of the project, add dependencies from the following libraries:

System.Web.Extensions.dll – class library included in .NET Farmework;

Terrasoft.Core.dll – library of base Creatio server core classes. It can be found using the following path: [Creatio setup catalog]\Terrasoft.WebApp\bin\Terrasoft.Core.dll ;

Terrasoft.Nui.ServiceModel.dll — application service class library. It can be found using the following path: [Creatio setup catalog]\Terrasoft.WebApp\bin\Terrasoft.Nui.ServiceModel.dll ;

Terrasoft.Common.dll – library of base Creatio server core classes. It can be found using the following path: [Creatio setup catalog]\Terrasoft.WebApp\bin\Terrasoft.Common.dll .

Add the using directives to the application source code file:

Adding the using directives

using System; using System.Text; using System.IO; using System.Net; using System.Collections.Generic; using Terrasoft.Nui.ServiceModel.DataContract; using Terrasoft.Core.Entities; using System.Web.Script.Serialization; using Terrasoft.Common;

© 2021 Creatio. All rights reserved. Update a record in the [Contacts] section | 61

2. Add fields and constants and field declarations to the source code To access DataService features, add the fields and constants to the application source code.

Adding the fields and constants

// Primary URL of Creatio application. Must be repoaced with a custom one. private const string baseUri = @"http://example.creatio.com"; // Request string to the Login methid of the AuthService.svc service. private const string authServiceUri = baseUri + @"/ServiceModel/AuthService.svc/Login"; // Path string for the UpdateQuery. private const string updateQueryUri = baseUri + @"/0/DataService/json/reply/UpdateQuery"; // Creatio authentication cookie. private static CookieContainer AuthCookie = new CookieContainer();

Here, three string fields are declared. These fields will be used to form authentication query and read data queries execution paths. Authentication data will be saved in the AuthCookie field.

3. Add method that performs Creatio application authentication аAuthentication is required to enable access to the DataService for the created application.

4. Add implementation of the record add query

Because the updateQueryUri constant declared earlier contains a path for sending data in the JSON format, sent data must be configured beforehand as a string that contains a JSON object that corresponds to the UpdateQuery data contract. This can be done directly in a string variable, although a much more secure and convenient way of doing this would be to create an instance of the UpdateQuery class, fill out its properties and then serialize it to a string.

Implementation the request for adding a record

// Instance of the request class. var updateQuery = new UpdateQuery() { // Root schema name. RootSchemaName = "Contact", // New column values. ColumnValues = new ColumnValues() { // Key-value collection. Items = new Dictionary() { // [Email] column. { // key.

© 2021 Creatio. All rights reserved. Update a record in the [Contacts] section | 62

"Email", // Value — instance of object schema request class. // Configuration of [Email] column. new ColumnExpression() { // Type of expression of obkect schema query — parameter. ExpressionType = EntitySchemaQueryExpressionType.Parameter, // Query expression parameter. Parameter = new Parameter() { // Parameter value. Value = "[email protected]", // Parameter data type — string. DataValueType = DataValueType.Text } } } } }, // Query filters. Filters = new Filters() { // Filter type — group. FilterType = Terrasoft.Nui.ServiceModel.DataContract.FilterType.FilterGroup, // Filter collection. Items = new Dictionary() { // Filter by name. { // Key. "FilterByName", // Value. new Filter { // Filter type — comparison filter. FilterType = Terrasoft.Nui.ServiceModel.DataContract.FilterType.CompareFilter, // Comparison type — starts with expression. ComparisonType = FilterComparisonType.Equal, // Expression to check. LeftExpression = new BaseExpression() { // Expression type - schema column. ExpressionType = EntitySchemaQueryExpressionType.SchemaColumn, // Path to column. ColumnPath = "Name" }, // Filtering expression. RightExpression = new BaseExpression() {

© 2021 Creatio. All rights reserved. Update a record in the [Contacts] section | 63

// Expression type - parameter. ExpressionType = EntitySchemaQueryExpressionType.Parameter, // Expression parameter. Parameter = new Parameter() { // Parameter data type - text. DataValueType = DataValueType.Text, // Parameter value. Value = "John Smith" } } } } } } }; // Serialization of update query class instance in a JSON string. var json = new JavaScriptSerializer().Serialize(updateQuery);

Here, an instance of the UpdateQuery class is created. In the ColumnValues property, the "[email protected]" value is set for the [ Email ] column. To apply this value to a specific record or group of records, specify a link to a correctly initialized Filters class in the Filters property. In this case, a single filter is added to the filters collection to select only records that have the "John Smith" value in the [ Full name ] column.

The next step is to execute DataService POST -query. To do this, create an instance of the < HttpWebRequest class, fill its properties and connect the string with the JSON object created earlier then execute the DataService query and process its result. To do this, add the following source code:

Request implementation

// Converting a JSON object string to a byte array. byte[] jsonArray = Encoding.UTF8.GetBytes(json); // Creating an insrance of HTTP request. var updateRequest = HttpWebRequest.Create(updateQueryUri) as HttpWebRequest; // Defining a request method. updateRequest.Method = "POST"; // Determining type of request content. updateRequest.ContentType = "application/json"; // Adding authentication cookie received earlier to a request. updateRequest.CookieContainer = AuthCookie; // Set length for request content. updateRequest.ContentLength = jsonArray.Length;

// Putting BPMCSRF token to the request header. CookieCollection cookieCollection = AuthCookie.GetCookies(new Uri(authServiceUri)); string csrfToken = cookieCollection["BPMCSRF"].Value; updateRequest.Headers.Add("BPMCSRF", csrfToken);

© 2021 Creatio. All rights reserved. Delete a record in the [Contacts] section | 64

// Plase a JSON-object to request content. using (var requestStream = updateRequest.GetRequestStream()) { requestStream.Write(jsonArray, 0, jsonArray.Length); } // Executing HTTP request and getting a response from server. using (var response = (HttpWebResponse)updateRequest.GetResponse()) { // Displaying response in console. using (StreamReader reader = new StreamReader(response.GetResponseStream())) { Console.WriteLine(reader.ReadToEnd()); } }

Delete a record in the [Contacts] section

Advanced

Example. Create a console application that, using the DataService service, will delete the "John Best" contact record added in the example.

Example implementation algorithm

1. Сreate and configure a C# console application project Using the Microsoft Visual Studio (version 2017 and up) development environment, create a Visual C# console application project and name it DataServiceDeleteExample. The Target framework project property must be set to .NET Framework 4.7.

In the References section of the project you need to add dependencies of the following libraries:

System.Web.Extensions.dll is a class library included in the .NET Farmework

Terrasoft.Core.dll is a main class library of the application server kernel. Can be found by the following path: [Directory with the installed application]\Terrasoft.WebApp\bin\Terrasoft.Core.dll

Terrasoft.Nui.ServiceModel.dll class library the application services. Can be found by the following path: [Directory with the application installed]\Terrasoft.WebApp\bin\Terrasoft.Nui.ServiceModel.dll .

Terrasoft.Common.dll is a main class library of the application server kernel. Can be found by the following path: [Directory with the installed application]\Terrasoft.WebApp\bin\Terrasoft.Common.dll .

Add using directives to the application source code file:

© 2021 Creatio. All rights reserved. Delete a record in the [Contacts] section | 65

Adding using directives

using System; using System.Text; using System.IO; using System.Net; using System.Collections.Generic; using Terrasoft.Nui.ServiceModel.DataContract; using Terrasoft.Core.Entities; using System.Web.Script.Serialization; using Terrasoft.Common;

2. Add field declarations and constants to the application source code To access the DataService features, you must add the fields and constants to the application source code.

Adding the fields and constants

// Main Creatio URL. Has to be changed to a custom one. private const string baseUri = @"http://example.creatio.com"; // Query string to the Login method of the AuthService.svc service. private const string authServiceUri = baseUri + @"/ServiceModel/AuthService.svc/Login"; // DeleteQuery query path string. private const string deleteQueryUri = baseUri + @"/0/DataService/json/reply/DeleteQuery"; // Creatio cookie authentication. private static CookieContainer AuthCookie = new CookieContainer();

Three string constant fields that are used to carry out the authentication requests and requests to read data are declared here. The authentication data will be stored in the AuthCookie field.

3. Add a method that performs authentication in the Creatio application You need to authenticate the newly created application to access the DataService web service.

4. Implement a query to add a record

As the previously declared updateQueryUri constant contains the path for sending data in JSON format, the data sent must be pre-configured in the form of a string containing a description of the JSON object corresponding to the UpdateQuery data contract. This can be done directly in a lowercase variable but it is much easier and safer to create an instance of the UpdateQuery class, fill its properties, and then serialize it to a string.

Implementation the request to adding a record

// Query class instance.

© 2021 Creatio. All rights reserved. Delete a record in the [Contacts] section | 66

var deleteQuery = new DeleteQuery() { // Root schema name. RootSchemaName = "Contact", // Query filters. Filters = new Filters() { // Filter type — group. FilterType = Terrasoft.Nui.ServiceModel.DataContract.FilterType.FilterGroup, // Filter collection. Items = new Dictionary() { // Filtration by name. { // Key. "FilterByName", // Value. new Filter { // Filter type — comparison filter. FilterType = Terrasoft.Nui.ServiceModel.DataContract.FilterType.CompareFilter, // Comparison type — starts with an expression. ComparisonType = FilterComparisonType.Equal, // Expression to be checked. LeftExpression = new BaseExpression() { // Expression type — schema column. ExpressionType = EntitySchemaQueryExpressionType.SchemaColumn, // Column path. ColumnPath = "Name" }, // Filtration expression. RightExpression = new BaseExpression() { // Expression type — parameter. ExpressionType = EntitySchemaQueryExpressionType.Parameter, // Expression parameter. Parameter = new Parameter() { // Parameter data type — text. DataValueType = DataValueType.Text, // Parameter value. Value = "John Best" } } } } }

© 2021 Creatio. All rights reserved. Delete a record in the [Contacts] section | 67

} }; // Class instance serialization of the JSON string adding query. var json = new JavaScriptSerializer().Serialize(updateQuery);

This creates an instance of the DeleteQuery class. The Contact value is set in the RootSchemaName property. To delete a particular record or group of records, you need to set a link to the correctly initialized Filters class instance to the Filters property. In this case, a single filter that selects only records with the John Best value in the [ Full name ] column is added to the filter collection.

In the final step you must perform POST query to the DataService service. To do this, create an instance of the HttpWebRequest class, fill in its properties, attach a previously created string with the JSON object to a request, and then execute and process the result of the query to the DataService service. To do this, add the following source code:

Request implementation

// Converting a JSON object string to a byte array. byte[] jsonArray = Encoding.UTF8.GetBytes(json); // Creating an insrance of HTTP request. var updateRequest = HttpWebRequest.Create(updateQueryUri) as HttpWebRequest; // Defining a request method. updateRequest.Method = "POST"; // Determining type of request content. updateRequest.ContentType = "application/json"; // Adding authentication cookie received earlier to a request. updateRequest.CookieContainer = AuthCookie; // Set length for request content. updateRequest.ContentLength = jsonArray.Length;

// Putting BPMCSRF token to the request header. CookieCollection cookieCollection = AuthCookie.GetCookies(new Uri(authServiceUri)); string csrfToken = cookieCollection["BPMCSRF"].Value; updateRequest.Headers.Add("BPMCSRF", csrfToken);

// Plase a JSON-object to request content. using (var requestStream = updateRequest.GetRequestStream()) { requestStream.Write(jsonArray, 0, jsonArray.Length); } // Executing HTTP request and getting a response from server. using (var response = (HttpWebResponse)updateRequest.GetResponse()) { // Displaying response in console. using (StreamReader reader = new StreamReader(response.GetResponseStream())) { Console.WriteLine(reader.ReadToEnd());

© 2021 Creatio. All rights reserved. Add and update a record in the [Contacts] section | 68

} }

Add and update a record in the [Contacts] section

Advanced

Example. Create a console application that will use DataService to:

add a contact record with the value "John Smith" in the [ Full name ] column;

change the value of the [ Business phone ] column to 012 345 67 89 for all contact records that have "John Smith" as the value in the [ Full name ].

Records must be added and modified via a batch query.

Example implementation algorithm

1. Create and set up a C# application project Using the Microsoft Visual Studio development environment (version 2017 and up), create a Visual C# console application project and specify the project name, for example, DataServiceBatchExample . Set ".NET Framework 4.7" for the project property Target framework .

In the References section of the project, add dependencies from the following libraries:

System.Web.Extensions.dll – class library included in .NET Framework;

Terrasoft.Core.dll – library of base Creatio server core classes. It can be found using the following path: [Creatio setup catalog]\Terrasoft.WebApp\bin\Terrasoft.Core.dll ;

Terrasoft.Nui.ServiceModel.dll — application service class library. It can be found using the following path: [Creatio setup catalog]\Terrasoft.WebApp\bin\Terrasoft.Nui.ServiceModel.dll ;

Terrasoft.Common.dll – library of base Creatio server core classes. It can be found using the following path: [Creatio setup catalog]\Terrasoft.WebApp\bin\Terrasoft.Common.dll .

Add the using directives to the application source code file.

Adding the using directives

using System; using System.Text; using System.IO; using System.Net;

© 2021 Creatio. All rights reserved. Add and update a record in the [Contacts] section | 69

using System.Collections.Generic; using Terrasoft.Nui.ServiceModel.DataContract; using Terrasoft.Core.Entities; using System.Web.Script.Serialization; using Terrasoft.Common;

2. Add fields and constants and field declarations to the source code To access DataService features, add the fields and constants to the application source code.

Adding the fields and constants

// Primary URL of Creatio application. Must be replaced with a custom one. private const string baseUri = @"http://example.creatio.com"; // Request string to the Login methid of the AuthService.svc service. private const string authServiceUri = baseUri + @"/ServiceModel/AuthService.svc/Login"; // Path string for the BatchQuery. private const string batchQueryUri = baseUri + @"/0/DataService/json/reply/BatchQuery"; // Creatio authentication cookie. private static CookieContainer AuthCookie = new CookieContainer();

Here, three string fields are declared. These fields will be used to form authentication query and read data queries execution paths. Authentication data will be saved in the AuthCookie field.

3. Add method that performs Creatio application authentication Authentication is required to enable access of the created application to the DataService.

4. Implement query adding request

Because the batchQueryUri constant declared previously earlier contains a path for sending data in the JSON format, sent data must be configured beforehand as a string that contains a JSON object description. Use data contract classes to create separate queries then serialize them in a string.

For a query to add a contact record with the name "John Smith", add the following program code:

Implementation the request for adding a record

// Insert query. var insertQuery = new InsertQuery() { RootSchemaName = "Contact", ColumnValues = new ColumnValues() { Items = new Dictionary() {

© 2021 Creatio. All rights reserved. Add and update a record in the [Contacts] section | 70

{ "Name", new ColumnExpression() { ExpressionType = EntitySchemaQueryExpressionType.Parameter, Parameter = new Parameter { Value = "John Smith", DataValueType = DataValueType.Text } } } } } };

To change the value of the [ Business phone ] column to 012 345 67 89 for all contact records that have "John Smith" value in the [ Full name ] column, add the code.

Implementation the request for updating a record

// Update query. var updateQuery = new UpdateQuery() { RootSchemaName = "Contact", ColumnValues = new ColumnValues() { Items = new Dictionary() { { "Phone", new ColumnExpression() { ExpressionType = EntitySchemaQueryExpressionType.Parameter, Parameter = new Parameter() { Value = "0123456789", DataValueType = DataValueType.Text } } } } }, Filters = new Filters() { FilterType = Terrasoft.Nui.ServiceModel.DataContract.FilterType.FilterGroup, Items = new Dictionary()

© 2021 Creatio. All rights reserved. Add and update a record in the [Contacts] section | 71

{ { "FilterByName", new Filter { FilterType = Terrasoft.Nui.ServiceModel.DataContract.FilterType.CompareFilter, ComparisonType = FilterComparisonType.Equal, LeftExpression = new BaseExpression() { ExpressionType = EntitySchemaQueryExpressionType.SchemaColumn, ColumnPath = "Name" }, RightExpression = new BaseExpression() { ExpressionType = EntitySchemaQueryExpressionType.Parameter, Parameter = new Parameter() { DataValueType = DataValueType.Text, Value = "John Smith" } } } } } } };

After serializing the created instances of the query class, add information about the qualified name of the corresponding data contract to the strings with JSON objects. Compose the string with batch query.

Batch query

// Serialization of update query class instance in a JSON string. var jsonInsert = new JavaScriptSerializer().Serialize(insertQuery); // Inserting query type in a JSON string. jsonInsert = jsonInsert.Insert(1, @"""__type"": ""Terrasoft.Nui.ServiceModel.DataContract.InsertQuery""," // Serialization of instance of the update query class in a JSON string. var jsonUpdate = new JavaScriptSerializer().Serialize(updateQuery); // Inserting query type in a JSON string. jsonUpdate = jsonUpdate.Insert(1, @"""__type"": ""Terrasoft.Nui.ServiceModel.DataContract.UpdateQuery""," // Creating batch query. var json = @"{""items"": [" + jsonInsert + "," + jsonUpdate + "]}";

The next step is to execute the POST DataService query. To do this, create an instance of the HttpWebRequest class, fill its properties and connect the string with JSON object, created earlier, then execute the DataService query and process its result. To do this, add the source code.

© 2021 Creatio. All rights reserved. InsertQuery class | 72

Request implementation

// Converting a JSON object string in a byte array. byte[] jsonArray = Encoding.UTF8.GetBytes(json); // Creating an instance of HTTP request. var batchRequest = HttpWebRequest.Create(deleteQueryUri) as HttpWebRequest; // Defining request method. batchRequest.Method = "POST"; // Determining request content. batchRequest.ContentType = "application/json"; // Adding authentication cookie received earlier to a query. batchRequest.CookieContainer = AuthCookie; // Set the ContentLength property of the WebRequest. batchRequest.ContentLength = jsonArray.Length;

// Adding CSRF token to the request header. CookieCollection cookieCollection = AuthCookie.GetCookies(new Uri(authServiceUri)); string csrfToken = cookieCollection["BPMCSRF"].Value; batchRequest.Headers.Add("BPMCSRF", csrfToken);

// Adding JSON object to the query contents. using (var requestStream = batchRequest.GetRequestStream()) { requestStream.Write(jsonArray, 0, jsonArray.Length); } // Executing HTTP request and getting reply from server. using (var response = (HttpWebResponse)batchRequest.GetResponse()) { // Displaying response in console. using (StreamReader reader = new StreamReader(response.GetResponseStream())) { Console.WriteLine(reader.ReadToEnd()); } } // Application execution delay. Console.ReadKey();

InsertQuery class C#

Advanced

The Namespace Terrasoft.Nui.ServiceModel.DataContract .

The InsertQuery data contract is used to add records to sections. The data is transferred to the DataService via HTTP by using the POST request with the URL.

© 2021 Creatio. All rights reserved. InsertQuery class | 73

The structure of request for adding data

// URL format of the POST query to add data to DataService. http(s)://[Creatio application address]/[Configuration number]/dataservice/[Data fromat]/reply/InsertQuery

An example the request for adding data

// URL example for the POST query to add data to DataService. http(s)://example.creatio.com/0/dataservice/json/reply/InsertQuery

The InsertQuery data contract has a hierarchical structure with multiple nesting levels. In the Creatio application server part, the InsertQuery data contract is represented by the InsertQuery class of the Terrasoft.Nui.ServiceModel.DataContract namespace of the Terrasoft.Nui.ServiceModel.dll class library. However, for simplicity, the hierarchical structure of the InsertQuery data contract is conveniently presented as a JSON format object:

Structure of the InsertQuery data contract

{ "RootSchemaName":"[Root object schema name]", "OperationType":[Record operation type], "ColumnValues":{ "Items":{ "Added column name":{ "ExpressionType":[Expression type], "Parameter":{ "DataValueType":[Data type], "Value":"[Column value]" } }... } } }

Properties

RootSchemaName

A string containing the name of the root object schema of the added record.

OperationType

© 2021 Creatio. All rights reserved. InsertQuery class | 74

Operation type is set by the QueryOperationType namespace Terrasoft.Nui.ServiceModel.DataContract namespace enumeration value. For the InsertQuery the QueryOperationType.Insert value is set.

Possible values ( QueryOperationType )

Select 0

Insert 1

Update 2

Delete 3

Batch 4

ColumnValues

Contains a collection of column values of the added record. Its ColumnValues type is defined in the Terrasoft.Nui.ServiceModel.DataContract namespace.<

The ColumnValues class C#

The Namespace Terrasoft.Nui.ServiceModel.DataContract .

The ColumnValues class has a single Items property that is defined as a collection of the Dictionary keys and values. The key is a string with the added column title, and the value is the object with the ColumnExpression type defined in the Terrasoft.Nui.ServiceModel.DataContract namespace. The basic properties of the ColumnExpression class used when adding records, are given in table.

Properties

ExpressionType

The expression type that defines the value that will be contained in the added column. Set by the EntitySchemaQueryExpressionType enumeration of the Terrasoft.Core.Entities namespace defined in the Terrasoft.Core class library. For the InsertQuery the EntitySchemaQueryExpressionType.Parameter value is set.

Possible values ( EntitySchemaQueryExpressionType )

© 2021 Creatio. All rights reserved. InsertQuery class | 75

SchemaColumn 0 Schema column.

Function 1 Function.

Parameter 2 Parameter.

SubQuery 3 Subquery.

ArithmeticOperation 4 Arithmetic operation.

Parameter

Defines the value that will be contained in the added column. Its Parameter type is defined in the Terrasoft.Nui.ServiceModel.DataContract namespace.

The Parameter class C#

The Namespace Terrasoft.Nui.ServiceModel.DataContract .

The Parameter class has multiple properties, two of which are used to add records.

Properties

DataValueType

The data value type that defines the value that will be contained in the added column. Set by the DataValueType enumeration value of the Terrasoft.Nui.ServiceModel.DataContract namespace.

Possible values ( DataValueType )

© 2021 Creatio. All rights reserved. SelectQuery class | 76

Guid 0

Text 1

Integer 4

Float 5

Money 6

DateTime 7

Date 8

Time 9

Lookup 10

Enum 11

Boolean 12

Blob 13

Image 14

ImageLookup 16

Mapping 18

Value

The object that contains the added column value.

SelectQuery class C#

Advanced

The Namespace Terrasoft.Nui.ServiceModel.DataContract .

The SelectQuery data contract is used for reading section records. The query data is transferred to DataService via HTTP, with the help of POST by the URL.

The structure of request for reading data

© 2021 Creatio. All rights reserved. SelectQuery class | 77

// URL format of the POST query to read data from DataService. http(s)://[Creatio application address]/[Configuration number]/dataservice/[Data fromat]/reply/SelectQuery

An example the request for reading data

// URL example of the POST query to read data from DataService. http(s)://example.creatio.com/0/dataservice/json/reply/SelectQuery

The SelectQuery data contract has a complex hierarchical structure with a number of nesting levels. In the Creatio server core, it is represented by a SelectQuery class of the Terrasoft.Nui.ServiceModel.DataContract namespace of the Terrasoft.Nui.ServiceModel.dll library of classes. The hierarchical data structure of the SelectQuery data contract can be conveniently viewed in JSON format:

Structure of the SelectQuery data contract

{ "RootSchemaName":"[Object root schema name]", "OperationType":[Type of record operation], "Columns":{ "Items":{ "Name":{ "OrderDirection":[Sorting order], "OrderPosition":[Column position], "Caption":"[Title]", "Expression":{ "ExpressionType":[Expression type], "ColumnPath":"[Path to column]", "Parameter":[Parameter], "FunctionType":[Function type], "MacrosType":[Macro type], "FunctionArgument":[Function argument], "DatePartType":[Type of date part], "AggregationType":[Aggregation type], "AggregationEvalType":[Aggregation scope], "SubFilters":[Buit-in filters] } } } }, "AllColumns":[Indicates that all columns are selected], "ServerESQCacheParameters":{ "CacheLevel":[Caching level], "CacheGroup":[Caching group], "CacheItemName":[Record key in repository] },

© 2021 Creatio. All rights reserved. SelectQuery class | 78

"IsPageable":[Indicates page-by-page], "IsDistinct":[Indicates uniqueness], "RowCount":[Number of selected records], "ConditionalValues":[Conditions for building a pageable query], "IsHierarchical":[Indicates hierarchical data selection], "HierarchicalMaxDepth":[Maximum nesting level of the hierarchical query], "HierarchicalColumnName":[Column name used to create hierarchical query], "HierarchicalColumnValue":[Initial value of hierarchical column], "Filters":[Filters] } }

Properties

RootSchemaName string

String that contains root schema name of the added record object.

OperationType QueryOperationType

Type of write operation. Specified as a QueryOperationType enumeration value of the Terrasoft.Nui.ServiceModel.DataContract namespace. The QueryOperationType.Select value is set for SelectQuery .

Possible values ( QueryOperationType )

Select 0

Insert 1

Update 2

Delete 3

Batch 4

Columns SelectQueryColumns

Contains a collection of the record columns being read. It has the SelectQueryColumns type defined in the Terrasoft.Nui.ServiceModel.DataContract namespace. It must be configured if the AllColumns checkbox is set to false and a set of specific root schema columns, which does not include the [ Id ] column, is required.

AllColumns bool

© 2021 Creatio. All rights reserved. SelectQuery class | 79

Indicates if all columns are selected. If the value is set to true , all columns of the root schema will be selected by the query.

ServerESQCache Parameters

Parameters of EntitySchemaQuery caching on server. The ServerESQCacheParameters type is defined in the Terrasoft.Nui.ServiceModel.DataContract namespace.

IsPageable bool

Indicates whether the data is selected page-by-page.<

IsDistinct bool

Indicates whether duplicates must be eliminated in the resulting data set.

RowCount int

Number of selected strings. By default, the value is -1, i.e. all strings are selected.

ConditionalValues ColumnValues

Conditions of creating a page-by-page query. The ColumnValues type is defined in the Terrasoft.Nui.ServiceModel.DataContract namespace.

IsHierarchical bool

Indicates whether the data is selected hierarchically.

HierarchicalMaxDepth int

Maximum nesting level of a hierarchical query.

hierarchicalColumnName string

Name of the column used for creating a hierarchical query.

hierarchicalColumnValue string

Initial value of hierarchical column from which the hierarchy will be built.

Filters Filters

© 2021 Creatio. All rights reserved. SelectQuery class | 80

Collection of query filters. The Filters type is defined in the Terrasoft.Nui.ServiceModel.DataContract namespace.

ColumnValues ColumnValues

Contains collection of column values for the added record. The ColumnValues type is defined in the Terrasoft.Nui.ServiceModel.DataContract namespace.

The SelectQueryColumns class C#

The Namespace Terrasoft.Nui.ServiceModel.DataContract .

The SelectQueryColumns class has a single Items property, defined as a collection of keys and values Dictionary . The key is the string with the name of the added column. The value is an instance of the SelectQueryColumn class, defined in the Terrasoft.Nui.ServiceModel.DataContract namespace. The properties of the SelectQueryColumn are available in the table.

Properties

OrderDirection OrderDirection

Sorting order. Specified with a value from the OrderDirection enumeration of the Terrasoft.Common name space defined in the Terrasoft.Common class library.

OrderPosition int

Sets position number in the collection of the query columns, by which the sorting is done.

Caption string

Column title.

Expression ColumnExpression

Property that defines expression of the type of selected column.

The ColumnExpression class C#

The Namespace Terrasoft.Nui.ServiceModel.DataContract .

The ColumnExpression class defines expression that sets the type of the schema column. The class is defined in the Terrasoft.Nui.ServiceModel.DataContract namespace of the Terrasoft.Nui.ServiceModel library. The properties of an instance of this class are filled in depending on the ExpressionType property, which sets the expression type. The full list of the ColumnExpression class properties is available in table.

© 2021 Creatio. All rights reserved. SelectQuery class | 81

Properties

ExpressionType EntitySchemaQuery ExpressionType

Type of expression that determines the value that the added column will contain. Specified with a value from the ntitySchemaQueryExpressionType enumeration of the Terrasoft.Core.Entities namespace defined in the Terrasoft.Core class library. The EntitySchemaQueryExpressionType.Parameter value is set for InsertQuery .

Possible values ( EntitySchemaQueryExpressionType )

SchemaColumn 0 Schema column.

Function 1 Function.

Parameter 2 Parameter.

SubQuery 3 Subquery.

ArithmeticOperation 4 Arithmetic operation.

ColumnPath string

Path to the column in relation to the root schema. Rules for building paths are available in the Build path to columns article.

Parameter Parameter

Determines the value that the added column will contain. The Parameter type is defined in the Terrasoft.Nui.ServiceModel.DataContract namespace.

FunctionType FunctionType

Function type. Specified with a value from the FunctionType enumeration, which is defined in the Terrasoft.Nui.ServiceModel.DataContract namespace.

Possible values ( FunctionType )

© 2021 Creatio. All rights reserved. SelectQuery class | 82

None 0 Not defined.

Macros 1 Macro.

Aggregation 2 Aggregate function.

DatePart 3 Part of date value.

Length 4 Length.

MacrosType EntitySchemaQuery MacrosType

Macro type. Specified with a value of the EntitySchemaQueryMacrosType enumeration, which is defined in the Terrasoft.Core.Entities namespace.

FunctionArgument BaseExpression

Function argument. Accepts a value if the function is defined with a parameter. The BaseExpression class is defined in the Terrasoft.Nui.ServiceModel.DataContract namespace, is an ancestor for the ColumnExpresion class and has the same set of properties.

DatePartType DatePart

Part of date value Specified with a value from the DatePart enumeration, which is defined in the Terrasoft.Nui.ServiceModel.DataContract namespace.

Possible values ( DatePart )

None 0 Not defined.

Day 1 Day.

Week 2 Week.

Month 3 Month

Year 4 Year.

Weekday 5 Week day.

Hour 6 Hour.

HourMinute 7 Minute.

© 2021 Creatio. All rights reserved. SelectQuery class | 83

AggregationType AggregationType

Aggregate function type. Specified with a value from the AggregationType enumeration defined in the Terrasoft.Common namespace defined in the Terrasoft.Common class library.

AggregationEvalType AggregationEvalType

Aggregate function scope. Specified with a value from the AggregationEvalType enumeration defined in the Terrasoft.Common namespace defined in the Terrasoft.Common class library.

SubFilters Filters

Collection of subquery filters. The Filters type is defined in the Terrasoft.Nui.ServiceModel.DataContract namespace.

The Parameter class C#

The Namespace Terrasoft.Nui.ServiceModel.DataContract .

The Parameter class is defined in the Terrasoft.Nui.ServiceModel.DataContract namespace. Its properties are available in table.

Properties

DataValueType DataValueType

Type of data for the value that the added column will contain. Specified as a DataValueType enumeration value of the Terrasoft.Nui.ServiceModel.DataContract namespace.

Possible values ( DataValueType )

© 2021 Creatio. All rights reserved. SelectQuery class | 84

Guid 0

Text 1

Integer 4

Float 5

Money 6

DateTime 7

Date 8

Time 9

Lookup 10

Enum 11

Boolean 12

Blob 13

Image 14

ImageLookup 16

Mapping 18

Value object

The object that contains the value of the added column.

ArrayValue string[]

Array of the added column values. Used when serializing arrays and BLOBs.

ShouldSkipConvertion bool

Indicates the need to skip the process of providing the type for the Value property.

The ServerESQCacheParameters class C#

© 2021 Creatio. All rights reserved. Filters class | 85

The Namespace Terrasoft.Nui.ServiceModel.DataContract .

The ServerESQCacheParameters class is defined in the Terrasoft.Nui.ServiceModel.DataContract namespace. Its properties are available in table.

Properties

CacheLevel int

Data allocation level in the EntitySchemaQuery cache.

CacheGroup string

Caching group.

CacheItemName string

Repository record key.

The Filters class is defined in the Terrasoft.Nui.ServiceModel.DataContract namespace. For details on the properties of this class and its use, please see the Filters class article.

Filters class C#

Advanced

During the execution of DataService operations, it is often necessary to filter data. For example, when reading section records, you need to fetch only those records that meet certain criteria. Creatio provides the Filters class to form these criteria.

The Filters class C#

The Namespace Terrasoft.Nui.ServiceModel.DataContract .

The Filters class is defined in the Terrasoft.Nui.ServiceModel.DataContract namespace of the Terrasoft.Nui.ServiceModel.dll class library. For simplicity, the hierarchical structure of the Filters data filter is conveniently presented as a JSON format object:

Structure of the Filters data filter

"Filters":{ "RootSchemaName":["Root schema name"], "FilterType":[Filter type], "ComparisonType":[Comparison type], "LogicalOperation":[Logical operation], "IsNull":[Completeness checkbox],

© 2021 Creatio. All rights reserved. Filters class | 86

"IsEnabled":[Activation checkbox], "IsNot":[Negation operator checkbox], "SubFilters":[Subquery filters], "Items":[Filter group collection], "LeftExpression":[Expression to be checked], "RightExpression":[Filtration expression], "RightExpressions":[Filtration expressions array], "RightLessExpression":[Initial filtration range expression], "RightGreaterExpression":[Final filtration range expression], "TrimDateTimeParameterToDate":[Cutting time for date/time parameters checkbox], "Key":["Filter key in the filter collection"], "IsAggregative":[Aggregating filter checkbox], "LeftExpressionCaption":["Expression title to be checked"], "ReferenceSchemaName":["Reference schema name"] }

Properties

RootSchemaName string

A string containing the name of the root object schema of the added record.

FilterType FilterType

Filter type. Set by the FilterType enumeration value of the Terrasoft.Nui.ServiceModel.DataContract namespace.

Possible values ( FilterType )

None 0 Filter type not defined.

CompareFilter 1 Comparison filter. Used to compare expression results.

IsNullFilter 2 The filter that defines whether an expression is empty.

Between 3 The filter that defines whether an expression is one of the expressions.

InFilter 4 The filter that defines whether an expression equals one of the expressions.

Exists 5 Existence filter.

FilterGroup 6 Filter group. Filter groups can be nested in one another, i.e., the collection itself can be an element of another collection.

© 2021 Creatio. All rights reserved. Filters class | 87

ComparisonType FilterComparisonType

Comparison operation type. Set by the FilterComparisonType enumeration value of the Terrasoft.Core.Entities namespace.

LogicalOperation LogicalOperationStrict

Logical operation. This type does not allow the None value specified in the LogicalOperationStrict enumeration of the Terrasoft.Common namespace.

IsNull bool

Expression completion checkbox.

IsEnabled bool

Checkbox that defines whether the filter is active and will be taken into account when building a request.

IsNot bool

Specifies whether to use the negation logical operator.

SubFilters Filters

Subrequest filters. Cannot contain filters with other subrequests.

Items Dictionary

Collection containing a filter group.

LeftExpression BaseExpression

The expression in the left part of the comparison, i.e. the expression to be tested. The BaseExpression class is defined in the Terrasoft.Nui.ServiceModel.DataContract namespace.

RightExpression BaseExpression

The filter expression that will be compared to the expression contained in the LeftExpression property.

RightExpressions BaseExpression[ ]

The expression array that will be compared to the expression contained in the LeftExpression property.

© 2021 Creatio. All rights reserved. Filters class | 88

RightLessExpression BaseExpression

Initial filtration range expression.

RightGreaterExpression BaseExpression

Final filtration range expression.

TrimDateTime ParameterToDate bool

Checkbox indicating whether to cut time from the date-time parameters.

Key string

Filter key in the collection of Items filters.

IsAggregative bool

Aggregating filter checkbox.

LeftExpressionCaption string

Left comparison part title.

ReferenceSchemaName string

The object schema name referenced by the left part of the filter if the column type is lookup.

The BaseExpression class C#

The Namespace Terrasoft.Nui.ServiceModel.DataContract .

The BaseExpression class is the base expression class. It is defined in the Terrasoft.Nui.ServiceModel.DataContract namespace of the Terrasoft.Nui.ServiceModel library. The properties of this class instance are populated depending on the ExpressionType property that specifies the expression type. A complete list of the BaseExpression class properties is given in table.

Properties

ExpressionType EntitySchemaQuery ExpressionType

The expression type that defines the value that will be contained in the added column. Set by the EntitySchemaQueryExpressionType enumeration of the Terrasoft.Core.Entities namespace defined in the

© 2021 Creatio. All rights reserved. Filters class | 89

Terrasoft.Core class library. For the InsertQuery the EntitySchemaQueryExpressionType.Parameter value is set.

Possible values ( EntitySchemaQuery ExpressionType )

SchemaColumn 0 Schema column.

Function 1 Function.

Parameter 2 Parameter.

SubQuery 3 Subquery.

ArithmeticOperation 4 Arithmetic operation.

ColumnPath string

The path to a column relative to the root schema. The rules for building the paths can be found in the "The use of EntitySchemaQuery for creation of queries in database" article.

Parameter Parameter

Defines the value that will be contained in the added column. Its Parameter type is defined in the Terrasoft.Nui.ServiceModel.DataContract namespace.

FunctionType FunctionType

Function type. Set by the value from the FunctionType enumeration defined in the Terrasoft.Nui.ServiceModel.DataContract namespace.

Possible values ( FunctionType )

None 0 Not defined.

Macros 1 Macro.

Aggregation 2 Aggregating function.

DatePart 3 Date part.

Length 4 Length.

MacrosType EntitySchemaQuery MacrosType

© 2021 Creatio. All rights reserved. Filters class | 90

Macro type. Set by the value from the EntitySchemaQueryMacrosType enumeration defined in the Terrasoft.Core.Entities namespace.

FunctionArgument BaseExpression

Function argument. Takes the value if the function is defined with a parameter. The BaseExpression class is defined in the Terrasoft.Nui.ServiceModel.DataContract namespace and is the ancestor of the ColumnExpresion class and has the same set of properties.

DatePartType DatePart

Date part. Set by the value from the DatePart enumeration defined in the Terrasoft.Nui.ServiceModel.DataContract namespace.

Possible values ( DatePart )

None 0 Not defined.

Day 1 Day.

Week 2 Week.

Month 3 Month.

Year 4 Year.

Weekday 5 Day of the week.

Hour 6 Hour.

HourMinute 7 Minute.

AggregationType AggregationType

Aggregating function type. Sets the value of AggregationType enumeration defined in the namespace Terrasoft.Common defined in the class library Terrasoft.Common .

AggregationEvalType AggregationEvalType

Aggregating function Set by the value from the AggregationEvalType enumeration defined in the Terrasoft.Core.DB namespace defined in the Terrasoft.Core class library.

SubFilters Filters

© 2021 Creatio. All rights reserved. EntitySchemaQueryMacrosType enumeration | 91

Subquery filter collection. Its Filters type is defined in the Terrasoft.Nui.ServiceModel.DataContract namespace. EntitySchemaQueryMacrosType

enumeration C#

Advanced

When creating queries to DataService, both parameterized (ie requiring an argument) and non-parameterized macros can be used. Macro types that must be used in the macro expressions are defined in the EntitySchemaQueryMacrosType enumeration in the Terrasoft.Core.Entities namespace. Enumeration values of macro types and their descriptions are available in table.

Possible values ( EntitySchemaQueryMacrosType )

CurrentHalfYear 16 Current half-year (January-June or July-December).

CurrentHour 21 Current hour.

CurrentMonth 10 Current month.

CurrentQuarter 13 Current quarter.

CurrentUser 1 Current user.

CurrentUserContact 2 Contact record of the current user.

CurrentWeek 7 Current week.

CurrentYear 19 Current year.

DayOfMonth 28 Day of month. Requires parameterization.

DayOfWeek 29 Week day. Requires parameterization.

Hour 30 Hour. Requires parameterization.

HourMinute 31 Time. Requires parameterization.

Month 32 Month. Requires parameterization.

NextHalfYear 17 Next half-year (January-June or July-December).

NextHour 22 Next hour.

NextMonth 11 Next month.

© 2021 Creatio. All rights reserved. UpdateQuery class | 92

NextNDays 24 Next N days. Requires parameterization.

NextNHours 26 Next N hours. Requires parameterization.

NextQuarter 14 Next quarter.

NextWeek 8 Next week.

NextYear 23 Next year.

None 0 Type of macro not defined.

PreviousHalfYear 15 Previous half-year (January-June or July-December).

PreviousHour 20 Previous hour.

PreviousMonth 9 Previous month.

PreviousNDays 25 Previous N days. Requires parameterization.

PreviousNHours 27 Previous N hours. Requires parameterization.

PreviousQuarter 12 Previous quarter.

PreviousWeek 6 Previous week.

PreviousYear 18 Previous year.

Today 4 Today.

Tomorrow 5 Tomorrow.

Year 33 Year. Requires parameterization.

Yesterday 3 Yesterday.

UpdateQuery class C#

Advanced

The Namespace Terrasoft.Nui.ServiceModel.DataContract .

The UpdateQuery data contract is used for updating section records. The query data is transferred to DataService via HTTP, with the help of POST by the URL.

© 2021 Creatio. All rights reserved. UpdateQuery class | 93

The structure of request for updating data

// URL format of the POST query to DataService to update data. http(s)://[Creatio application address]/[Configuration number]/dataservice/[Data fromat]/reply/UpdateQuery // URL example of the POST query to DataService to update data.

An example the request for updating data

http(s)://example.creatio.com/0/dataservice/json/reply/UpdateQuery

The UpdateQuery data contract has a hierarchical structure with a number of nesting levels. In the Creatio server core, it is represented by a UpdateQuery class of the Terrasoft.Nui.ServiceModel.DataContract namespace of the Terrasoft.Nui.ServiceModel.dll library of classes. For the hierarchical data structure of the UpdateQuery data contract can be conveniently viewed in JSON format:

Structure of the UpdateQuery data contract

{ "RootSchemaName":"[Root schema]", "OperationType":[Type of operation with record], "IsForceUpdate":[Force update], "ColumnValues":{ "Items":{ "Name of the added column":{ "ExpressionType":[Expression type], "Parameter":{ "DataValueType":[Data type], "Value":"[Column value]" } }... } }, "Filters":[Request filters] }

Properties

RootSchemaName string

String that contains root schema name of added record object.

© 2021 Creatio. All rights reserved. UpdateQuery class | 94

OperationType QueryOperationType

Type of write operation. Specified as a QueryOperationType enumeration value of the Terrasoft.Nui.ServiceModel.DataContract namespace. The QueryOperationType.Select value is set for SelectQuery .

Possible values ( QueryOperationType )

Select 0

Insert 1

Update 2

Delete 3

Batch 4

IsForceUpdate bool

Indicates force update. If the value is true , the entity will be saved on the server even if column values have been modified. Default value: false .

ColumnValues ColumnValues

Contains collection of column values for the added record. The ColumnValues type is defined in the Terrasoft.Nui.ServiceModel.DataContract namespace.

Filters Filters

Collection of query filters. The < Filters type is defined in the Terrasoft.Nui.ServiceModel.DataContract namespace.

The ColumnValues class C#

The Namespace Terrasoft.Nui.ServiceModel.DataContract .

The ColumnValues class has a single Items property, defined as a collection of keys and values Dictionary . The key is the string with the name of the added column. The value is an object of the ColumnExpression type, defined in the Terrasoft.Nui.ServiceModel.DataContract namespace. General properties of the ColumnExpression class used when adding records are available in table.

Properties

© 2021 Creatio. All rights reserved. UpdateQuery class | 95

ExpressionType EntitySchemaQuery ExpressionType

Type of expression that determines the value that the added column will contain. Specified with a value from the EntitySchemaQueryExpressionType enumeration of the Terrasoft.Core.Entities namespace defined in the Terrasoft.Core class library. The EntitySchemaQueryExpressionType.Parameter value is set for InsertQuery .

Possible values ( EntitySchemaQueryExpressionType )

SchemaColumn 0 Schema column.

Function 1 Function.

Parameter 2 Parameter.

SubQuery 3 Subquery.

ArithmeticOperation 4 Arithmetic operation.

Parameter Parameter

Determines the value that the added column will contain. The Parameter type is defined in the Terrasoft.Nui.ServiceModel.DataContract namespace.

The Parameter class C#

The Namespace Terrasoft.Nui.ServiceModel.DataContract .

The Parameter class has a number of properties, only two of which are used for adding records.

Properties

DataValueType DataValueType

Type of data for the value that the added column will contain. Specified as a DataValueType enumeration value of the Terrasoft.Nui.ServiceModel.DataContract namespace.

Possible values ( DataValueType )

© 2021 Creatio. All rights reserved. DeleteQuery class | 96

Guid 0

Text 1

Integer 4

Float 5

Money 6

DateTime 7

Date 8

Time 9

Lookup 10

Enum 11

Boolean 12

Blob 13

Image 14

ImageLookup 16

Mapping 18

Value object

The object that contains the value of the added column. Has the Object type.

The Filters class C#

The Namespace Terrasoft.Nui.ServiceModel.DataContract .

An instance of the UpdateQuery class must contain a link to a correctly initialized instance of the Filters class in the Filters property. Otherwise, new column values from the ColumnValues property will be set for ALL section records.

DeleteQuery class C#

Advanced

© 2021 Creatio. All rights reserved. DeleteQuery class | 97

The Namespace Terrasoft.Nui.ServiceModel.DataContract .

The DeleteQuery contract is used to delete sections. The data is transferred to the DataService via HTTP by using the POST request with the following URL:

The structure of request for deleting data

// URL format of the POST query to DataService to delete data. http(s)://[Creatio application address]/[Configuration number]/dataservice/[Data fromat]/reply/DeleteQuery

An example the request for deleting data

// URL example of the POST query to DataService to delete data. http(s)://example.creatio.com/0/dataservice/json/reply/DeleteQuery

The DeleteQuery data contract has a hierarchical structure with multiple nesting levels. In the Creatio application server part, the DeleteQuery data contract is represented by the DeleteQuery class of the Terrasoft.Nui.ServiceModel.DataContract namespace of the Terrasoft.Nui.ServiceModel.dll class library. However, for simplicity, the hierarchical structure of the DeleteQuery data contract is conveniently presented as a JSON format object:

Structure of the DeleteQuery data contract

{ "RootSchemaName":"[Root schema]", "OperationType":[Record operation type], "ColumnValues":[Column values. Not used.], "Filters":[Query filters] }

Properties

RootSchemaName string

A string containing the name of the root object schema of the added record.

OperationType QueryOperationType

Operation type is set by the QueryOperationType namespace Terrasoft.Nui.ServiceModel.DataContract namespace enumeration value. For the SelectQuery the QueryOperationType.Select value is set.

Possible values ( QueryOperationType )

© 2021 Creatio. All rights reserved. Batch queries | 98

Select 0

Insert 1

Update 2

Delete 3

Batch 4

ColumnValues ColumnValues

Contains a collection of column values of the added record. Inherited from the BaseQuery parent class. Not used in this type of queries.

Filters Filters

Query filter collection. Its Filters type is defined in the Terrasoft.Nui.ServiceModel.DataContract namespace.

The Filters class C#

The Namespace Terrasoft.Nui.ServiceModel.DataContract .

The DeleteQuery query class instance must contain a link to the correctly initialized Filters class instance in the Filters property. Otherwise ALL section records will be deleted.

Batch queries C#

Advanced

Batch queries are used to minimize requests to DataServise, which improves application performance. Packet query is a collection that contains a custom set of DataService requests. The query data is transferred to DataService via HTTP, with the help of POST by the URL.

The structure of batch query

// URL format of the batch POST query to DataService. http(s)://[Creatio application address]/[Configuration number]/dataservice/[Data fromat]/reply/BatchQuery

An example the batch query

// URL example of the batch POST query to DataService.

© 2021 Creatio. All rights reserved. Batch queries | 99

http(s)://example.creatio.com/0/dataservice/json/reply/BatchQuery

The data that comprises a batch query can be passed in different formats. One of the more convenient formats is JSON.

The structure of a batch query in JSON format

{ "items": [ { "__type": "[Full qualified name of the query type]", //One-time query contents. ... }, // Other one-time queries. ... ] }

To generate the contents of one-time queries that comprise a batch query, use the following data constants: InsertQuery , SelectQuery , UpdateQuery and DeleteQuery .

© 2021 Creatio. All rights reserved.