Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
DiagnosticBlock for Sitecore Commerce
/**
This block is designed to assist with diagnosing data/pipeline issues within Sitecore
Example:
services.Sitecore().Pipelines(config => config
.ConfigurePipeline<ICalculateSellableItemSellPricePipeline>(builder => builder
.Add<DiagnosticBlock<SellableItem>>("Before CalculateSellableItemListPriceBlock").Before<CalculateSellableItemSellPriceBlock>(),
order: 1001
)
);
The block logs the supplied name, a JSON-serialized representation of the argument, and the object types added to CommerceContext
**/
using System.Threading.Tasks;
using System.Linq;
using Microsoft.Extensions.Logging;
using Sitecore.Commerce.Core;
using Sitecore.Framework.Pipelines;
using Newtonsoft.Json;
namespace Sitecore.Commerce.Engine
{
public class DiagnosticBlock<TArg> : PipelineBlock<TArg, TArg, CommercePipelineExecutionContext>
{
public override Task<TArg> Run(TArg arg, CommercePipelineExecutionContext context)
{
context.Logger.LogInformation($@"BEGIN DiagnosticBlock: {Name}
Argument: {Serialize(arg)}
Context objects: {GetObjectTypes(context.CommerceContext)}
END DiagnosticBlock: {Name}
");
return Task.FromResult(arg);
}
private string GetObjectTypes(CommerceContext context)
{
return string.Join("\r\n\t", context.GetObjects<object>()
.Select(x => x.GetType().FullName));
}
private string Serialize(TArg arg)
{
try
{
return JsonConvert.SerializeObject(arg);
}
catch
{
return "(Failed to serialize)";
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment