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

How do I setup an AngularJS application in Visual Studio 2013

Q: How do I setup an AngularJS application in Visual Studio 2013?

Not trying to avoid the answer, however, I think the answer to this question depends on the type of application that you need for the solution. Your decision is based on how much of ASP.NET do you want or need. And if you are going to integrate AngularJS with ASP.NET features or not. There are some purists out there that wouldn’t think of integrating AngularJS with an ASP.NET MVC application. They want pure HTML and JavaScript (no Microsoft). That is ok too! I would love to work on that kind of project.

I like to take the approach that AngularJS is a tool and if it is used correctly for the specific job or solution then it could be integrated along with an ASP.NET MVC application – OR NOT. If so, I think you need to determine what the boundaries are for its use and when it is appropriate – there should be a good division of responsibility for MVC and AngularJS. When, Where, and How are you going to use it.

Angular’s MVC approach on the client-side of things using models, views, and controllers all self-contained in neat .js files is a great improvement in the structure and management of JavaScript code. The structure and conventions used in Angular make it a great choice for teams – the conventions are the same. And they will be the same for the next project and the project after that. So Angular is still a good choice whether or not you are combining it with ASP.NET MVC technologies.

Q: Which project template should I use?

Again, it depends based on what you need. You can use the ones that come installed with your version of Visual Studio or you can use some that are created by other concerned developers like yourself.

AngularJS-SPA-Template @ https://github.com/kriasoft/AngularJS-SPA-Template

Here are some project template options provided by Visual Studio 2013

  • Singe Page Application: Setup for a single page application that is ASP.NET MVC specific. There are controller, model, and view folders setup for your application with all of the other MVC goodness.
  • Empty Web Application: Only contains a web.config file. I guess you can delete it if you don’t need it. This is as basic as you get.
  • Web API: This template provides you with basic ASP.NET MVC, but it includes a sample “Value” Web API controller that uses the new ApiController base class. This project template will allow you to implement Web APIs along with Angular – you have the option of adding as much MVC that you want or not.

Q: When would I use Angular with no ASP.NET MVC (i.e., Angular straight up)?

Recipe: AngularJS ONLY :: Single Page Application (No ASP.NET MVC).

You would make this choice when ASP.NET MVC features are not required or needed. Also, it might be a requirement – you would only be using the Visual Studio 2013 as an IDE or development environment for your application. Visual Studio is a good option to use as an IDE for an AngularJS application. There are some intellisense templates out there that make it a rich experience. You can also use Resharper Extensions for Angular.

This is a great choice when you do not require any HTTP calls for data or data persistence (same application). Or you are using a different HTTP source that is well-known or exposed API to provide data for the application.

Suggested Project Template: Empty Web Application

image

Q: Should I mix Angular with ASP.NET MVC Views (i.e., mixed or blended mode)?

Recipe: ASP.NET MVC Application + Web API + AngularJS SPA

This might be a good choice if you want to use the ASP.NET MVC views to serve up the pages of your web site and/or application. It provides some SEO benefits – or so I’ve heard. Basically, you are using ASP.NET to load up the page initially and supply it with whatever it requires for the initial display.

Most likely, you will use Angular for subsequent displays and requests for models. In this recipe, there is a good separation of concerns. ASP.NET is responsible for the initial loading of pages and subsequent calls for information are done by Angular. You might even have just partial sections or partial templates within the ASP.NET MVC page that use specific Angular controllers, models, and views. This would be considered another example of a mixed-mode.

Suggested Project Template: Single Page Application

image

Q: When would I use ASP.NET MVC, Web API and AngularJS (i.e., mixed mode with a splash of Web API)?

I could see this recipe with or without the ASP.NET MVC. The interesting part here is the Web API mixed in. The Angular controllers may need to make some HTTP calls to retrieve or persist information. Web APIs make this possible. The routing and model binding provided by Web API make the implementation a lot easier.

This would be a great choice when your Angular controllers need a place to call for data.

Suggested Project Template: Web API Application

image

Q: What packages do I need to implement an AngularJS application?

If you are using Visual Studio, it is probably a good idea to use the Package Manager to retrieve the packages you require.

  • AngularJS (required)
  • jQuery (required)
  • Bootstrap (optional)

AngularJS && Intellisense && Code Snippets

I’m getting ready to start calling some ASP.NET Web APIs – I wanted to make sure that I get all of the intellisense goodness from Visual Studio. Since I sue Resharper, I installed an extension for Resharper:

image

Now it is looking good.

image

Resharper Code Snippets for AngularJS

It gets better with code snippets. You can type in a code snippet name and it will add the code to your script. Type:

ngdc

image

Now you get the snippet injected into your script. That is pretty cool.

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.