There’s need to do something in background in both AxCMS.net and custom project. This applies to time-consuming tasks (like making snapshots of the pages), regular scheduled tasks (like reporting), etc. The goal of AxCMS.Service is to provide unified way for executing tasks in background for both AxCMS.net and custom projects.
Database
New table is introduced - AxServiceTask.
Table exists in both MS and LS.
Following fields are defined:
[AxID] [bigint] NOT NULL - unique ID of the service task
[Active] [bit] NOT NULL – shows if the task is active (1, default) or stopped (0)
[ClassName] [nvarchar](255) NOT NULL – name of class implemenenting IServiceTask to be executed (e.g. „Axinom.AECMS.IndexTextTask“)
[AssemblyName] [nvarchar](255) NULL – optional assembly name of the task class (e.g. „AxCMS.BL“). If not specified, service will search all assemblies available in the folder
[ElementID] [bigint] NULL – optional element id to apply the task to
[ElementType] [smallint] NULL – optional element type to apply the task to
[Parameters] [ntext] NULL – optional string of parameters for the task, can also be XML
[DateAdded] [datetime] NOT NULL – date when task is added
[LastExecuted] [datetime] NULL – date when task was last executed, null means task was never executed
[ExecutionInterval] [int] NULL – optional execution interval specification, null means task is for one-time execution only (task is deleted from the table after execution), 0 means task should always be running, any value larger than 0 means number of seconds to wait between executions of the task
[LastException] [ntext] NULL – contains last exception when executing task, null means no exception occured during last execution
You can schedule a task by inserting a row into the database, e.g.
INSERT INTO [AxServiceTask]
(AxID,Active,ClassName,AssemblyName,ExecutionInterval)
VALUES
(2,1,'Axinom.AECMS.GenerateReportsActivity','AxCMS.BL',86400)
Classes and Interfaces
IServiceTask interface – every task has to implement this interface to be executed by AxCMS.Service. Members:
void Execute(string encodedParameters, IClassifiable element) – executes the current task for given encoded parameters and element
string EncodeParameters() – encodes current task instance properties (if any) to the string for further saving to the database
ServiceTask class – the class representing a task. Instance of ServiceTask class is created by AxCMS.Service instance for each task scheduled for execution. Instance has following methods in additions to methods inherited from AxDbObject:
public void Execute() – creates an instance of the IServiceTask and calls Execute method to start the task passing the encoded patameters and element proxy
public void Start()– starts the execution of the task according to schedule
public void Stop()– stops the task from execution
ServiceTask class also provides static method for scheduling an instance of a class implementing IServiceTask interface:
public static long Schedule(IServiceTask itask, IClassifiable element, int? executionInterval)
This method encodes the properties (or parameters) of the task to string by calling EncodeParameters() method, saves the class name, element provided, parameters and interval to AxServiceTask table for current connection manager. Method returns AxID of the new created task. There are also overloads for tasks requiring one-time execution:
public static long Schedule(IServiceTask itask, IClassifiable element)
and tasks that do not use element
public static long Schedule(IServiceTask itask)
There also overloads that take IConnectionManager as parameter to schedule the task for specified database connection.
ServiceTask also defines following static methods for stopping / resuming tasks:
public static void Start(long taskAxId)
public static void Stop(long taskAxId)
ConfigurationAxCMS.Service will have its own configuration file AxCMS.Service.exe.config. It should declare all the service instances to run:
<ServiceInstances>
<ServiceInstance name="AxCMSweb_MS">
<Context path="/AxCMSweb" site="Default Web Site"/>
<Settings threadCount="5" sleepTime="60" errorSleepTime="3600" />
</ServiceInstance>
<ServiceInstance name="AxCMSweb_LS">
<Context path="/AxCMSwebLive" site="Default Web Site"/>
<Settings threadCount="5" sleepTime="60" errorSleepTime="3600" />
</ServiceInstance>
</ServiceInstances>
Context element determines the configuration context of the instance. Set the site to the CMS site to be monitored and path to the virtual path of the system.
Settings element sets various settings of the instance:
* threadCount is the number of threads to create for each task
* sleepTime is the amount of seconds to wait between trying to execute next set of tasks
* errorSleepTime is the amount of seconds to wait if critical error has occured (e.g. DB is not accessible).
Exception publisher also has to be defined for logging the exceptions occured during task execution. If you use ExceptionPublisherMail, you also have to add appSettings section with SmtpServer key.
<appSettings>
<add key="SmtpServer" value="mail.axinom.de" />
</appSettings>
Standard tasks supplied with AxCMS.net
IndexFileTask, IndexTextTask - these tasks perform indexing operations for files and texts and are called from AxIndexer. They replace AxIndexQueue and AxIndexService used before. Task parameters have format of Field=IndexedContent, e.g. Name=Page1.
NewsletterQueueTask - this task performs customizing and sending of the newsletters. It replaces NewsletterSyndicationService used before. Task parameters have format of NumberOfNewslettersToSend,ResourceManagerToUse, e.g. 1,LIVE.
CmsActivity - CmsActivity and all its children implement now IServiceTask interface and thus can be scheduled. Before they were scheduled with Background executor. Task parameter is serialized instance of CmsActivity itself.
EmailGateway - this task performs checking of the specified mailbox, getting mails out of it, processing them and deleting them. This task does not do anything, but publishes the mail with ExceptionManager. You should inherit from this task and override ProcessMail method, which is called for every message. Task parameter is connection string to the mailbox, in format Server=mailserver.somewhere;Port=110;Username=myUser;Password=myPassword
AxTaskEmailGateway - implementation of EmailGateway. This task checks the e-mails coming to the specified mailbox and creates CMS tasks out of them. You should schedule it same way as any e-mail gateway task. To assign a CMS task to an user, send this user an e-mail with CC to the mailbox of this task. To: field will become owner of the task, From: field will become creator of the task, Subject: will become title of the task and message body will be the task description. Both owner and creator e-mails must match e-mails in their AxCMS.net user profile.
AxDocumentEmailGateway - implementation of EmailGateway. This task checks the e-mails coming to the specified mailbox and creates CMS documents from mail attachments. You should schedule it same way as any e-mail gateway task. To upload a document to a CMS, send the e-mail with a document attached to mailbox of this task. All attachments of the mail will be uploaded as documents in CMS, attachment name will become document title, mail subject will become document caption and mail body will become document description, user who sent the e-mail will become author of the document. User e-mail must match e-mail in AxCMS.net user profile. Note: only binary files will be accepted by AxDocumentEmailGateway.
Code sample
Source of SampleTask:
class SampleTask : IServiceTask
{
private string _param1;
private string _param2;
public SampleTask() { }
public SampleTask(string param1, string param2)
{
this._param1 = param1;
this._param2 = param2;
}
#region IServiceTask Members
//This method will be called from AxCMS.Service upon task execution
public void Execute(string encodedParameters, IClassifiable element)
{
//decode parameters first
DecodeParameters(encodedParameters);
//do something
DoSomething(_param1,param2);
}
//This method will be called on scheduling the task, it should be used
//to encode paramaters needed for task to one string that will be saved
//to database table
public string EncodeParameters()
{
//here we just concatenate two parameters together with a comma
return _param1+","+_param2;
}
#endregion
//This method should do operation oposite to EncodeParameters - restore task
//parameters from the string of encoded parameters
public void DecodeParameters(string encodedParameters)
{
//we simply split the encoded parameters by comma
string[] prms = encodedParameters.Split(new char[] { ',' }, 2);
_param1 = prms[0];
_param2 = prms[1];
}
}
Scheduling the SampleTask:
//this schedules the sample task with parameters myParam1 and myParam2 for
//one time execution
ServiceTask.Schedule(new SampleTask('myParam1','myParam2'));
//this schedules the sample task with parameters myParam1 and myParam2 for
//continuous execution
ServiceTask.Schedule(new SampleTask('myParam1','myParam2'),0);
//this schedules the sample task with parameters myParam1 and myParam2 for
//execution every hour
ServiceTask.Schedule(new SampleTask('myParam1','myParam2'),3600);