Implement a virtual object
This functionality is available for Creatio 10.2 and later.
A virtual object needs a query executor that reads the records and an event listener that writes the changes to the data source. The operations to implement depend on the Creatio tools that use the object. Learn more: Use virtual objects in Creatio tools.
General procedure
1. Create a virtual object
- Create the "Object" type schema. Instructions: Implement an object (steps 1-6).
- Select the "Virtual" checkbox in the Behavior property block.
- Click Save and publish.
As a result, Creatio adds the virtual object to the package. Creatio does not create a database table for the object.
2. Implement a query executor
A query executor is a C# class that returns the records of a virtual object. Creatio calls the query executor for every read of the object.
Follow these rules when you implement a query executor:
- Reject the query parts that the query executor does not support. If the query includes a filter, a sort order, or a total that the query executor does not support, throw the
NotSupportedExceptionexception with a clear message. Saving a record on a page, deleting a record in a list, and the Modify data and Delete data process elements process every record that the query executor returns. A query executor that ignores a filter makes them change or delete all records. - Apply both the
RowCountandSkipRowCountproperties. Creatio reads large sets of records in batches and stops when a batch is shorter than requested. A query executor that limits the batch but does not skip records returns the first batch repeatedly. - Implement the access checks. In Creatio 10.2, Creatio does not apply access permissions to virtual objects, so the query executor checks which records and columns the user can read. In upcoming releases, Creatio checks operation and column permissions of virtual objects automatically, and the query executor checks only record permissions. Learn more: Difference between virtual and regular objects.
- Do not set the state of the records. Creatio marks the records that the query executor returns as existing records. When a user saves such a record, Creatio calls the
OnUpdating()method, not theOnInserting()method. - Use the query only inside the method call. Do not store or change the
EntitySchemaQueryobject, and do not use it from another thread.
To implement a query executor, complete the following steps.
1. Create the query executor class
- Create a "Source code" type schema in your package. Instructions: Implement the source code (steps 1-5).
- Create a class that implements the
IEntityQueryExecutorinterface. - Specify the binding name in the
Nameparameter of the[DefaultBinding]attribute to bind the class to the object. The binding name consists of the object code and theQueryExecutorsuffix. For example, the binding name for the "External invoice" (UsrExtInvoicecode) object isUsrExtInvoiceQueryExecutor. Creatio finds the query executor by the binding name, not by the class name.
The following code shows an example of the query executor class.
namespace Terrasoft.Configuration
{
using System;
using System.Collections.Generic;
using System.Linq;
using Terrasoft.Core;
using Terrasoft.Core.Entities;
using Terrasoft.Core.Factories;
/* Bind the query executor to the "UsrExtInvoice" object.
* The binding name is the object code plus the "QueryExecutor" suffix. */
[DefaultBinding(typeof(IEntityQueryExecutor),
Name = "UsrExtInvoiceQueryExecutor")]
public class UsrExtInvoiceQueryExecutor : IEntityQueryExecutor
{
/* The user connection that creates the entities to return. */
private readonly UserConnection _userConnection;
/* Creatio passes the user connection to the constructor. */
public UsrExtInvoiceQueryExecutor(UserConnection userConnection) {
_userConnection = userConnection;
}
/* Creatio calls the method for every read of the object. */
public EntityCollection GetEntityCollection(
EntitySchemaQuery esq) {
/* Process the query. */
}
}
}
2. Implement the query processing
Creatio calls the GetEntityCollection() method of the query executor and passes the query as an EntitySchemaQuery object. To process the query:
- Get the records that match the filters of the query from the data source.
- Return totals if the query requests them, for example, for metrics or for the counter of selected records. In this case, return a single row that contains the totals for the filtered records and skip the next steps.
- Sort the records by the columns of the query that have a sort direction.
- Split the records into batches. Skip and take the number of records that the query specifies.
- Return the records as an
EntityCollectionobject. Fill out the selected columns of each record.
The following table lists the parts of the query and how to process them.
Part of the query | Source | Processing |
|---|---|---|
Columns | The items of the | Fill out every selected column that the data source stores. Always fill out the ID. |
"Lookup" type columns | The | Fill out both the ID of the lookup record and its displayed value. Creatio does not retrieve the displayed value, so a lookup without the displayed value shows an empty field. |
Filtering records | The | Apply the groups ( |
Reading records by ID | The | Return exactly the records that have the IDs. Creatio uses the query to open a record and before Creatio changes or deletes records. |
Sorting records | The items of the | Sort the records. Sort a "Lookup" type column by its displayed value. |
Loading records in batches | The | Skip |
Calculating totals | An item of the | Return a single row that contains the total for the filtered records. |
A condition does not always compare a column of the object with a value:
- The left side can be a column of a linked object, for example,
UsrOwner.Namein the list search. - The right side can be a macro instead of a value, for example, "Current user," "Today," or "Current month." The macro arrives as a function, and the query executor calculates its value.
- A column of the query can be a function, for example, the year or the month of a date in a pivot table.
Support the cases that your pages and business processes use, and reject the other cases.
The following code shows an example that processes the parts of the query in the required order. In the code, _client is your class that calls the data source, and ExternalInvoice is a record that the class returns. ToExternalFilter() and Sort() are your methods that convert the filters and the sort order of the query to the format of the data source.
public EntityCollection GetEntityCollection(EntitySchemaQuery esq) {
/* The object schema that the query reads. */
EntitySchema schema = esq.RootSchema;
/* Filters. Keep only the records that match esq.Filters. */
List<ExternalInvoice> invoices =
_client.GetInvoices(ToExternalFilter(esq.Filters));
/* Totals. If the query requests totals, return a single row. */
if (esq.Columns.Any(IsAggregate)) {
return GetTotals(esq, invoices);
}
/* Sorting. Sort by the columns that have a sort direction. */
IEnumerable<ExternalInvoice> page = Sort(esq, invoices);
/* Batches. Skip SkipRowCount records and take RowCount records. */
if (esq.SkipRowCount > 0) {
page = page.Skip(esq.SkipRowCount);
}
if (esq.RowCount > 0) {
page = page.Take(esq.RowCount);
}
/* Records. Return an entity for each record. */
var collection = new EntityCollection(_userConnection, schema);
foreach (ExternalInvoice invoice in page) {
Entity entity = schema.CreateEntity(_userConnection);
entity.LoadColumnValue("Id", invoice.Id);
entity.LoadColumnValue("UsrName", invoice.Name);
entity.LoadColumnValue("UsrAmount", invoice.Amount);
/* Lookup value. */
entity.LoadColumnValue("UsrOwnerId", invoice.OwnerId);
/* Displayed value of the lookup. */
entity.LoadColumnValue("UsrOwnerName", invoice.OwnerName);
collection.Add(entity);
}
return collection;
}
In a production query executor, pass the filters, the sort order, and the batch parameters to the data source instead of loading all records and processing them in memory.
If the query requests totals, the query includes function columns instead of regular columns. The response is a single row. Build the row based on the schema of the query that the esq.GetSchema() method returns. Unlike the "Object" type schema, this schema includes a column for every total. The following code shows an example that returns totals.
/* Check whether the column of the query is a total. */
private static bool IsAggregate(EntitySchemaQueryColumn column) {
EntitySchemaQueryExpression expression = column.ValueExpression;
return expression != null
&& expression.ExpressionType ==
EntitySchemaQueryExpressionType.Function
&& expression.Function is EntitySchemaAggregationQueryFunction;
}
private EntityCollection GetTotals(EntitySchemaQuery esq,
List<ExternalInvoice> invoices) {
/* The schema of the query includes a column for every total. */
EntitySchema resultSchema = esq.GetSchema();
Entity row = resultSchema.CreateEntity(_userConnection);
foreach (EntitySchemaQueryColumn column in
esq.Columns.Where(item => item.IsSelecting)) {
/* Reject grouping that the query executor does not support. */
if (!IsAggregate(column)) {
throw new NotSupportedException(
"External invoices cannot be grouped.");
}
var function = (EntitySchemaAggregationQueryFunction)
column.ValueExpression.Function;
/* Calculate the total for the filtered records. */
object total;
switch (function.AggregationType) {
case AggregationTypeStrict.Count:
total = invoices.Count;
break;
case AggregationTypeStrict.Sum:
total = invoices.Sum(invoice => invoice.Amount);
break;
/* Reject the functions that the query executor does not support. */
default:
throw new NotSupportedException(
"External invoices do not support the " +
function.AggregationType + " function.");
}
/* Write the total to the column of the row. */
row.LoadColumnValue(resultSchema.Columns
.GetByName(column.Name).ColumnValueName, total);
}
/* Return the row as a collection of a single entity. */
var collection = new EntityCollection(_userConnection,
resultSchema);
collection.Add(row);
return collection;
}
3. Register the query executor
- Compile the configuration.
- If Creatio runs on .NET, restart Creatio. Creatio on .NET Framework restarts after the compilation automatically. Creatio registers the query executor when Creatio starts. Until the restart, reading the object fails with the "Entity schema executor for schema "UsrExtInvoice" not found" error.
4. Check the query executor
To check the query executor with real data in lists:
- Open a list that is based on the virtual object. Make sure that the list shows the records and the "Lookup" type columns show the displayed values.
- Scroll down the list until Creatio loads the next batch of records. Make sure that the list shows new records and does not repeat records.
- Sort the list by a text column, a number column, and a "Lookup" type column.
- Filter the list using the search and a quick filter. Then add a filter that the query executor does not support, and make sure that the user sees an error instead of records that do not match the filter.
To check the query executor with real data in components and widgets:
- If you use the object in a calendar, check the calendar on more records than a single batch includes.
- Add a metric that calculates the number of records of the object, then add a metric that has a filter.
- If you use the object in a pivot table, check the pivot table on more records than a single batch includes.
To check the query executor with real data in business processes:
- Run a business process that includes the Read data process element in each read mode and the Add data, Modify data, and Delete data process elements.
- Make sure that only the records that match the condition changed for the Modify data and Delete data process elements.
3. Implement an event listener
An event listener is a C# class that writes the changes of a virtual object to the data source. Creatio calls the methods of the event listener when a user adds, changes, or deletes a record of the object.
Follow these rules when you implement an event listener:
- Implement only the operations that the data source supports. If the data source does not support deleting records, throw an exception that explains this in the
OnDeleting()method instead of leaving the method empty, and remove the Delete action from the pages. - Implement the access checks. In Creatio 10.2, Creatio does not apply access permissions to virtual objects, so the event listener checks that the user can add, change, or delete the record and change its columns. In upcoming releases, Creatio checks operation and column permissions of virtual objects automatically, and the event listener checks only record permissions. Learn more: Difference between virtual and regular objects.
- Do not check whether the record exists. Creatio determines whether a save adds or changes a record. Creatio changes a record that the query executor reads and adds a new record.
- Write only the columns that the data source stores in the
OnUpdating()method. The changed columns can include a column that the query executor does not fill out. Such a column contains its default value, not a value that the user enters. - Report a failure using an exception. If the data source rejects the change, throw an exception with a clear message. The user sees the message, and a business process element stops with the message. A virtual object has no transaction, so Creatio does not roll back the changes that an earlier method has already written to the data source.
To implement an event listener, complete the following steps.
1. Create the event listener class
- Create a "Source code" type schema in your package. Instructions: Implement the source code (steps 1-5).
- Create a class that inherits the
BaseEntityEventListenerclass. - Specify the object code in the
SchemaNameparameter of the[EntityEventListener]attribute to register the event listener for the object. An event listener registered for all objects does not receive theOnInsertingandOnUpdatingevents of a virtual object.
2. Implement the methods of the event listener
Implement the methods for the operations that the data source supports:
OnInserting(): add a record to the data source.OnUpdating(): write the changed columns to the data source.OnDeleting(): delete the record from the data source.
The following code shows an example of the event listener. In the code, _client is the same class as in the query executor, and ExternalInvoiceChanges is your class that contains the changed values.
namespace Terrasoft.Configuration
{
using System;
using Terrasoft.Core.Entities;
using Terrasoft.Core.Entities.Events;
/* Register the event listener for the "UsrExtInvoice" object. */
[EntityEventListener(SchemaName = "UsrExtInvoice")]
public class UsrExtInvoiceEventListener : BaseEntityEventListener
{
/* Add a record. */
public override void OnInserting(object sender,
EntityBeforeEventArgs e) {
base.OnInserting(sender, e);
var entity = (Entity)sender;
/* Create the invoice in the data source. */
_client.CreateInvoice(
entity.PrimaryColumnValue,
entity.GetTypedColumnValue<string>("UsrName"),
entity.GetTypedColumnValue<int>("UsrAmount"),
entity.GetTypedColumnValue<Guid>("UsrOwnerId"));
}
/* Change a record. */
public override void OnUpdating(object sender,
EntityBeforeEventArgs e) {
base.OnUpdating(sender, e);
var entity = (Entity)sender;
/* Collect only the columns that the data source stores. */
var changes =
new ExternalInvoiceChanges(entity.PrimaryColumnValue);
foreach (EntityColumnValue columnValue in
entity.GetChangedColumnValues()) {
switch (columnValue.Name) {
case "UsrName":
changes.Name = (string)columnValue.Value;
break;
case "UsrAmount":
changes.Amount =
Convert.ToInt32(columnValue.Value);
break;
case "UsrOwnerId":
changes.OwnerId = columnValue.Value as Guid?;
break;
}
}
/* Write the changes to the data source. */
_client.UpdateInvoice(changes);
}
/* Delete a record. */
public override void OnDeleting(object sender,
EntityBeforeEventArgs e) {
base.OnDeleting(sender, e);
var entity = (Entity)sender;
/* Delete the invoice in the data source. */
_client.DeleteInvoice(entity.PrimaryColumnValue);
}
}
}
3. Check the changes in the data source
- Compile the configuration.
- If Creatio runs on .NET, restart Creatio. Creatio on .NET Framework restarts after the compilation automatically. Creatio registers the event listener when Creatio starts.
- Add, change, and delete a record of the object. After you change a record, open the record again and make sure that the record includes the new values.
- Make sure that the data source changed this record and did not change other records.
Issue handling
Issue | Description | Solution |
|---|---|---|
The "Entity schema executor for schema "..." not found" error | The query executor has no |
|
The list is empty | The query executor returns no records for the query of the list. | Check the filters that the query executor receives. |
The search, a quick filter, or a folder does not change the list | The query executor ignores the | Apply the filters of the query. Instructions: Implement the query processing. |
A click on a column header does not sort the list | The query executor ignores the sort direction of the columns. | Sort the records by the columns that have a sort direction. Instructions: Implement the query processing. |
The list shows the same records again when you scroll down | The query executor ignores the | Apply both the |
A lookup field or a "Lookup" type column is empty | The query executor fills out the ID of the lookup but not its displayed value. | Fill out both the ID and the displayed value of the lookup. Instructions: Implement the query processing. |
The metric shows "0" or an error | The query executor does not calculate totals. | Return totals. Instructions: Implement the query processing. |
The totals of a pivot table are too high, or a calendar shows only part of the records | The query executor ignores the | Apply both the |
The page opens the wrong record | The query executor ignores the condition on the ID and returns multiple records. | Return exactly the records that have the IDs from the query. Instructions: Implement the query processing. |
Saving a single record changes other records, or deleting a single record deletes other records | The query executor ignores the condition on the ID. Creatio changes or deletes every record that the query executor returns. | Return exactly the records that have the IDs from the query. Instructions: Implement the query processing. |
The page reports that the record is saved, but the change is lost | The event listener has no |
|
A deleted record appears again | The event listener has no | Implement the |
The Modify data or Delete data process element changes more records than expected | The query executor ignores a filter instead of rejecting the query. | Throw the |
A business process element fails with the | The element uses a filter, a sort order, or a function that the query executor rejects. | Simplify the element or extend the query executor. |