Adding Validation MetaData to Entity Framework Auto Generated Classes

Entity Framework’s Code First is one of my favorite tools, but in my experience it is somewhat uncommon to build a database from scratch. More often you are accessing and editing data in an existing database, or modifying its schema. Thankfully, Entity Framework 6.1 introduced “reverse code first”, which is more officially known as “Code First From Database”. This pattern allows you to choose an existing database, and Entity Framework will generate the appropriate entities and DbContext classes for it. This can also be a great option if you are a fan of code first syntax but still prefer to design your databases through SQL or Management Studio.

When you first start using Code First From Database, however, it won’t be long until you run into a problem. The framework generates correct entity classes for you based on your database tables, but what happens when you want to add additional meta data to these classes? Maybe you want to enforce certain model validation rules that don’t actually exist in the database. How do we add this meta data? Sure, you can add them directly to the classes Entity Framework generates, but if the database changes and you need to regenerate the classes, you’ll loose these updates. There must be a better way!

Professional NopCommerce Training Released!

Hey there, I’m excited to announce that I have released a professional NopCommerce training course today through Pluralsight!  Pluralsight is one of the largest online training companies in the world and offers tons of great development courses. I have published Introduction to NopCommerce Plugin Development, which you can find here.  This is a greatly extended and enhanced version of the free training I released a few months ago.  The course provides almost 3.5 hours of video training, through both conceptual slides and code demos.  You will learn how to build an advanced plugin from start to finish and explore topics the other training does not cover.

This course covers the following topics:

  • Overview of the NopCommerce platform, architecture, and plugin system
  • Data Access and Infrastructure
  • Configuring, setting up and installing a plugin
  • Building Admin Interface pages
  • Working in depth with Kendo UI
  • Building front end widgets
  • Polishing the user experience through form validation, localization, and more
  • An entire module devoted to miscellaneous but important NopCommerce development tasks

Creating a Generic Repository with Entity Framework and MVC

Hey there! So, I really like Generic Repositories.  They are a very useful design pattern and are enjoyable to use once configured properly.  However, when I first started learning about this design pattern I found a lot of the tutorials out there to be overly convoluted. The goal of this article is to get you up and running with a simple but powerful Generic Repository.

This tutorial assumes general working knowledge of Entity Framework and is based around MVC, though it could be applied to other frameworks and patterns.

As a side note or disclaimer, most of the code shown here is actually slightly modified code from the open source NopCommerce ecommerce platform.  I think NopCommerce has a great implementation of a generic repository, so why rewrite the whole thing?  The whole point of this in the first place is to avoid rewriting code.  Don’t worry if you don’t even know what NopCommerce is – the code here is stand alone and has no dependency on the platform. I have simply extracted some of it out and simplified it for a tutorial.

Let’s quickly review the purpose and benefits of a Generic Repository.

Efficient MVC Redirects Using an HTTP Module

Redirects are a common necessity for websites operating in the real world.  Perhaps your marketing team wants a URL changed, or perhaps there has been an architectural change in your application that impacts its URL structure.  Maybe you’re just experimenting with SEO.  Regardless of the reason, there are a lot of ways to handle redirects in MVC.

The most common way I have seen people handing redirects is inside of an action method of their controllers.  This is probably the easiest and most straightforward way to do things.  You might see some code like this:

public ActionResult About()
{
    ViewBag.Message = "Your application description page.";

    return RedirectToAction("Contact");
}

public ActionResult Contact()
{
    ViewBag.Message = "Your contact page.";

    return View();
}

There is nothing really wrong with this strategy, especially if you’re okay with recompiling code.  However, this isn’t the most efficient way to handle redirects from a performance standpoint.  The reason for this is because ASP.NET still needs to process the entire MVC framework pipeline, just to have another request start up again.  This is not an article on the ASP.NET Request Life Cycle, but for those who are unaware, MVC Controller instantiation and Action Method invocation actually happen fairly late into the overall request pipeline.  The MVC framework is implemented through the MvcHttpHandler, which gets excuted late in the HttpApplication life cycle events.  We wanted to prevent this Handler from ever being executed.  To do this we can hook into an event that gets triggered before it and handle our redirect there.  You can see a complete list of the events at this link – we need our code to run before the PreRequestHandlerExecute event.  This is the event that begins execute of the MVC handler.

Overriding NopCommerce Admin Views and Partial Views

Overriding NopCommerce Admin Views is often a topic of confusion for Nop developers, but the task seems more difficult than it really is.  If you haven’t read my other blog post, Overriding and Adding Views in a NopCommerce Plugin,  I recommend you do before reading this.  The other reading isn’t required to understand this post, particularly if you’re adept at MVC, but it provides some additional insights.  This post is meant to be a comprehensive overview of Overriding Admin views – I will try to strike a balance between conceptual and coding examples.

So anyway, the easiest way to override a NopCommerce Admin View is to create a Custom View Engine that extends the Razor View Engine to search your plugin.  For full Views (meaning not partial views) you also need to override the corresponding Admin route and Controller Action if you want to alter logic.  This process is really no different than overriding other NopCommerce views in Nop.Web, but the Admin routes are a bit trickier because they use MVC areas.  Remember, MVC areas are like large sections of an MVC application that can contain their own controllers, views and routes.  They are a way of easily seperating major portions of your application, such as an admin area and a user facing area (as is the case with Nop).

Remember, a View Engine is responsible for finding and rendering our views.  By default the NopCommerce View Engine (ThemableRazorViewEngine) does not know it needs to search our plugin for views.  We have to create a View Engine that is aware of our plugin and proritizes it in its search locations.

Fixing Broken NopCommerce Razor Intellisense

I’ve been working with NopCommerce plugins for a while now, and for a long time I never really used Razor (at least not its intellisense).  Don’t get me wrong, I think Razor is awesome and I use it when I can, but by default Razor intellisense simply doesn’t work in NopCommerce plugin projects.  I saw a lot of people out there with the same problem and decided to get to the bottom of it.  After all, it’s a huge productivity barrier to not have full Razor support in larger projects.

It turns out this isn’t really a NopCommerce issue, but rather a Visual Studio issue.  It simply surfaces in Nop projects because of the choice to make plugins class libraries and not MVC projects or Areas.  Outside of NopCommerce I’ve never actually ran into a situation where i wanted to use Razor in a non MVC project, at first I thought it was a NopCommerce architecture issue.  However, the real problem is simply that Razor intellisense is not supported in class library projects.

There is a fairly easy way to fix this, though it feels a bit hacky.  I have seen various instructions out there for how to fix this issue – none of them worked for me so I pieced together these steps.  Here is what you do:

Advanced NopCommerce Plugin Tutorial – Data Access, Services, Kendo UI and more!

Hey there,

I recently completed a fairly extensive NopCommerce plugin tutorial.  I created this with the goal of providing a complete training series – one that takes you through the process of building a Nop plugin from start to finish and shows all the code.   The plugin is also something you can use on your own stores and is something of value rather than just a “Hello World!” test. The video series is fairly long so I have divided it into four logical sections.  Below you will find a summary of each and the associated video embedded.  The full source code is also available below.

 Download Source Code

Part 1 – An overview of the plugin, setting up our project, and getting started with data access

In this first video I will provide a demo of the completed plugin so you have an idea of what we will be building.  From there we will download NopCommerce and install it, and then create our initial plugin project in the Visual Studio solution.  We will properly configure this plugin so we have a solid base going forward.  We will then move on to some of our data access classes and set up some of the default wiring most meaningful Nop plugins require.

Trial Tracker – Empowering your NopCommerce Trial Downloads

Overview

Notice: This plugin is currently unavailable while I finish migrating the site to a new platform and updating the plugin to work with newer versions of NopCommerce.  Please check back soon!  Fill out the contact form if you would like to be directly notified.

Supported Platforms:  NopCommerce 3.3, NopCommerce 3.4

Trial Tracker is a plugin that allows you to require customers to provide a name and email before they can download any trial products.  This can be used by you for conversion optimization, analytics, mailing list generation, product trials, and other purposes.  Trial Tracker replaces one of the standard NopCommerce interfaces – after the plugin is installed, when users click on the “Download Trial” button they are first presented with a pop up to fill in their information rather than directly receiving the download.  After they submit correctly formatted information, the pop up returns their download link.

NopCommerce Plugin Localization for Validation Errors and Properties

NopCommerce features strong support for Localization, and at some point you’ll want to add this feature into your plugins. Localization allows for all of the user facing text in your plugin to be content manageable – meaning it can either be edited to say something else or translated into another language through the Admin area.  NopCommerce localization is actually pretty easy and straight forward once you know how to set things up.

I recently released a plugin you can download here that assists you with tracking trial downloads.  This plugin features pretty strong localization support so I’ll be using code samples from it in this tutorial.

The trick with localization is to turn all user facing text into String Resources, which are basically small pieces of text that can be managed through the NopCommerce admin area.  Creating string resources couldn’t be easier. Inside your main plugin class you can simply create and delete new string resources inside of the Install and Uninstall methods.  These methods are defined in the BasePlugin class that your own plugin class should inherit from.

Let’s define a few string methods that we will use for the display names of our Model properties as well as the validation errors.

Here is an example of the install method:

Understanding How Routing Works in NopCommerce Plugins

A Sample NopCommerce Route

Note: Basic working knowledge of MVC routing is assumed for this article – this is not a tutorial on what routing is or how it works, but rather a light analysis of how NopCommerce plugin routing is architected

Routing can sometimes be a challenging or confusing topic in .NET development.  There are a lot of pieces that fit together to make things work right, especially with MVC.  When working with a huge platform like NopCommerce, this is especially true due to the need for extensibility.  NopCommerce allows developers to write their own plugins and integrate them into the NopCommerce routing system.  Adding routes into your Plugin can be confusing, so let’s take a look at how this all works.  Below I have pasted a sample route from the NopCommerce plugin tutorial.

routes.MapRoute("Plugin.Payments.PayPalStandard.PDTHandler",
     "Plugins/PaymentPayPalStandard/PDTHandler",
     new { controller = "PaymentPayPalStandard", action = "PDTHandler" },
     new[] { "Nop.Plugin.Payments.PayPalStandard.Controllers" }
);

This is a pretty standard MVC (and NopCommerce) route.  MapRoute is a shorthand method that returns a new Route object that implements the default MVC Route Handler.  If we quickly analyze the parameters in order we can see there is nothing special going on here: