V10 ResourcesGuides
ResourcesGuides
Guides
Back | List of Articles

How to execute tasks with the ECHO Assistant (v10.10)?

Last changed in 02/03/2021

It is possible to execute tasks outside of the ERP process with the ECHO Assistant. These tasks can be scheduled automatically or by using operations in the ERP.

The task execution allows to create ECHO messages that can be used, for example, to report the end of the execution to the user. This way, it is possible for the user to execute a specific task "on request" in consequence of an action in the ERP, or automatically, during the night or at the weekend, for example.

This approach frees resources from the ERP and from the workstation, considering that tasks are always executed on the server.

The ECHO task execution is limited by the availability of resources on the server. That is, the task can be delayed, in case the server is too limited in terms of disk, memory, CPU, and resources on the SQL Server. This management is performed automatically.

Create tasks

To create tasks, it is necessary to first create a topic. You can view the article "How to extend the Echo Assistant (v10.10 SR1)?" for more information on its creation.

  1. In the "Bot.BotTasks" table, insert a new record for a "Task", for example, with the name you prefer. Let's consider the name "TaskExecutionExample";
  2. Specify the "task" name and the "pipeline" that the task should execute. Let's consider the name "TaskExecutionExamplePipeline" for the pipeline;
  3. Define the scheduling, if you wish the task to execute automatically. The example configuration file in the topic project has all the possible combinations explained;
  4. Define the validity time for the messages generated by this task;
  5. Define the message "scope", that is, if the task will be executed once by instance, once by instance, company and user combination;
  6. Specify the platforms that the topic supports. It is possible to filter by line and by environment type;
  7. Create the pipeline, in the "pipelines" section, with the name specified when associating to the "task";
  • If you wish to have in your "handler" the information on the ERP instances/companies/users, you should put this handler in the first pipeline place.
    <Handler Id="ErpReadConfigHandler" Order="1" Behavior="Reader" Type="Primavera.Platform.HurakanHandlers.ErpReadConfig" ConfigStr="instanceIdFilter=%%InstanceId%%;userFiltler=%%UserFilter%%;enterpriseFilter=%%EnterpriseFilter%%"/>
  • Next, put your handler(s). Let's consider the name "TaskExecutionExampleHandler".
    <Handler Id="TaskExecutionExampleHandler" Order="2" Behavior="Reader" Type="Primavera.Bot.DevelopersNetworkTopic.Handlers.TaskExecutionExampleHandler" ConfigStr="topicId=%%TopicId%%;taskId=%%TaskId%%"/>
  • If during the task execution new messages are generated to ECHO, put the following handler in order to save them:
    <Handler Id="CreateUserBotMessagesHandler" Order="3" Behavior="Reader" Type="Primavera.Hurakan.BotHandlers.CreateUserBotMessages" ConfigStr=""/>
    <Handler Id="SaveBotMessagesHandler" Order="4" Behavior="Reader" Type="Primavera.Hurakan.BotHandlers.SaveBotMessages" ConfigStr=""/>
    

The previous point is adapted to the normal reality of producing topics and actions that interact with the ERP and generate messages at the end. The handlers list can be totally customized by the integrator and include, for example, handlers that use the information of other sources.

Right now, the ECHO Assistant already knows how to execute its task. This task can be scheduled manually, but will also be scheduled automatically, in the defined calendar. If you remove the "Schedule", the task will only be scheduled manually by invoking the platform function: "PSO.Bot.CriaTarefa" using PEX or "Plataforma.Bot.CriaTarefa" using an external integration.

Task and pipeline created in the previous points (the definition and detail in each column is present in the example SQL file on GitHub):

INSERT INTO Bot.BotTasks(NaturalKey, DescriptionId, TopicId, Importance, ScheduleConfig, MessageConfig, PlatformsConfig, PipelineConfig, [System], Active, CreatedBy, ModifiedBy, AllowConfigReceivers, ReceiverOption, [Version]) 
VALUES(
	'TaskExecutionExample', 
	'Task_ExecutionExample', 
	@TopicId, 
	1, 
	'{"Active":true,"Execute":""Daily"","StartAt":1,"StartTolerance":31}', 
	'{"Scope":"Instance","ExpireDays":365}', 
	'[{"Version":"V100", "platform":"Executive"},{"Version":"V100", "platform":"Professional"}]', 
	'
		
			
			
			
			
		
	', 
	0, 1, 'MyUser', 'MyUser', 1, -1, 1)

Implement tasks

Next, let's implement the task:

In the topic project, please create a new class with the name you prefer and the suffix "Handler", ex.: "TaskExecutionExampleHandler.cs".

  • The class must be public and inherit "TopicHandlerBase" (Add using Primavera.Hurakan.BotHandlers)
  • Implement the abstract class (that is, override the method "ProcessMessage")
  • Add the "using System.ComponentModel.Composition;" at the start of the file.
  • Add the "exports" from which Echo will use the Management Extensibility Framework (MEF) from .NET Framework, to locate the new class.
[Export(typeof(IHandler))]
[Export(typeof())]
  • Add the following code at the start of the method "ProcessMessage:
this.TopicId = ""; 
this.TaskId = ""; 
this.Initialize(message as IntegrationMessage);
  • From this moment, in case you put the ERP data reading handler, you must have an pobject "this.Instances" with the instances/productive companies/users that obey the scope of the task, that is:
    - If the scope is "Instance" you will have one of the instances available with all productive companies and users.
    - If the scope is "Instance|Enterprise" you will have one of the instances, one of the companies and all users.
    - If the scope is "Instance|Enterprise|User" you will only have one of the possible combinations.
  • There will be scheduled automatically as many tasks as necessary to accomplish the task scope in all instances/productive companies/users. The scope only defines the processing unit in order to allow to make the tasks bigger or faster, depending on its nature. It is an implementation option.
  • Next, an iteration should be created for each one of the instances/companies/users for the handler to adapt automatically to the processing unit. That is:
foreach (Instance instance in this.Instances) 
{ 
	foreach (Enterprise enterprise in instance.Enterprises) 
	{ 
		(...) 
		this.BuildConnectionString(instance.ServerSql, instance.LoginSql, instance.PasswordSql, instance.Database); 
		(...) 
	} 
}

If you wish to perform SQL queries to the database, you must initialize the connection string, as shown previously:

  • After this operation, simply use the method "this.ExecuteNonQuery" and/or "this.Fill" to execute an SQL instruction or to perform an SQL query, respectively.
  • The client is free to implement the remaining task execution.

If necessary, use the ERP engine, it is available using the reflection and can be used as follows:

using (ErpHelper erpHelper = new ErpHelper()) 
{ 
	// edit a customer and change something... 
	erpHelper.SetErpConnectionString(instance, enterprise.Code);
	
	dynamic customerObject = erpHelper.Erp.Base.Clientes.Edita(customerId); 
	customerObject.Nome = "Nome"; 
	
	erpHelper.Erp.Base.Clientes.Actualiza(customerObject); 
}

Using "ErpHelper" inside of the "using" ensures that the "dispose" pattern is correctly applier and that the engine connection is destroyed as soon as the code block finishes.

In case it is necessary to create messages as a consequence of the execution, you can do it the following way:

  • Create a list of messages, at the start of the function:
protected List BotMessages { get; set; };
  • Create a list of messages, by instance, inside the foreach of the instance:
List instanceMessages = new List();
  • Inside the instance cycle, execute the following block of code to create a message for the instance:
BotMessage companyMessage = this.InitializeNewMessage(instance, EmptyUserCodePlaceHolder, "A tarefa 'TaskExecutionExample' foi concluída com sucesso.");
companyMessage.CompanyId = enterprise.Code;
instanceMessages.Add(companyMessage);
  • At the end of the instance cycle, add the main object messages:
this.BotMessages.Add(instance.Id, instanceMessages);
  • At the end of the function, add the following code to transfer the messages to the handler that will save it:
return this.BuildIntegrationMessage(this.BotMessages);

Note: All possibilities to create messages will be approached in a more complete way in the following article.

With the information currently in this article, it is possible to execute any lengthy task, automatically or upon request, by integrating with the ERP engines, or by directly executing the SQL code, as well as its successful (or unsuccessful) report for the final user, in the ERP.

The code detailed in this article is available on the PRIMAVERA GitHub.

Bookmark or share this article
Esta página foi útil?
Obrigado pelo seu voto.

login para deixar a sua opinião.

Obrigado pelo seu feedback. Iremos analisá-lo para continuarmos a melhorar!
Artigos Relacionados
Começar a Usar Como criar um projeto de integração com Visual Studio? Como criar um projeto de extensibilidade de interface (PEX) com Visual Studio? Como criar um projeto de extensibilidade de API (Motor) com Visual Studio? Como criar separadores do utilizador com Visual Studio?