Vergosity Rule Engine + Fluent API

The Vergosity Rule Engine is now easier to use with Fluent API features. Basically, there is a ValidationContext object that  you can add and configure rules using fluent API style syntax. If you are not familiar with the ValidationContext – it is contained in the Vergosity.Validation namespace. And if you are not familiar with Vergosity, you can get from Nuget: Install-package Vergosity.Framework. Or search by “Vergosity” in your “Manage Nuget Packages” reference option.

image

ValidationContext

The Vergosity Rule Engine contains a set of rules already implemented. You can start by adding them to an instance of the ValidationContext. There are (2) ways to use the new Fluent API. You just need to create an instance of the ValidationContext.

ValidationContextBase context = new ValidationContext();

Simple

Option 1, shown below is the easiest way to add a new rule to the ValidationContext. All of the new Fluent API calls are prefixed using “With”. This provides a nice filter for your methods. Below, an entity is setup for the unit test and is used as the target parameter in the IsNotNull rule.

image

When you call the RenderRules() method of the ValidationContext – you can retrieve the results from the Results list. You can use the results any way you prefer in your application. The ValidationContext also contains results filtered by the Severity indicated in the rule configuration.

  • ValidationContext.ExceptionResults;
  • ValidationContext.InformationResults;
  • ValidationContext.WarningResults;

image

With Configuration

The unit test below shows another option that includes rule configuration – this is where the fluent api really helps out. After you add the rule to the ValidationContext, you are ready to start configuring the specified rule using a set of methods that are prefixed by “With”.

image

Custom Business Rules

There will be situations where you need to create a custom business rules. The Vergosity Framework contains the framework classes for you to create simple or complex rules. We will show you how to create these rules – and then use them in your code.

Simple Rule

Simple rules inherit from the Vergosity Framework class called Rule. You modify the constructor to send in your target. The Render() method is where you implement the rule’s validation logic. You will need set the IsValid property to true/false based on the rule logic – then, you will return a new Result object as show below.

Simple rules allow you create rules that can be used or composed into composite rules. The rule rendering using the ValidationContext is consistent whether the rule is a simple or composite rule. Therefore, you have a lot of flexibility in managing business rules for you business logic.

image

Composite Rule

You can create a custom rule that contains any of the default rules and/or other custom rules. This allows you to compose your custom rule to contain whatever rule-set you require for you business logic. The composite rule will inherit from the Vergosity Framework class called: RuleComposite. Creating a custom rule allows you to reuse the rule from one or more locations in your code. You are also encapsulating the rule implementation into a single rule – therefore, you will only have one place to modify or extend you rule implementation.

Building the rule set is similar to the previous example in the unit tests. However, in the actual rule, you use the Rules list to add rules.

image

The following is the code snippet from the composite rule class. If you have noticed the WithPriority setting, this allows you to set or arrange the order that the rules are evaluated.

this.Rules.WithStringIsNotEmptySpace(entity.Name)
    .WithName(“NameIsValid”)
    .WithMessage(“The name value is not valid.”)
    .WithPriority(100)
    .WithSeverity(Severity.Exception);

this.Rules.WithAreNotEqual(entity.DateOfBirth, new DateTime())
    .WithName(“DateIsInitialized”)
    .WithMessage(“Date contains the default DateTime value.”)
    .WithPriority(200)
    .WithSeverity(Severity.Exception);

this.Rules.WithRange(entity.FavoriteNumber, 1, 100)
    .WithName(“FavoriteNumberIsValid”)
    .WithMessage(string.Format(“The favorite number value is not within the specified range: {0}-{1}”, 1, 100))
    .WithPriority(300)
    .WithSeverity(Severity.Information);

this.Rules.WithGuidIsValid(entity.Id)
    .WithName(“IdIsValid”)
    .WithMessage(“The entity id is not valid. Cannot be empty Guid value.”);

Code Generation :: Vergosity, Razor Engine & Entity Framework

I recently created a Code Generation tool that targets a set of entity items in a .NET project – to generate an entire .NET stack that includes a Service, Business and Data Access Layers. Because Entity Framework has database migration tools I can leverage my Entity Framework DbContext (that is generated) to also create a database based on the specified DbContext. I can do this in less than 10 minutes. I think that is productive, right?

The application leverages the Vergosity Framework and a light-weight enterprise architecture. I felt that once I had the architecture in place and realized the patterns were repeatable, I was ready for code generation. It has been a few years since I have worked with a code generator. The first consideration of code generation is to define the source that will be used to generate code. The second consideration are the templates. Then you bind the source with the template to create the output. Sounds pretty straight forward. You have some binding options when you are using .NET (i.e., T4Templates, Razor Engine). I chose the Razor Engine because this allowed me to use Razor syntax in Visual Studio to create my templates (.cshtml) files – this turned out to be the easiest part of creating the code generator. I’ve worked with T4Templates in the past. I do not have anything against them, just wanted to try something different.

Try it out for yourself…You can get the installer on GitHub (https://github.com/buildmotion/CodeBuilder-Install) or you can download the actual source code and see how it works.

Download the BuildMotion.CodeBuilder

You will need to get the source code which is contained in (2) projects on GitHub. The CodeBuilder requires a reference to Vergosity.Services and to the latest version of the Vergosity Framework (available on NuGet).

Here is a screen shot of the main window for the Code Builder. It was built using WPF on top of the Vergosity Framework for handling all of the business actions. The application doesn’t use a database, although I could see some future feature that saves the configuration.

image

Recipe for the Application

I would recommend starting out with a new or existing C# .NET Class Library project. You will want to make some NuGet package references.

1. Reference the Vergosity Framework & Vergosity.Services

You can reference the Vergosity framework with one of (2) ways using NuGet.

Package Manager Console: Install-Package Vergosity.Framework

URL: https://www.nuget.org/packages/Vergosity.Framework

The Vergosity.Services source code and project is located on GitHub. You will need to reference this project for both the BuildMotion.CodeBuilder and your target application.

GitHub: https://github.com/buildmotion/Vergosity.Services

2. Create or Modify Existing Entity

You will want to create or modify your entity classes. Make sure your entity classes inherit from Vergosity.Entity.IEntity or some other distinct interface. You might need to create one for you entity classes. This will be used by the code generator to target all classes in your project that implement or inherit from the specified type.

Ex: public class Customer : Vergosity.Entity.IEntity

image

3. Add Identifier Properties to your Entities

Make sure your entity have identifier properties. If you are using the Vergosity.Entity.IEntity interface – you will need to implement the Id property as a System.Guid.

4. Add reference to the DataAnnotations namespace

We are going to use some annotations to provide information to Entity Framework Migrations when we generate the database from the code. Pretty cool, right. Now, Entity Framework will know which property is our identity column.

Reference: System.ComponentModel.DataAnnotations

image

5. Compile the Target Assembly

You will now want to compile the target assembly project before you generate your code. You will select the actual compiled assembly when you use the BuildMotion.CodeBuilder tool.

image

6. Open/Run the BuildMotion.CodeBuilder application.

  1. Select the target assembly. It should be compiled with your Entity definitions.
  2. Enter the default or core namespace for the application. (i.e., BuildMotion.Reference)
  3. Enter the Application Name (i.e., ReferenceApp).

image

7. Build Some Code

This will provide the CodeBuilder enough information to create the Service and Entity Framework code. It will also create a few other necessary files for the application. For example, I use Autofac as the dependency injection container, and there is a bootstrap class to do the initial wire up.

  1. Click on the Build Service Code button.
  2. Click on the Build Entity Framework Code button.

image

8. Create Entity Code: Service, Business, Rules, Validation, and Data Access Repositories.

  1. Click the Retrieve Entity Items button.
  2. Select one ore more entity items to build your code.
  3. Click the Build Code button to finish generating all of the code.

image

If you are all good, you will the following.

image

9. Include the code into your Target Project.

You will now want to include all of the generated code into your project and compile when you are ready.

image

ASP.NET Web API

I’m starting a new project that will be using ASP.NET Web API. I have used WCF in the past to create RESTful services – so I’m very interested in how I can achieve the same using Web API. It relies on the HTTP methods:

  • Get (retrieves a list of items)
  • Get (retrieves an item by id)
  • Post (creates a new item)
  • Put (updates an item)
  • Delete (removes an item)

So, if I am working with a Customer entity, I would have the following web api:

  • // GET api/Customers –> public List<Customer> Get(){..}
  • // GET api/Customers/123 –> public Customer Get(in id){..}
  • // POST api/Customers –> public void Post(Customer c){..}
  • // PUT api/Customers/123 –> public void Put(int id, Customer c){..}
  • // DELETE api/Customers/123 public void Delete(int id){..}

API Method Names

Notice that the method names correspond to the HTTP Method type. This is by convention. However, you have another option by convention as well, you can prefix the methods with the HTTP Method type name. You can use the same URI and ASP.NET Web API will know which method to call in the CustomersController.

  • // GET api/Customers –> public List<Customer> GetAllCustomers(){..}
  • // GET api/Customers/123 –> public Customer GetCustomer(in id){..}
  • // POST api/Customers –> public void PostCustomer(Customer c){..}
  • // PUT api/Customers/123 –> public void PutCustomer(int id, Customer c){..}
  • // DELETE api/Customers/123 public void DeleteCustomer(int id){..}

You can also modify the default convention by using Web API attributes. Using our GET as an example, we can use the default Get() method, or we can

  1. Use the default: Get()
  2. Prefix the method name with the HTTP Method: GetCustomers()
  3. Use the [HttpGet] attribute and name the method whatever we want.
  4. Use the [AcceptVerbs(“GET”)] attribute and also name the method whatever we want.

// GET api/values
//1. public List<Customer> Get()
//2. public List<Customer> GetCustomers
//3. [HttpGet]
//public List<Customer> GetAllllllCustomerss()
// 4. Use [AcceptVerbs(..)]
[AcceptVerbs(“GET”)]
public List<Customer> GetAllllllCustomersWithAcceptVerbs(){..}

As we can see, the mapping the actual URI to the Controller’s method is flexible. Each of the implementations noted above will return the same result. There is also another option to configure the mapping of the URIs to the Controller methods – this is an RPC style, where you actually include the name of the method in the URI – this requires you to modify the HttpRoutes to include the name of the Action in the URI. It is an option – however, I’m going to stick with the more conventional approach.

API Routing

Really, both approaches use Routing. You can modify the route map and register the new route by modifying the WebApiConfig class. If you wanted to use the RPC style (with the Action name), you would just update the RouteTemplate with “api/{Controller}/{Action}/{id}”.

imageC

There may be other parameters to put into the route template. For example, in a multi-tenant application, you might include an additional parameter and provide a constraint for the value.

image

Http-Compliant ASP.NET Web API

There are specific things that you will want to do to keep you API Http-Compliant. This is a good thing. We want users of the API to understand the API and have certain expectations when they are working with it. We’ll talk about the message body, Request and Response, and Http status codes.

When we are working with Http Methods what we return in the response and what status codes we use matters. For example, using our simple Get() method – the following implementation is fairly naïve. We are not returning any status codes in the response. The id value supplied may not even be a valid Customer identifier. So we have to be concerned with the how we handle the response and what status codes we use.

image

An improvement would be to provide a response and a status code if the specified item was not found. Otherwise, the status code would 200 OK.

image

When the request for a Get is valid, I get the XML in the response and the status code is 200 – OK.

image

When I inspect the HTTP request and response in Fiddler, I see the expected status code.

image

Let’s see if I get the 422 status code when the customer is not found during the request. I not only get the correct status code when I do not find the customer, but the Reason Phrase value is also provided in the response. This information will help users of you API to understand the responses when they do not get the expected results. In a more comprehensive solution, we would want to provide other status codes to indicate other causes of not providing the expected response: 200 OK.

image

Create a new Resource using the Web API

Just as there is special handling in processing a GET request, there is a protocol to use when creating a new resource using HTTP POST. The information used to create a new resource is contained in the body of the Http Request. The data or information can be either XML or JSON format – it just needs to represent the target we are trying to create. The response is also different – we not only need to return a status code, but we need to include some details about the new item that was created. This includes a URI to retrieve the item that was just created.

To improve the ASP.NET Web API default Post method – we update the return type to HttpResponseMessage. This will allow to provide a nice response with a status code, the resource just created, and a URI that will allow the user of the API to retrieve the item just created.

image

To make the request, we need to create the information used in the body of the request:

{“Name”:”Maria”}

I’ll use Fiddler to compose a request.I updated the body with the JSON that represents a new Customer, I changed the Http Method to POST and updated the URL.

image

When I execute the request using Fiddler, I expect to receive the information described above. I get the 201 Status – Created and the JSON data in the content represents my new Customer.

image

Conclusion

We covered a little bit of ground in setting up a GET and a POST. I’ll continue later with a blog entry about PUT and DELETE. But so far, we see how we can use Fiddler to generate a request and/or replay a request. We can retrieve data from our application using HTTP method calls – which has so many uses.