Example of AsyncConnectionExtension Implementation
In this example, we simply save the identifier of the last order using asynchronous
data storage. The extension intercepts SaveOrder requests, executes them,
and after the request completes, it reads DocumentId from the order XML node
and stores it with KeyValueStorage asynchronously.
For asynchronous connection interceptor you need to implement ExecuteRequestAsync. The execute
delegate is asynchronous (ExecuteRequestAsyncMethod) and returns a Task<XDocument>.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Sana.Extensions.Connection;
using Sana.Extensions.Data;
namespace Sana.LastOrderInterception;
public class LastOrderInterceptionExtension : AsyncConnectionExtension
{
public override Task<XDocument> ExecuteRequestAsync(string operation, IList<XElement> parameters, ExecuteRequestAsyncMethod execute, CancellationToken cancellationToken)
{
if (operation.Equals("SaveOrder", StringComparison.Ordinal))
return InterceptSaveOrderAsync(parameters, execute);
return execute(operation, parameters);
}
private async Task<XDocument> InterceptSaveOrderAsync(IList<XElement> parameters, ExecuteRequestAsyncMethod execute)
{
var document = await execute("SaveOrder", parameters);
var result = document.Root.Element("Result");
if (result != null && result.HasElements)
await SaveLastPlacedOrderAsync(result.Element("Order"));
return document;
}
private Task SaveLastPlacedOrderAsync(XElement orderNode)
{
var documentId = GetFieldValue(orderNode, "DocumentId");
var data = new KeyValueData("LastOrderInterceptionExtension", documentId);
return Api.KeyValueStorage.SaveAsync("LastPlacedOrder", [data]);
}
private static string GetFieldValue(XElement element, string filedName)
{
return element
.Elements("field")
.FirstOrDefault(x => x.Attribute("name").Value == filedName)
.Attribute("value").Value;
}
}