Custom page for schedule job status

Our customer asked for a custom dashboard that shows uses data sources, including ‘Schedule Job’ history. To achieve this we are going to use:

IScheduledJobRepository

And implementation would be quite easy:

[HttpPost]
public async Task<ActionResult> ImportHistory()
{
    var importUsersJobType = typeof(ImportUsersJob);

    var job = scheduledJobRepository
        .List()
        .FirstOrDefault(j => j.TypeName == $"{importUsersJobType.Namespace}.{importUsersJobType.Name}");

    var result = await scheduledJobLogRepository.GetAsync(job.ID, 0, int.MaxValue);

    return Json(result.PagedResult.Select(a => new
    {
        CompletedUtc = a.CompletedUtc.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss"),
        a.Message,
        Status = a.Status.ToString()
    }));
}

The schedule job type is ‘ImportUserJob’, and we are getting history data of the execution of the job:

var result = await scheduledJobLogRepository.GetAsync(job.ID, 0, int.MaxValue);

And finally return back JSON object of exection data back to FED:

return Json(result.PagedResult.Select(a => new
    {
        CompletedUtc = a.CompletedUtc.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss"),
        a.Message,
        Status = a.Status.ToString()
    }));

PS: Scott Reed mentioned there is a plugin to overview all of your scheduled jobs please find it here

Epsierver Developer Group – Winter 2020

We are back with awesome gathering (obviously online) for our awesome developers. Our agenda:

  • Darren Stahlhut presents AI 1:1 Personalisation with Episerver Content Intelligence & Recommendations – Darren Stahlhut is Technical Director of Digital @ Empired, with more than 16 years experience across .NET CMS & DXPs. Darren is an Episerver MVP and certified developer of Episerver, Sitecore and Kentico.
  • Ronil Rangaiya presents “YAML with Deployment API” to setup CI/CD pipelines in Azure DevOps – Ronil Rangaiya is Digital Technical Architect @ Empired, with more than 10 years experience designing and implementing digital experience solutions, Ronil is certified in Episerver CMS and Commerce

it will happen online at Wed, August 5, 2020, 6:30 PM – 8:00 PM AEST. We love to see you all online so if you are interested please register here.

Custom LineItemValidator

Episerver has quite nice mechanism on validating cart, line item, shipment , , promotion and inventory. I was looking into customizing the line item validtion, to inject some business logic. To do this:

  1. First create new class and inherit from ILineItemValidator
   public class CustomLineItemValidator : ILineItemValidator
    {
        private readonly ILineItemValidator defaultImplementation;
        private readonly IOrderRepository orderRepository;

        public CustomLineItemValidator(ILineItemValidator defaultImplementation,
            IOrderRepository orderRepository)
        {
            this.defaultImplementation = defaultImplementation;
            this.orderRepository = orderRepository;
        }

        [Obsolete]
        public bool Validate(ILineItem lineItem, IMarket market, Action<ILineItem, ValidationIssue> onValidationError)
        {
            if (AlreadyPurchased(lineItem))
            {
                onValidationError(lineItem, ValidationIssue.RemovedDueToUnavailableItem);

                return false;
            }

            return defaultImplementation.Validate(lineItem, market, onValidationError);
        }

        public bool Validate(ILineItem lineItem, MarketId marketId, Action<ILineItem, ValidationIssue> onValidationError)
        {
            if (AlreadyPurchased(lineItem))
            {
                onValidationError(lineItem, ValidationIssue.RemovedDueToUnavailableItem);

                return false;
            }

            return defaultImplementation.Validate(lineItem, marketId, onValidationError);
        }

        private bool AlreadyPurchased(ILineItem lineItem)
        {
            var alreadyPurchased = false;
            var customerId = lineItem?.ParentOrderGroup?.CustomerId;

            if (customerId != null)
            {
                var orders = orderRepository.Load<IPurchaseOrder>(customerId.Value);

                if (orders != null)
                {

                    alreadyPurchased = orders.Any(a => a.GetAllLineItems()
                                                            .Any(l => string.Equals(l.Code,
                                                                                    lineItem.Code,
                                                                                    StringComparison.InvariantCultureIgnoreCase)));

                }
            }

            return alreadyPurchased;
        }
    }

In our example above, we are checking to make sure if the user already purchased the item before and if that is a case we return false as a result of validation. It may be weird but our customer has this requirement and it is meaningful in their context. As you can see we are re-using existing line item validator as well.

2. Next step is to inject our new validator to the DI:

    [InitializableModule]
    public class DependencyResolverInitialization : IConfigurableModule
    {
        private static readonly ILogger logger = LogManager.GetLogger();

        public void ConfigureContainer(ServiceConfigurationContext context)
        {
            var services = context.Services;

            services.Intercept<ILineItemValidator>(
                (locator, defaultImplementation) =>
                    new CustomLineItemValidator(defaultImplementation,
                                locator.GetInstance<IOrderRepository>()));
        }
    }

As you can see on DependencyResolverInitialization class, I added a new section to intercept the ILineItemValidator. If you are not sure what I’m speaking of you can read more about it here.

If you are having ‘Commerce Manager’ make sure you do same thing in both CommerceManager and Shopfront projects!

Create a Campaign, Discount programmatically – Episerver Commerce

We had a scenario that customer wants to generate a coupon dynamically and use the coupon as credit for the user. The code as everything else in Episerver is quite straight forward:

The first step is to create a sales campaign:

        private SalesCampaign EnsureCampaignCreated()
        {
            var campaign = contentRepository
                .GetChildren<SalesCampaign>(SalesCampaignFolder.CampaignRoot)?
                .FirstOrDefault(a => a.Name == "Credit");
            
            if (campaign == null)
            {
                campaign = contentRepository
                    .GetDefault<SalesCampaign>(SalesCampaignFolder.CampaignRoot);
                campaign.Name = "Credit";
                campaign.Created = DateTime.UtcNow;
                campaign.IsActive = true;
                campaign.ValidFrom = DateTime.Today;
                campaign.ValidUntil = DateTime.Today.AddYears(1);
                var campaignContentRefrence = contentRepository.Save(campaign, SaveAction.Publish, AccessLevel.NoAccess);

                campaign = contentRepository.Get<SalesCampaign>(campaignContentRefrence);
            }

            return campaign;
        }

As you can see we just make sure the campaign is being created and our key in this stage is ‘Campaign Name’ which may be not good enough for some scenarios but for us is enough. Second I’m loading ALL campaigns and iterate through them to find a specific campaign. Again in our scenario, it will not that much effect but if the commerce you are dealing with has MANY campaigns you can use LoaderOptione as below:

Next step is to create a discount:

        private string CreateDiscountPromotion(ContentReference campaignLink, string orderNumber, Money couponAmount)
        {
            var catalougLink = siteSettingsService.StartPage.DefaultCatalogue;

            var couponCode = $"CREDIT-{Guid.NewGuid().ToString().Replace("-", "").Substring(6)}";

            var promotion = contentRepository.GetDefault<BuyQuantityGetItemDiscount>(campaignLink);
            promotion.IsActive = true;
            promotion.Name = $"CREDIT-{orderNumber}";
            promotion.Coupon.Code = couponCode;
            promotion.Condition.Items = new List<ContentReference>() { catalougLink };
            promotion.Condition.RequiredQuantity = 1;
            promotion.Condition.MatchRecursive = true;
            promotion.DiscountTarget.Items = new List<ContentReference>() { catalougLink };
            promotion.Discount.UseAmounts = true;
            promotion.Discount.Amounts = new List<Money>() { couponAmount };

            contentRepository.Save(promotion, SaveAction.Publish, AccessLevel.NoAccess);

            return couponCode;
        }

As you can see generating a discount is very straight forward. I used ‘BuyQuantityGetItemDiscount’ which fits for my purpose but you can use any out of the box or custom discount you want. Discount which I used ‘BuyQuantityGetItemDiscount’ require to define what catalog item can this discount can be applied. I’m including all current site catalog (I’m getting it from start page which is custom property) but you can use any other method (e.g. iterate through all catalogs and include all catalogs). There is a flag ‘MatchRecursive’ which is set to true, means all descendants of selected items will include in promotion.

So finally we need to call these method full code as bellow:

        private string CreateCreditVoucher(string orderNumber, Money couponAmount)
        {
            var campaign = EnsureCampaignCreated();

            return CreateDiscountPromotion(campaign.ContentLink, orderNumber, couponAmount);
        }

        private SalesCampaign EnsureCampaignCreated()
        {
            var campaign = contentRepository
                .GetChildren<SalesCampaign>(SalesCampaignFolder.CampaignRoot)?
                .FirstOrDefault(a => a.Name == "Credit");
            
            if (campaign == null)
            {
                campaign = contentRepository
                    .GetDefault<SalesCampaign>(SalesCampaignFolder.CampaignRoot);
                campaign.Name = "Credit";
                campaign.Created = DateTime.UtcNow;
                campaign.IsActive = true;
                campaign.ValidFrom = DateTime.Today;
                campaign.ValidUntil = DateTime.Today.AddYears(1);
                var campaignContentRefrence = contentRepository.Save(campaign, SaveAction.Publish, AccessLevel.NoAccess);

                campaign = contentRepository.Get<SalesCampaign>(campaignContentRefrence);
            }

            return campaign;
        }

        private string CreateDiscountPromotion(ContentReference campaignLink, string orderNumber, Money couponAmount)
        {
            var catalougLink = siteSettingsService.StartPage.DefaultCatalogue;

            var couponCode = $"CREDIT-{Guid.NewGuid().ToString().Replace("-", "").Substring(6)}";

            var promotion = contentRepository.GetDefault<BuyQuantityGetItemDiscount>(campaignLink);
            promotion.IsActive = true;
            promotion.Name = $"CREDIT-{orderNumber}";
            promotion.Coupon.Code = couponCode;
            promotion.Condition.Items = new List<ContentReference>() { catalougLink };
            promotion.Condition.RequiredQuantity = 1;
            promotion.Condition.MatchRecursive = true;
            promotion.DiscountTarget.Items = new List<ContentReference>() { catalougLink };
            promotion.Discount.UseAmounts = true;
            promotion.Discount.Amounts = new List<Money>() { couponAmount };
            
            contentRepository.Save(promotion, SaveAction.Publish, AccessLevel.NoAccess);

            return couponCode;
        }

Discount and promotion has far more features that I haven’t included, you can read more about it HERE

Episerver Ascend Sydney 2020

First Episerver Ascend in the APAC area was very exciting. First I realized how many friends I found through Episerver and it is not just the platform I loved it helped me to find heaps of good friends.

Starting the day Episerver Regional Director APAC Natalia Gamarra kicked off the event with the agenda:

Next Episerver CEO Alex Atzberger spoke about Personalization and Privacy and how it can change the user acquisition:

And focus of Episerver to “empowering growing companies to compete digitally”

Jacob Khan VP, Solution Architecture spoke about the road map and Episerver focus on the personalization:

Next presenter was Niteco spoke about best practices when dealing with digital transformation. Nicola Ayan started with best technical best practices for digital transformation:

And then Michelle Tran follows the conversation on best practice for design and strategy:

Next Empired spoke about a digital project for Laser Clinics. Kevin Miller presented on behalf of Empired and Louise Chamberlain on behalf of Laster Clinics.

Deane Barker had a really good presentation about the content. He thinks “Content ha a soul” which is I agree with him, we need to think about the content as part of our solution:


And this is my favorite:

And finally Adi Wickramaratne on behalf of St John New Zealand. LEVO Digital did the digital transformation.

No alternative text description for this image

IT was really nice day, learned heaps and see many old friends. Thanks so much, Episerver, especially

Alexander Atzberger

Joey Moore

Natalia Gamarra

Jacob Khan

Malin Dahlin

Frankie Lui

“Some” best practices I learned on commerce personalization

The concept of personalization is a wide range. I’m working on a project that needs personalization and started to learn. One cool thing I learn from “Foundation” project (Foundation is a very good sample of all Episerver offerings) is how to build a code to use Episerver Tracking Commerce. Again I’m learning and please advise me if I can improve any part of it 🙂

Please read through how to install tracking Nuget package from here

The next step is to create a separate project in your solution and add a commerce tracking package to the solution. Then add a class as below:

public interface ICommerceTrackingService
    {
        Task<TrackingResponseData> TrackOrder(HttpContextBase httpContext, IPurchaseOrder order);
    }

    public class CommerceTrackingService: ICommerceTrackingService
    {
        private readonly IContextModeResolver contextModeResolver;
        private readonly TrackingDataFactory trackingDataFactory;
        private readonly ITrackingService trackingService;
        private readonly ServiceAccessor<IContentRouteHelper> contentRouteHelperAccessor;

        public CommerceTrackingService(IContextModeResolver contextModeResolver,
            TrackingDataFactory trackingDataFactory,
            ITrackingService trackingService,
            ServiceAccessor<IContentRouteHelper> contentRouteHelperAccessor)
        {
            this.contextModeResolver = contextModeResolver;
            this.trackingDataFactory = trackingDataFactory;
            this.trackingService = trackingService;
            this.contentRouteHelperAccessor = contentRouteHelperAccessor;
        }

        public async Task<TrackingResponseData> TrackOrder(HttpContextBase httpContext, IPurchaseOrder order)
        {
            if (contextModeResolver.CurrentMode != ContextMode.Default)
            {
                return null;
            }

            var trackingData = trackingDataFactory.CreateOrderTrackingData(order, httpContext);
            return await trackingService.TrackAsync(trackingData, httpContext, contentRouteHelperAccessor().Content);
        }
    }

I put both interface and class in the same file to simplify the post but if you want you can separate them.

Next step is to change you StructureMap to scan new project (this is optional depending on your StructureMap structure)

            context.StructureMap().Configure(config =>
            {
                config.Scan(scan =>
                {
                    scan.TheCallingAssembly();
                    scan.Assembly("EPiServer.Sample.Commerce.Personalization");
                    scan.WithDefaultConventions();
                    scan.LookForRegistries();
                });
            });

The next step is to call the track order. We want to do that when the order is being placed. So after cart converted to purchase order you can call your TrackOrder function:

commerceTrackingService.TrackOrder(httpContext, purchaseOrder);

This will push all relevant data from order to tracking engine to help the recommendation engine to get a better understanding of the user behavior.

I recommend to checkout “Foundation” project that has a very comprehensive sample.

Episerver and ASP.Net Core

Recently Episerver announced for Episerver ASP.Net Core program. This is really exciting news, as .Net Community (aka Microsoft!) announced focus more on .Net Core (means no more new version of .Net Framework!). Details of how Episerver is going to do it will be available here. So what is good about it:

  • The presentation layer can be written on lovely ASP.Net Core platform
  • .Net Core is lightweight compare to .Net framework. The presentation conceptually would be lean and faster! (I not sure if it would be a case anyway!)
  • Developers would be happy that they are working on edge technology!

Now what I think would be interim challenges until upgrading the whole platform:

  • Running two applications (for CMS) and three applications (for Commerce).
  • For page rendering, another HTTP call required that to be a potential failure point – means when something goes wrong developer needs more time to find the issue and that means more APPLICATION LOGGING!
  • Page Templates (aka Razor Templates) should be running on both PRESENTATION and EDITOR view. This perhaps makes it quite complicated as now we need ANOTHER project to share MODELS! And the concept of ‘Feature Group‘ we are using for a while needs to be reconsidered – Having said that there could be some ways to avoid duplicated views!

I have a very positive feeling about this Episerver move and I know it would be complicated both for Episerver Devs and external Devs and we all love challenges!

Sydney Episerver Meetup – Winter 2019 – Outcome

It was a really good gathering and I personally learn a lot.

Damien Dias from Episerver went through Episerver CMS and eCommerce certification exams. He gave a very good brief about what is his journey to get the certifications and shared tips around the main area of the exams.

The second part we had Darren Stahlhut from Luminary that he spoke about the really cool framework called Blazor from Microsoft (it is still not released!) and he married up Blazor with Episerver which was really cool. You read about it more here.

UPDATED – Episerver Sydney Winter 2019 Meetup

I’m so excited about this meetup. It is going to be on 10 July 2019 6pm – 8pm at Episerver Sydney office! In this session:

Damian Dias will talk about Commerce and CMS Certifications best practices.

Nicola Ayan will talk about Episerver Find and share lessons learned from recent projects.

Marcus Babajews will give you a short update on Episerver Campaign

UPDATE: We are so excited that Darren Stahlhut is joining us and present Episerver Blazor a proof of concept and add-on Episerver Cognitive Services. We are so excited to have him in Sydney 🙂

Please signup via link below:

https://www.eventbrite.com/e/episerver-developer-meetup-sydney-tickets-62842623980

Episerver CMS Cheat Sheet

During the time I worked with CMS, I built up list of some cool stuff. I thought to share them with you. Maybe in future we can have a Episerver CMS/Commerce cheat sheet or knowledge based in Github so we can all use them. This is just beginning 🙂

==========================CUSTOM LINK ITEM COLLECTION RENDERING=====================================
    @Html.PropertyFor(m => m.MainBody)

    // FullRefreshPropertiesMetaData asks on-page edit to reload the page 
    // to run the following custom rendering again after the value has changed.
    @Html.FullRefreshPropertiesMetaData(new []{ "RelatedContentLinks" })

    // EditAttributes enables on page-edit when you have custom rendering.
    <p @Html.EditAttributes(m => m.CurrentPage.RelatedContentLinks) >
    @if (Model.CurrentPage.RelatedContentLinks != null)
    {        
        <span>See also:</span>
        foreach (LinkItem item in Model.CurrentPage.RelatedContentLinks)
        {
            <a href="@item.Href">@item.Text</a>
        }
    }
    </p>
    ...


-------------------------------------------OR-------------------------------------------------------
    ...
    @Html.PropertyFor(m => m.MainBody)

    <h2>Releated Content</h2>
    @Html.PropertyFor(m => m.CurrentPage.RelatedContentLinks, "SeeAlso")
    ...
----------------------------------------------------------------------------------------------------
	
	
-------------------------------------------OR-------------------------------------------------------	
public class ArticlePage : PageData
{
    ...

    [UIHint("SeeAlso")]
    public virtual LinkItemCollection RelatedContentLinks { get; set; }

    ...
----------------------------------------------------------------------------------------------------


TIPS:
-----------
global folder for the media and block -> EPiServer.Core.SiteSettings.Current.GlobalBlocksRoot
site folder for the media and block EPiServer.Core.SiteSettings.Current.SiteBlocksRoot
-----------
Loaders:
IContentLoader (just readonly) vs IContentRepository  (CRUD) vs DataFactory (legacy, backward compatibility)
-----------

- Attributes:
Content Types: [ContentType], [Access], [AvailableContentTypes], [ImageUrl]

Property: [Display(
            Name = "Classification",
            Description = "Genre or type of article.",
            GroupName = "Details", Order = 2)]
			
Group: 
[GroupDefinitions]
public static class GroupNames
{
   [Display(GroupName="MyNews", Order=1)]
   public const string News = "News";
   [RequiredAccess(AccessLevel.Publish)]
   public const string Contact= "Contact";
}


Version status 
	NotCreated. The version has not been saved yet.
	CheckedOut. The currently edited version
	AwaitingApproval. The editor is done and has marked the version as ready for approval
	Rejected. The version did not pass the approval
	CheckedIn. The version is approved and ready for publish
	DelayedPublished. The version will be automatically published at a future date and time
	Published. The version is published
	PreviouslyPublished. The version has been published but is now replaced with a different version
	
Status transitions
	Default/None. Saves a version maintaining the current status unless a new version is created. In this case the new version is created in a checked out state. (Default has replaced None in CMS 10)
	Publish. Publishes a version.
	Schedule. Schedule a version for automatic publishing at a later date. (New in CMS 10)
	CheckOut. Checks out a version to indicate that it is being worked on. (New in CMS 10)
	CheckIn. Checks in a version indicating that it is ready to be published
	RequestApproval. Saves a version to a state indicating that it is ready to be approved
	Reject. Rejects a version. This is normally done during an approval review.
	Save. Save action which outcome will depend on the current status. Will in some cases maintain the status and in other cases check out the current version.
Optional parameter
	ForceNewVersion. Specifies that the content saved should be created as a new version.
	ForceCurrentVersion. Specifies that the save should update the existing version.
	SkipValidation. Specifies that the content should be saved without performing the usual validation.
	SkipSetCommonDraft. Specifies that the version should not be set as common draft (the version used by default in the CMS edit user interface)
	DelayedPublish. Used in combination with SaveAction. CheckIn to specify that the version should be automatically published at a future date and time. (Deprecated in CMS 10)
----------------------

force to save/publish by anonymouse user (e.g. schedule job) contentRepository.Save(myPage, EPiServer.DataAccess.SaveAction.Publish, EPiServer.Security.AccessLevel.NoAccess);


custom icon for content type:

[UIDescriptorRegistration]
public class ContainerPageUIDescriptor : UIDescriptor<ContainerPage>
{
	public ContainerPageUIDescriptor()
		: base("epi-iconObjectPage")
	{
	}
}

change the default view

	[UIDescriptorRegistration]
	public class StartPageUIDescriptor : UIDescriptor
	{
		public StartPageUIDescriptor(): base(ContentTypeCssClassNames.Page)
		{
			DefaultView = CmsViewNames.AllPropertiesView;
			EnableStickyView = false;
		}
	}
	
change the default icon of media

[UIDescriptorRegistration]

public class DocumentUIDescriptor : UIDescriptor<Document>
{
    public DocumentUIDescriptor() : base("icon-document")
    {
        DefaultView = CmsViewNames.AllPropertiesView;
    }
}
	
change editor descriptor

	[EditorDescriptorRegistration(TargetType = typeof(string))]
	public class StringEditorDescriptor : EditorDescriptor
	{
		public StringEditorDescriptor()
		{
			ClientEditingClass = "dijit.form.ValidationTextBox";
		}
	}
====================================================================================================


TemplateResolver

The EPiServer.Web.TemplateResolver.TemplateResolving event is raised. If an event handler selects a template, that template is used with no further handling.
All templates matching the desired content type are filtered according to the rendering mode: If t is a page, a suitable controller is selected; if it is partial rendering, a suitable partial controller or partial view is selected. For partial templates, the list is filtered according to main template.
If the template is requested with a specific tag, the list is filtered on that tag. If no template matching the tag exists, all templates from 2 are taken into account.
If any display channel is active, and there are template tags matching that channel, templates are filtered for DisplayChannel. 
From remaining templates, the shortest inheritance chain to the TemplateModel marked as Default and not inherited, is selected.
If no match from 5, the shortest inheritance chain to TemplateModel that is marked as Default, is selected.
If no match from 6, the shortest inheritance chain to TemplateModel, is selected.
The EPiServer.Web.TemplateResolver.TemplateResolved event is raised, providing a chance to replace the selected template.



--------------------------custom root folder for block selector----------------------------
[UIHint("teaserblock")]
public virtual ContentReference TeaserBlockReference { get; set; }

[EditorDescriptorRegistration(TargetType = typeof(ContentReference), UIHint = "teaserblock")]
public class BlockReferenceEditorDescriptor : ContentReferenceEditorDescriptor<TeaserBlock>
{
    public override IEnumerable<ContentReference> Roots
    {
        get
        {
            //Sample to override the default root for the repository.
            //Take the reference from configuration or site initialization and do not hard-code it.
            return new ContentReference[] { new ContentReference(90 ) };
        }
    }
}

-------------------------------------------------------------

PERMISSION:

- Protecting a controller via a permission

   [AuthorizePermission("MyCustomPermissions", "EditSettings")]
    public class EditSettingsController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
	
- 

  [PermissionTypes]
    public static class MyCustomPermissions
    {
        public const string GroupName = "MyCustomPermissions";

        static MyCustomPermissions()
        {
            EditSettings = new PermissionType(GroupName, "EditSettings");
            ViewSettings = new PermissionType(GroupName, "ViewSettings");
        }

        public static PermissionType EditSettings { get; private set; }

        public static PermissionType ViewSettings { get; private set; }
    }
	
--------------------------------------------------------------------------
Property settings:

[EPiServer.Core.PropertySettings.PropertySettings(typeof(CustomStringSettings), true)]
public class CustomPropertyString : PropertyString
{
}

[ModuleDependency(typeof(EPiServer.Web.InitializationModule))]
    public class PlugInInitialization : IInitializableModule
    {
        public void Initialize(InitializationEngine context)
        {
            PropertyControlClassFactory.Instance.RegisterClass(typeof(PropertyString), typeof(CustomPropertyString));
            PropertyControlClassFactory.Instance.RegisterClass(typeof(PropertyLongString), typeof(CustomPropertyString));
        }

        public void Uninitialize(InitializationEngine context)
        {
        }
    }