Lars-Erik's bloghttp://blog.aabech.no/blog/
Ramblings about Umbraco, .net and JavaScript development. With a sprinkle of other stuff.Articulate, blogging built on Umbraco1138http://blog.aabech.no/archive/morphing-ucommerce-products/
umbracoucommerceMorphing UCommerce Products<h2>The problem</h2>
<p>Today I had a new but fun challenge with UCommerce. Turns out, as usual, it's a great fit for my whims with architecture.
I was stuck between a rock and a hard place when I was looking at adding a custom pricing algoritm.
I can't go into details, but there's custom client pricing involved of course.
To add to the fun, we're mapping UCommerce products to DTOs for wire transfer. We could aslo have been mapping to view models or something else. To map we're using AutoMapper with quite a few configurations and jumps-through-hoops.</p>
<p>I had this code (ish):</p>
<pre><code>var products = productRepository.Select().Where(SomePredicate);
var mapped = products.Select(Mapper.Map&lt;ProductDto&gt;);
return mapped;
</code></pre>
<p>I immediately thought of a few options:</p>
<ul>
<li>Iterate over the products and change prices here</li>
<li>Create a Product adapter with additional logic and map from that</li>
<li>Execute the pricing logic from AutoMapper configuration</li>
</ul>
<p>They all seemed weird and out of place though. None seemed like they would be easy to find for the next developer. Not even with unit tests. It just didn't seem right.
Changing data on the entities would mean I'd have to go out of my way to ensure nobody went and saved those products later in the request. Creating an adapter would mean loads of new instances, bloated wrapper classes and weird names.
And finally executing business logic from AutoMapper configuration means I'd been mixing responsibilities en mass.</p>
<h2>UCommerce &amp; NHibernate to the rescue</h2>
<p>Luckily I've been using EntityFramework a lot and tried to force it into my Domain Driven Design patterns since it's infancy. I've been through the lot (and I enjoy it). So I kind of know what to expect from an ORM. When using UCommerce I'm stuck with NHibernate, but I haven't really been doing it justice by just leaving it in the background. (And fiddling with Entity Framework - which is just as good!)
Together the two systems are extremely powerful. UCommerce have even documented the possibilities,
though the documentation fails to point out the really juicy benefits.</p>
<p>We have <code>ProductDefintion</code>, right? It allows us to set up product types with different properties and variant options. It even supports inheritance. But we're still stuck with the <code>Product</code> class and its <code>GetProperty()</code> overrides. In my case, I'd like to have <code>ProductWithFancyPricing</code> so I could override that <code>GetPrice()</code> method. If I could have <code>ProductWithFancyPricing</code> and <code>ProductWithEvenFancierPricing</code> that would be totally awesome.</p>
<p>Turns out you can have your cake and eat it too. When properly using an ORM you can exploit OOP like it's supposed to and use polymorphism for varying behavior. It's possible to set up an inheritance tree so the mapper automatically handles creation of different types for you. You've basically got three options:</p>
<ul>
<li>
Table per concrete class (type)
<ul>
<li>All classes have a table of their own</li>
<li>Useful when base classes don't have (much) data</li>
</ul>
</li>
<li>
Table per hierarchy
<ul>
<li>One table per base class</li>
<li>Useful when <em>all</em> data is on the base class</li>
</ul>
</li>
<li>
Table per subclass
<ul>
<li>One common table for base data</li>
<li>Individual tables per derived class with only additional data</li>
<li>Useful when there are some data in both classes. (Think umbracoNode)</li>
</ul>
</li>
</ul>
<p>In my case, I don't need any new data on the derived classes. It's all there in <code>GetProperty()</code> anyway.
<em>(I will add some getters though. ModelsBuilder, anyone? )</em><br />
So for me it's going to be Table per hierarchy. The rest of the options are all viable for this technique if you have other requirements.
You can <a href="https://docs.ucommerce.net/ucommerce/v7.12/extending-ucommerce/extending-ucommerce-entities.html">read a bit about it in the UCommerce docs</a>.</p>
<h2>Mapping some product types</h2>
<p><em>(I inadvertently wrote document types there. ModelsBuilder, anyone?)</em></p>
<p>In order to have NHibernate treat products as subclasses with the Table per hierarchy strategy it needs a way to pick the right class for each record. That way is known as discriminator columns. I first thought I could just discriminate by the ProductDefinitionId, but it turns out NHibernate doesn't support discriminating on a column already in use for associations (foreign keys) or other means.<br />
We have to add a column. I just call it &quot;Discriminator&quot; and make it a varchar.</p>
<pre><code>alter table uCommerce_Product add Discriminator nvarchar(max)
</code></pre>
<p>Then we need some entities. I added a couple of docu... product types:</p>
<pre><code>public class ProductWithFancyPricing : UCommerce.EntitiesV2.Product
{
public override Money GetPrice(PriceGroup priceGroup)
{
var price = base.GetPrice(priceGroup);
if (IsChristmas())
{
price = new Money(price.Value * 2, price.Culture, price.Currency);
}
return base.GetPrice(priceGroup);
}
}
public class ProductWithEvenFancierPricing : UCommerce.EntitiesV2.Product
{
public override Money GetPrice(PriceGroup priceGroup)
{
var blackMarket = ObjectFactory.Instance.Resolve&lt;IBlackMarketService&gt;();
var priceValue = blackMarket.GetPrice(Sku);
return new Money(priceValue, priceGroup.Currency);
}
}
</code></pre>
<p>The next thing you need is to tell NHibernate that these are our new product classes:</p>
<pre><code>public class ProductWithFancyPricingMapping : FluentNHibernate.Mapping.SubclassMap&lt;ProductWithFancyPricing&gt;
{
public ProductWithFancyPricingMapping()
{
DiscriminatorValue(&quot;Product with fancy pricing&quot;);
}
}
public class ProductWithEvenFancierPricingMapping : FluentNHibernate.Mapping.SubclassMap&lt;ProductWithEvenFancierPricing&gt;
{
public ProductWithEvenFancierPricingMapping()
{
DiscriminatorValue(&quot;Product with naughty pricing&quot;);
}
}
</code></pre>
<p>We also need to subclass UCommerce's mapping for Product in order to tell UCommerce which column to use as the discriminator:</p>
<pre><code>public class ProductMap : global::UCommerce.EntitiesV2.Maps.ProductMap
{
public ProductMap()
{
DiscriminateSubClassesOnColumn(&quot;Discriminator&quot;);
}
}
</code></pre>
<p>Finally we need a class in the same assembly with a tag on it. <a href="https://docs.ucommerce.net/ucommerce/v7.12/extending-ucommerce/save-custom-data-in-the-database.html">More on that in the UCommerce docs</a>.</p>
<pre><code>public class MappingMarker : IContainsNHibernateMappingsTag
{
}
</code></pre>
<p>To have NHibernate pick the right classes now, we just need to fix the existing products if we have any.
I have called my discriminator values the same as my document types, so I can easily construct a query as such:</p>
<pre><code>update
ucommerce_product
set
discriminator = case productdefinitionid
when 10 then 'Product with fancy pricing'
when 11 then 'Product with naughty pricing'
else null
end
</code></pre>
<p>Now if we go...</p>
<pre><code>var products = productRepository.Select();
</code></pre>
<p>...we'll get a bounch of <code>ProductWithFancyPricings</code> and <code>ProductWithEvenFancierPricing</code>.
If you have more types, you might get into trouble though. You need to have a discriminator on them all.</p>
<h2>The final hurdle</h2>
<p>So that's cool. That's really cool. But there's one hurdle we have to jump over before we can cross the goal line. From very nasty experiences I knew I had to test <em>everything</em> manually and integrated. So I went and tried to see what happened if I added a product through the UCommerce Admin UI.</p>
<p><em>boom</em> :)</p>
<p>'Course it didn't work. It actually did, and didn't. Several weird things happened ranging from strange NHibernate mapping exceptions to products getting the discriminator &quot;UCommerce.EntitiesV2.Product&quot;. (Which makes a lot of sense if you think about it)</p>
<p>The @#¤%&amp; <code>CreateCategoryOrProduct.as[p|c]x</code> WebForms control is in our way. It instantiates a <code>Product</code> and saves it. It's completely sealed and unconfigurable. We could overwrite it with a custom one, but that would open another can of worms with regards to upgrading, source control and what-not. Luckily it's going away very very soon in UCommerce V8. (2018?)</p>
<p>After hacking at it a bit my final resolve was to add a step right after save in the product saving pipeline. Again, UCommerce is so versatile that even when it sucks, it's got a golden workaround right up its arm.
If you're not familiar with UCommerce Pipelines, <a href="https://docs.ucommerce.net/ucommerce/v7.12/extending-ucommerce/create-pipeline-task.html">go read about it here</a>.</p>
<p>Here's the extra configuration. (In a .config file included from UCommerce's custom.config)</p>
<pre><code>&lt;!-- PRODUCT CLASS FIX --&gt;
&lt;component id=&quot;SaveProduct&quot;
service=&quot;UCommerce.Pipelines.IPipeline`1[[UCommerce.EntitiesV2.Product, UCommerce]], UCommerce&quot;
type=&quot;UCommerce.Pipelines.Catalog.ProductPipeline, UCommerce.Pipelines&quot;&gt;
&lt;parameters&gt;
&lt;tasks&gt;
&lt;array&gt;
&lt;value&gt;${Product.UpdateRevision}&lt;/value&gt;
&lt;value&gt;${Product.Save}&lt;/value&gt;
&lt;value&gt;${FixProductClass}&lt;/value&gt;
&lt;value&gt;${Product.IndexAsync}&lt;/value&gt;
&lt;/array&gt;
&lt;/tasks&gt;
&lt;/parameters&gt;
&lt;/component&gt;
&lt;component id=&quot;FixProductClass&quot;
service=&quot;UCommerce.Pipelines.IPipelineTask`1[[UCommerce.EntitiesV2.Product, UCommerce]], UCommerce&quot;
type=&quot;My.Awesome.Site.Persistence.FixProductClassTask, My.Awesome.Site.UCommerce&quot;/&gt;
</code></pre>
<p>A pipeline task gets a reference to the entity being handled, so we can't just go and replace the entire product with an instance of the right type. But we can fake it and force the database value to be correct after saving.
UCommerce uses NHibernate level 2 cache, so we need to flush that as well, but we'll get to that.</p>
<p>Forcing the database is fairly easy. We have to resort to good old ADO code, which was actually a joyful little deja-vu experience (although I'm glad it was brief):</p>
<pre><code>public class FixProductClassTask : IPipelineTask&lt;Product&gt;
{
private readonly IStatelessSessionProvider sessionProvider;
public FixProductClassTask(IStatelessSessionProvider sessionProvider)
{
this.sessionProvider = sessionProvider;
}
public PipelineExecutionResult Execute(Product subject)
{
var command = sessionProvider.GetStatelessSession().Connection.CreateCommand();
command.CommandText = &quot;UPDATE uCommerce_Product SET Discriminator = @discriminator WHERE ProductId = @productId&quot;;
command.CommandType = CommandType.Text;
var discriminatorParam = command.CreateParameter();
discriminatorParam.ParameterName = &quot;discriminator&quot;;
discriminatorParam.Value = subject.ProductDefinition.Name;
var idParam = command.CreateParameter();
idParam.ParameterName = &quot;productId&quot;;
idParam.Value = subject.Id;
command.Parameters.Add(discriminatorParam);
command.Parameters.Add(idParam);
command.ExecuteNonQuery();
// TODO: Clear cache
return PipelineExecutionResult.Success;
}
}
</code></pre>
<p>I'm sure a lot of sazzy devs out there could prettify this a bit, but it does the job. Insert a <a href="/archive/kill-switch-weve-got-action/">switch/case (please don't)</a> or whatever you fancy if the product definition name isn't what you discriminate by. I'll leave it up to you to choose between strings, ints or even enums for performance vs. readability.</p>
<p>If you've turned off the level 2 cache, you might be fine with this. Otherwise we'd better &quot;evict&quot; the entity from the cache. We need to do that in order for the cached instance to change type from <code>Product</code> to <code>ProductWithFancyPricing</code>. Sadly the NHibernate <code>SessionFactory</code> in charge of doing this is hidden in an internal static field in UCommerce, so we need to resort to some nasty reflection to do it:</p>
<pre><code>// ...
command.ExecuteNonQuery();
var fieldInfo = typeof(SessionProvider).GetField(&quot;_factory&quot;, BindingFlags.Static | BindingFlags.NonPublic);
if (fieldInfo == null) throw new Exception(&quot;SessionFactory instance has moved in this UCommerce version. %(&quot;);
var sessionFactory = (ISessionFactory)fieldInfo.GetValue(null);
sessionFactory.Evict(typeof(Product), subject.Id);
return PipelineExecutionResult.Success;
// ...
</code></pre>
<p>Et voilá! We can now save new products, and they immediately morph into the correct derived type.
(Except for when being saved to RavenDB for the first time, ref. the config).</p>
<p>I'm now free to go back into the instances and implement however naughty pricing I fancy. \o/</p>
<h2>Added bonuses</h2>
<p>I already <a href="https://docs.ucommerce.net/ucommerce/v7.12/extending-ucommerce/save-custom-data-in-the-database.html">have a custom entity in the database and NHibernate model</a>. It has two associations to <code>Product</code>. Had I realized what I had under my fingertips it would already have been collections on my new shiny subclasses.</p>
<p>I recon you noticed I referenced ModelsBuilder a couple of times. How 'bout having all your properties statically typed on your product instances. How about some interfaces?</p>
<p>I'm sure you're getting the drift.</p>
<p>I for one am quite embarrased I didn't think of this before. I've had the knowledge and tools for years. But there you go. We learn something every day. And I love doing it with Umbraco, UCommerce, EntityFramework and apparently now also... NHibernate. :)</p>
Tue, 30 Jan 2018 23:48:27 Z2018-01-30T23:48:27Z