Pages - Menu

nopCommerce - Hello World to Multi Tenancy

Finally, it is about time to do some multi tenant works. Let's recap my goal and how I am travelling so far.

Scope

  • Build a multi tenant e-commerce platform for 15 or more international brands.
  • They are completely different brands and target consumers are completely different.
  • They will share some similarities in terms of functionalities but there will be customizations for individual brands
  • Administrator of a brand can only see stuff about their own brand.
  • Easy to develop
  • Easy to deploy
  • Easy to maintain
  • There is NOT necessary a super admin role to overlook ALL the brands.
  • Customers are NOT shared across brands.

Preparation

So far, I have built my first brand with the above scope in mind, the following strategies were implemented.

Specification

Since our first site went live, we are now ready for our next brand and the following needs to bear in mind with the followings:
  • Separate the brand specific codes in separated dll.
  • Database to be considered at later stage.
  • No brand specific code at controller level.
  • Views for different brands are handled by Nop Theme.
  • We will deploy for all the brands from the same Visual Studio Solutions.

Decision Making

Get Dirty with Code


Project Setup

Notice I am skipping some of the steps and only covering the key points. (eg. Add references, routes, register dependency etc...) They are covered previously.


I created a Misc Service and an interface for our platform.


Then I create brand specific services in the relevant projects.







Build Configuration

With the default Debug configuration, we will clone a set of new build configs per projects. In each build, we only include one brand dll at a time. (Only service dll in this example)






Only for the relevant build configurations of the brand projects, we will set the dll output path to the same as the Nop.Web project.



Controller

We setup a controller that will consume ITAMiscService and return the brand name. Notice how the controller does not have knowledge to the concrete class but only the ITAMiscService interface.



Hello World to Multi Tenancy


Who am I?

By changing the build configuration, I am able to change my workspace to the corresponding brand.







This is achieved by a MS Build trick.
  • The brand projects are not referenced anywhere (very important)
  • Therefore, when we build Debug, there will not be any brand specific dlls.
  • We used build configurations to trick MS Build to dump the brand dll to the web project for relevant brands.
  • Autofac reflection will pick up the brand dll if they exists, because of the way how Nop Dependency Register works.

Caution

  • Use clean solution in between the building of different brand environments (to delete any brand dlls).
  • Pay attention to the dlls in the Nop.Web bin folder. Occasionally the clean solution do not delete everything in the bin folder. Then we will need to manually clear this folder.
  • Always check Who am I to make sure you are working in the right brand.

Further Improvement

  • It is not so easy to deploy, as I need to build the project once per brand (so it will generate different dlls)
  • Unfortunately in practice, clean solution doesn't always work. For anyone who familiar with MS Build, we could create pre-build event to properly clean up the solutions (instead of relying on Visual Studio)
  • Combine MS Build with PowerShell, we can implement a way to "quick switch" dlls for different brands.

TSQL - Delete Duplicate Rows Basic Techniques

Scope

From time to time, I will be asked to delete duplicate rows from the database. This is a very easy job but if you don't know the trick, it might get you off-guarded.

In this exercise, we are trying to find out if there are any products with the same SKU in the system and remove all the duplicates but leave one alone.

Steps

First we will check if any duplicates by using group by and having.

select Sku, count(Sku) as Cnt
from Product
group by Sku
having count(Sku) > 1

We found 245 duplicate products.

We will verify the above by checking the product id.

select P.[Id], Duplicates.Sku
from Product P
join (select Sku 
      from Product
      group by Sku
      having count(Sku) > 1) Duplicates on (Duplicates.Sku = P.Sku)

The same SKU shown with different product ids.

The trick we use is use aggregation to group them together and pick the odd one we want. Showing all the duplicate products with only 1 row per sku by their max id, and leave the duplicates out of this result set.

select max(P.[Id]) as Id, Duplicates.Sku
from Product P
join (select Sku 
      from Product
      group by Sku
      having count(Sku) > 1) Duplicates on (Duplicates.Sku = P.Sku)
group by Duplicates.Sku

We picked our 245 products that we will keep.

The last thing to do is to remove the duplicates except the ones we picked. This is by using delete from. Notice the deived table in the query are from previous checking code.

delete Product
from (select max(P.[Id]) as Id
      from Product P
      join (select Sku 
            from Product
            group by Sku
            having count(Sku) > 1) Duplicates 
                                          on (Duplicates.Sku = P.Sku)
      group by Duplicates.Sku) ProductToDelete
where Product.Id = ProductToDelete.Id

245 rows with duplicate SKUs deleted.

What if?

Sounds too good to be truth? What if the following scenario arise, can we still do it?
  • A legacy SQL table doesn't have ID nor primary key for us to use group by on.
  • Need to find out duplicate values of whole row or multiple fields of a row and not just 1 field (in my case SKU)
The common fallency is that we need to use cursor, multiple sql scripts or a console app to loop through something. In fact not, it is achievable with T-SQL only and these are typical job interview questions that I would ask (as an interviewer) in the SQL area. :)

HttpWebRequest Error. The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

Scope

In an attempt to use HttpWebRequest to make https call to our server, I got the error of

The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

Pretty self explained that it is complaining about SSL certificate or security issue or UTC clock offset etc. For my purpose, this is a local server that I am calling and I am not transferring sensitive data anyway, so I am not worrying about SSL security.


Solution

try
{
    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });

    var req = HttpWebRequest.Create(url);
    var res = req.GetResponse();

    using (var stream = res.GetResponseStream())
    {
        using (var sr = new StreamReader(stream))
        {
            return sr.ReadToEnd();
        }
    }
}
catch (Exception ex)
{
    Console.WriteLine("Exception caught: " + ex.Message);

    return string.Empty;
}


All it take is the first line of ServerCertificateValidationCallback delegate to return true, the rest is just standard HttpWebRequest call.

Create a Script for Daily SQL Backup Job with Unique Name

Scope

Create a SQL script or job that manage daily sql backup with various options.

Code

The below script is generated from Sql Server Management Studio with my own little tweak that append a timestamp to the file name. This will create backup with file name MyDatabase_yyyy-mm-ddThh.mi.ss.mmm.bak
Declare @SQLPath nvarchar(4000)
Set @SQLPath = N'D:\Backup\MyDatabase_' + Replace(CONVERT(nvarchar(30), GETDATE(), 126), ':', '.') + '.bak' 
BACKUP DATABASE [MyDatabase] TO DISK = @SQLPath WITH NOFORMAT, INIT, NAME = N'MyDatabase-Full Database Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10

GO

PS. According to Microsoft. By default, SQL server will backup as NOINIT (append). For those who do not use the timestamp and always backup to the same filename, must make sure the right options are set for INIT or NOINIT depending on backup strategy of the business.

Example

A simple cursor example that does backup on all user databases and override the last backup.
DECLARE @name VARCHAR(50)
DECLARE @path VARCHAR(255)
DECLARE @fileDate VARCHAR(20)
DECLARE @fileName VARCHAR(255)
 
SET @path = 'D:\Backup\'  
SET @fileDate = Replace(CONVERT(nvarchar(30), GETDATE(), 126), ':', '.')

DECLARE db_cursor CURSOR FOR  
SELECT name 
FROM sys.databases
WHERE name NOT IN ('master','model','msdb','tempdb') -- system databases
and [state] = 0 -- online
 
OPEN db_cursor   
FETCH NEXT FROM db_cursor INTO @name   

WHILE @@FETCH_STATUS = 0   
BEGIN   
       SET @fileName = @path + @name + '.bak'  
       BACKUP DATABASE @name TO DISK = @fileName
       WITH NOFORMAT, INIT, 
       SKIP, NOREWIND, NOUNLOAD, STATS = 10

       FETCH NEXT FROM db_cursor INTO @name
END   

CLOSE db_cursor   
DEALLOCATE db_cursor

Xml Deserialization with Namespace Prefix in C#

Scope

  • To deserialize an xml from a 3rd party vendor into a strongly typed C# object.
  • The xml has a namespace attached.
  • No DTD or XSD were provided by vendor.

Steps

XML Schema Definition Tool (Xsd.exe)



Basically 2 command lines I executed:
  1. I first created the xsd file from a sample xml file that I have.
  2. Then I created the cs class file for the model by using the xsd scheme. 

Model

It is the best to generate model via Xsd tool because it contains a lot of System.Xml.Serialization Attribute that are needed for the serializer. Especially around the namespace area!! 

The class file will look something like this. A typical model class with lots of attribute hints.



Serializer

All the hard works were done for generating the model and xml attributes. That left this part a bit simple in comparison. It is a bit similar to Autofac, where the hard works are done at the entity level and the actual conversion is just 1 line of ToEntity().

The code looks like this. Some people managed to do this in 2 lines, but I found 4 lines look pretty neat for readability and my troubleshooting.



Troubleshoot


Unbounded Complex Type Bug

1 of the error that I ran into looks like this.

Unable to generate a temporary class (result=1). error CS0030: Cannot convert type

It is a confirmed Microsoft bug and won't be fixed.

The work around is to change the unbounded or add a dummy element for the complex type.


I added the element and regenerated the model class file, and the serializer is happy again.

Xsd generated incorrect schema

The xml schema reverse engineered by using xsd.exe from a sample xml file is slightly incorrect. It predicted I might have multiple child nodes, thus the class generated had all these unnecessary array declaration.

Looks like this.

   1: public MyComplexType Notes []


I would not blame the xsd tool but there are some manual works required to fix it. (Or C# code will end up with a lot of .FirstOrDefault()

XElement.Name.LocalName

As described before, there is a fallency of trying to access the element via XElement.Name. This method only works when there is no namespace. Out of curiosity and I read further that the correct way is to use XElement.Name.LocalName. I wouldn't recommend going down this path, but it is interesting to know that how we conventionally accessing an element name incorrectly (when you have namespace).

http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.name%28v=vs.110%29.aspx

My first nopCommerce website gone Live!!

nopCommerce

After spending 6 months with this open source nopCommerce platform. My first nopCommerce website finally went live. http://www.thenorthface.com.au 

Scope

Our business requirement in a nut shell:-
  • Build a multi tenant e-commerce platform to cater all of our brands.
  • All our brand sites are independent to each others in terms of development requirements or target audience. Only the main workflow is the same.
  • We have multiple integration points that we need to interact with. (Not surprise!!)
  • The first brand is The North Face

Challenges

  • 6 Integration Points
    • CRM (Customer Information)
    • CMS
    • Payment Gateway (CyberSource)
    • Promotions / Product Price (1 way coming in from other integration point)
    • Inventory System
    • Product Reviews
  • 2 Console Apps
    • Bulk Image Upload
    • Inventory System / Price

Thoughts of nopCommerce


Likes

  • Open Source
  • MVC
  • Easy to learn
  • The source code is fairly solid and clean. There were likes and hates, but I am generally happy.
  • Plugins readily available to purchase or easy to build your own
  • Payment workflow is rock solid and easy to integrate with (I am using CyberSource)
  • Multi-tenancy semi-friendly
  • Multi-store ready
  • Admin interface out of the box is nice and professional enough
  • Good support from the official forum

Dislikes

  • There is no Controller Factory in their MVC architecture. I kind of expected that for a "platform"
  • Telerick MVC for admin (but they are now using Kendo UI in v3.3, which is good now)
  • Easy to customize? This is an arguable point. Surely it wasn't hard but could be easier. As a platform, I would like to see the core code set to protected/virtual (to allow custom code override) and more hooks (empty protected class) in the core controllers.

The North Face Australia

A quick comparison of old and new site. Which one do you like more?

Level 1 (Root) Category 

 


L: The level 1 category is a little messy. At the root level, it shows everything from all the child categories.
R: The level 1 category shows featured products of level 2 categories, this is now organized in a systematic way that allow administrator to decide what to show. 

Level 2 (Children) Sub-Category 

 


Color variants of the same product no longer clogging up space. 
We can now show more variety of products on category page.

Category Page - Filter

 


Color filters now more colorful than ever!!

Product Detail Page

 


Customer can choose different color on product detail page.

Shopping Cart

 


Demo

Not too bad? Why not try it out yourself? It may change your decision making should you need to choose an ecommerce platform next time. Definitely recommended.

A potentially dangerous Request.Form value was detected from the client

Troubleshoot

A potentially dangerous Request.Form value was detected from the client

One of the error I am getting when performing a form post with HTML tags in .Net.

Solutions

Web.config


One of the StackOverflow 150+ voted answer was this. 

<httpRuntime requestValidationMode="2.0" />

Put this in the Web.config and it will work. It is not my taste to change a site wide config for a form post though. I potentially want to block all other requests that post potentially dangerous HTML tags but except my Simple method.

ValidateInput = false


One of the simple solution available on the net is this. Set ValidateInput to false.



This works, but it potentially allowing the post not to check validation. I think I can still do better!!

AllowHtml


Potentially, I am setting AllowHtml attribute to a field that I would allow html. Everything else stay away.