0
votes

I am implementing a custom module in Orchard to track the number of views for each content item. In my handler, I am checking to see if the content item's type is the default Orchard "Page" type, but right now it is using the Equals function and magic strings. Here's my code:

public class ContentItemViewRecordHandler : ContentHandler
{
    private readonly IOrchardServices services;
    private readonly IRepository<ContentItemViewRecord> repository;

    public ContentItemViewRecordHandler(IOrchardServices services, IRepository<ContentItemViewRecord> repository)
    {
        this.services = services;
        this.repository = repository;

        OnGetDisplayShape<CommonPart>(RecordView);
    }

    private void RecordView(BuildDisplayContext context, CommonPart part)
    {
        var contentItemType = context.ContentItem.ContentType;

        // THIS IS THE IF STATEMENT IN QUESTION
        if (!contentItemType.Equals("Page", StringComparison.CurrentCultureIgnoreCase))
        {
            return;
        }

        var contentItemViewRecord = new ContentItemViewRecord
        {
            ContentItemRecordId = context.ContentItem.Id,
            Username = services.WorkContext.CurrentUser.UserName,
            HostAddress = services.WorkContext.HttpContext.Request.UserHostAddress,
            DateCreated = DateTime.UtcNow
        };

        repository.Create(contentItemViewRecord);
    }
}

Anyone know if there is a way to determine the content item's type without the magic strings?

1

1 Answers

2
votes

Content types are not .NET types. They are dynamic entities that only exist at runtime. Strings are therefore perfectly fine to identify them.