Archive

Archive for July, 2013

[Pet Shop Reloaded] Generating code

July 29, 2013 Leave a comment

 
We have defined our application model and the technical environment of our application Pet Shop Reloaded. It is now time to generate the code we are going to work with. Both, for CodeFluent Entities and Entity Framework, the generated code will be produced from the “Model” we have designed.
 

Generating code from the CodeFluent Entities Model

 
Generating code with CodeFluent Entities is made using “Producers”. Producers will transform our model and all its concepts in concrete text files (source code files).
 

CodeFluent Entities Add a Producer

CodeFluent Entities Add a Producer


 
CodeFluent Entities provides a large choice of Producers and Sub-producers.
 
CodeFluent Entities Producers

CodeFluent Entities Producers

 

CodeFluent Entities Sub-Producers

CodeFluent Entities Sub-Producers


 
As you can see there are huge possibilities for the same Model, as the CodeFluent Entities Model is agnostic of all technology layer you only need to add a specific producer to have a concrete representation of your model.

All the producers will be executed when we build our CodeFluent Entities project, but if needed you can disable specific producers by right clicking them.

CodeFluent Entities does not use templates to generated code.
 

Using the SQL Server producer

 
First, we are going to add a “SQL Server” producer, this producer can be found under the “Persistence Layer Producers”
 

The SQL Server Producer

The SQL Server Producer

 

We just need to add a connection string and an output directory where the generated SQL Server specific scripts will be generated. We have added a SQL Server database project to store our scripts.

CodeFluent Entities supports a wide variety of persistence implementations natively. Using Entity Framework you will need to search for external providers when you want to use some specific data base engines like MySQL, PostgreSQL or Oracle.

As you can see on the image above CodeFluent Entities can execute the generated scripts to create the database if it does not exist, insert the instances we have defined in our model, update the database and create diffs.

Unless Entity Framework, CodeFluent Entities has a diff engine that avoids to drop the database and create a new one each time we make a change in our model structure. This is very useful because this way we don’t have to backup and restore our data for each database update.

 
The SQL Server producer will translate our Model concepts into platform specific code:

  • Properties become columns,
  • Methods become stored procedures,
  • Instances become lines of data,
  • Entity keys become primary keys,
  • Entity relation properties become foreign keys,
  • Views in your model become actual SQL views,
  • etc.

After building our CodeFluent Entities project, we now see the T-SQL scripts on the location we have specified (the scripts will also be executed on the database).
 

Generated T-SQL scripts

Generated T-SQL scripts


 
CodeFluent Entities use stored procedures for CRUD operations.
 
Stored Procedure example

Stored Procedure example


 

Using the Business Object Model (BOM) producer

 
Let’s now add the producer that will generate all the .NET/C# classes that will contain our model structure and logic.
 

The BOM Producer

The BOM Producer


 
We will use a C# class library project to store our generated BOM classes.

Let’s build our CodeFluent Entities project so our BOM classes are generated.

You may also have noticed that the BOM producer allows you to select VB.NET as the Target Language.

Since CodeFluent Entities is made to help developers through their developments its purpose isn’t to force you developing in a language you haven’t choose.

Therefore, CodeFluent Entities gives you the opportunity to develop using the language you love.

 

The generated BOM

The generated BOM


 
All the features in our model will be present in our generated code. For example, we have added Data Annotation Attributes right on our model so our class properties will be decorated with those attributes.
 
Data Annotation Attributes

Data Annotation Attributes


 
For each entity we have 2 classes: a class having the same name as the Entity (e.g. Product, Order…) to handle unitary operations (Load one, save, delete, update) and a class having the suffix “Collection” as you can guess that is used to handle entity collections (Load all, page Load…).

The BOM classes are partial, so you can extend them as you want.

 
The C# classes generated by CodeFluent Entities do not inherit from any technical class, they only implement interfaces, so the code is entirely readable. The BOM classes implement some of the most used .NET interfaces as:

  • Unitary classes:
    • System.ComponentModel.INotifyPropertyChanged
    • System.ICloneable
    • System.IComparable
    • System.IComparable<T>
    • System.ComponentModel.IDataErrorInfo
    • System.IEquatable<T>
  • Collection classes:
    • System.Collections.IList
    • System.Collections.ICollection
    • System.Collections.Generic.IList<T>
    • System.Collections.Generic.ICollection<T>
    • System.ComponentModel.IRaiseItemChangedEvents
    • System.ICloneable
    • System.ComponentModel.INotifyPropertyChanged
    • System.Collections.Specialized.INotifyCollectionChanged
    • System.ComponentModel.IBindingList
    • System.ComponentModel.ICancelAddNew

This way you have all the features you will need for your Business Object Layer.
 

BOM code example

BOM code example


 

If you need your BOM classes to implement custom interfaces you can define it right on your CodeFluent Entities model, you will only need to provide an implementation in a partial class.

You can use the BOM generated by CodeFluent Entities as it. It contains all the validation logic, access to CRUD methods, state tracking capabilities, binding features, comparison capabilities and all the “technical business” features that a Business Object Layer may contain. And we have all that out of the box without the need to customize templates or add extra code generation artifacts.

 

The CodeFluent Entities BOM is more than just POCO classes.

 
We can see that other classes have been generated, classes to handle BLOBs (binary large objects) and security features (authentication, membership features) as we have used the “Membership Entities” provided by the CodeFluent Entities Model. That is very convenient to have completely functional BLOB handlers, handling BLOBs inefficiently can seriously harm an application performance.
 

BOM extra classes

BOM extra classes


 
You can always add more custom generated code as CodeFluent Entities provides an API to access the inferred Model in each of the generation steps. For example you can add templates or aspects to generate or modify the generated code. You can even add custom producers and sub-producers.
 

Generating code with Entity Framework

 
As we are using a Model first approach with Entity Framework we will need to generate the database as well as a Business Model from our entities model.
 

Generate the database scripts with Entity Framework

 
From your Entity Framework model you can generate the SQL scripts to create the database and all the structure.

Generate SQL scripts with EF

Generate SQL scripts with EF

 

Generated SQL script with EF

Generated SQL script with EF

 

Unlike CodeFluent Entities, Entity Framework does not generate a diff of your database structure, so each time you make a change on your model and want to update your database structure you will need to do a backup of your data, execute the scripts and restore your data.

 

SQL code example with EF

SQL code example with EF


 

Generating POCO classes with Entity Framework

 
Entity Framework generates code using T4 templates (.tt files). There are several templates provided by the Entity Framework team and the code generated by default may depend on your Visual Studio version.

We are using Visual Studio 2012 and Entity Framework 5. For this configuration the recommended (and already provided) templates generate POCO entity classes and a context that derives from DbContext. These templates are nested under the .edmx file.
 

EF T4 templates

EF T4 templates


 
Let’s now generate the C# code from our Entity Framework Model.
 
Run Custom Tools with EF

Run Custom Tools with EF


 
The code generated by the default templates is very simple even minimalist. As you will see below, unlike CodeFluent Entities, Entity Framework generated code provides basic classes and not ready-to-use code for real world applications.
 
The EF DbContext

The EF DbContext

 

EF POCO class example

EF POCO class example


 
We use the DbSet and DbContext to manipulate entities (Add, Attach, Remove) and LINQ to read data (as DbSet implement IQueryable).
 

Conclusion

 
As the generated classes by Entity Framework are very simple, we will have to do some extra work if we want to add custom feature to our classes. For example, there is no easy way to add Data Annotations Attributes to our classes as we did it with our CodeFluent Entities model, we will need to add those attributes to our Entity Framework generated classes through partial classes for example.

We can see that the POCO classes generated by the Entity Framework default templates lack basic features for a Business Object layer and we will spend a significant amount of time extending the default templates, creating custom code generation artifacts, searching for external solutions, manually coding those features…

The CodeFluent Entities BOM classes are ready to use, no extra work is required to have a totally functional Business Layer while specific and custom extensions are easy to add.

 


On the next blog posts we are going to see how to use the generated code.

Remember that you can find all the blog posts related to the Pet Shop Reloaded by SoftFluent under the tag “Pet Shop Reloaded“. Stay tuned. 🙂

Cheers,

The SoftFluent Team

Hands-on CFQL

July 25, 2013 Leave a comment

If you are familiar with CodeFluent Entities it is possible that you have already used the CFQL. The acronym CFQL stands for CodeFluent Query Language. In a nutshell, the CodeFluent Query Language is a specific language that specifically eases stored procedures creation, custom methods and rule definitions.

As you know, according to the database that you use you will have to write either PL-SQL or T-SQL depending if you are using a SQL Server or an Oracle database. CodeFluent Query Language is platform independent and is therefore used to declare platform independent queries which will then be translated by producers in platform specific code.

Therefore, we are going to take a look at it, to see how CFQL works.

To illustrate this article, we will use the “SampleAdvertising” model provided by CodeFluent Entities. We will also create a new “ClassLibrary” project which will contain the business code generated by CodeFluent Entities. We will also add a new “Console Application” project to our solution to test the custom methods we are about to create.

1

First we will add our producers, in this case we will need two of these, the Business Object Model producers which allows us to generate our business code, and the SQL producer which will generate our database, tables, stored procedures, views…

For the Business Object Model producer, we will set its targeted project to our class library project.

2

Regarding the SQL Server producer, we will create a new folder named “SQL Scripts” in our class library project which will contain all the files generated by this producer.

3

Now that we have added our producers, we can start creating our custom methods using the CodeFluent Query Language. We will start by creating all our methods, then we will use some of them in our console application.

For instance, we will create custom methods for our “Customer” entity. To do so, in the modeler, click on the “Customer” entity and hit “Add method” from the ribbon.

4

First, we will create a custom “Load” method, “LoadByCountry”, which will enable us to load our customers depending on their country. Therefore, add the following code to create our custom method:

5

As you can see, the syntax of the CodeFluent Query Language is really close from the SQL language.

We will now create a “LoadOne” method named “LoadOneByName” which will return a single line of data, in this case a customer based on its name. Since the generated method manipulates a single line of data, in the generated Business Object Model, the method is generated in the entity class and not the collection class as for classic load methods.

6

Then we will create a “Load Raw” method named “LoadTodaysCustomers”. Raw methods are methods in which a developer can code whatever he wants: platform specific code (e.g. CSharp, SQL, etc.), CodeFluent Query Language (CFQL), or a mix of both. In this example, we will create a method which will return today new customers. As you can see in the screenshot below, creating a raw method allows to target specific platform and language, in our case it will be T-SQL.

7

Now, we will create a “LoadOne Raw” method named “LoadLastFiveMinCreatedCustomer” which will return a single row of a customer created within the last five minutes.

8

Once this method created, we will create a custom search method to find our customers based on their city. We will name it “SearchByCity”.

9

Then we will create a new method to count our customers based on their city according to the screenshot below, name it “CountByCity”.

10

Finally, we will create a custom method named “DeleteByCountry” to delete our customers based on their country.

11

Now that all the methods we wanted have been created, let’s build our solution to generate our database and our business code (right click on our CodeFluent Entity project > build).

Once the build is complete and successful, open the file “Program.cs” of our console application project and add the following code to get all our customers from the database.

foreach (Customer cust in CustomerCollection.LoadAll())
{
    Console.WriteLine(cust.Name + " " + cust.Country + " " + cust.City);
}

Then, we will start by testing our “LoadByCountry” custom method

CustomerCollection custByCountry = null;
Console.Write("LoadByCountry, enter a country: ");
string countryInput = Console.ReadLine();
if (countryInput != null && countryInput.Trim() != String.Empty)
{
    custByCountry = CustomerCollection.LoadByCountry(countryInput);
}
if (custByCountry != null)
{
    foreach (Customer cust in custByCountry)
    {
        Console.WriteLine(cust.Name + " " + cust.Country + " " + cust.City);
    }
}

As you can see on the screenshot below, our custom method returns our customers based on their country.

12

Now, we will test our “LoadOneByName” custom method. Insert the following code into the “Program.cs” file.

Console.WriteLine("\r\n");
Console.Write("LoadOneByName, enter a name: ");
string nameInput = Console.ReadLine();
Customer singleCustByName = null;
if (nameInput != null && nameInput.Trim() != String.Empty)
{
    singleCustByName = Customer.LoadOneByName(nameInput);
}
if (singleCustByName != null)
{
    Console.WriteLine(singleCustByName.Name + " " + singleCustByName.Country + " " + singleCustByName.City);
}

You can see the result in the screenshot below.

13

We can take a look to our raw method “LoadTodaysCustomers”. In order to test this method add the following code to the “Program.cs” file.

CustomerCollection custFromToday = null;
Console.WriteLine("\r\n");
Console.WriteLine("LoadTodaysCustomers:");
custFromToday = CustomerCollection.LoadTodaysCustomers();
if (custFromToday != null)
{
    foreach (var cust in custFromToday)
    {
        Console.WriteLine(cust.Name + " " + cust.Country + " " + cust.City);
    }
}

As you can see in the following screenshot, our method returns all our customers since they were all generated today.

14

Then, we can test our “LoadLastFiveMinCreatedCustomer” method, to do so, insert the following code into the “Program.cs” file.

Console.WriteLine("\r\n");
Console.WriteLine("LoadLastFiveMinCreatedCustomer:");
Customer lastModifiedCust = Customer.LoadLastFiveMinCreatedCustomer();
if (lastModifiedCust != null)
{
    Console.WriteLine(lastModifiedCust.Name + " " + lastModifiedCust.Country + " " + lastModifiedCust.City);
}

We can verify the result thanks to the two following screenshots.

15

16

We will now test our “SearchByCity” method, to do so, add the following code to the “Program.cs” file.

Console.Write("SearchByCity, enter a city: ");
string cityInput = Console.ReadLine();
CustomerCollection searchByCity = CustomerCollection.SearchByCity(cityInput);
foreach (Customer cust in searchByCity)
{
    Console.WriteLine(cust.Name + " " + cust.Country + " " + cust.City);
}

And this is what you should get.

17

Then we will test our “CountByCity” method which allow us to count our customers based on their city.

Console.Write("CountByCity, enter a city: ");
string cityCountInput = Console.ReadLine();
Console.WriteLine("Number of customer in " + cityCountInput + ": " + CustomerCollection.CountByCity(cityCountInput));

You can see the result in the following screenshot.

18

Finally, we can test our “DeleteByCountry” custom method and here is the code to test it.

Console.Write("DeleteByCountry, enter a country: ");
string deleteCountryInput = Console.ReadLine();
Console.WriteLine("You are about to delete all customers from " + deleteCountryInput + ". Are you sure? (y/n)");
string deleteConfirm = Console.ReadLine();
if(deleteConfirm.ToLower() == "y")
{
    CustomerCollection.DeleteByCountry(deleteCountryInput);
}

You can call again the “CustomerCollection.LoadAll” method to verify that customers related to the country you have specified in the previous method.

19

Cheers,

Aymeric ROLAND.

[Pet Shop Reloaded] Designing the application model – Part 2


In the previous post, we have seen how we designed our application with CodeFluent Entities. We will now take a look to how we did with Entity Framework 5 to conclude on a comparison of those two designers.

Using Entity Framework 5

Entity Framework is a tool that allows developers to create applications that access to data from a conceptual model. In order to create our model, we will need to add new “.edmx” file to our project as it is showed on the following screenshot.

addmodel

Once this file added, we can see the Entity Framework model. From this model we are able to create:

– Entities,

– Properties

– And relations.

As you can see in the screenshot below, the Entity Framework designer is composed by a designing surface and a right click contextual menu.

efmodel

Following the same path than our first article, we will start by adding a new entity to our model. To do so we will perform a right click on the surface then hit ‘Add New > Entity…’. According to our project we will name it ‘Category’. We will set the value of entity set to ‘Category’ and we will name our key property ‘Id’ of type ‘Int32’.

addentity

In order to demonstrate other features, we will add two other properties: Description and Name of type string. We will also create a new entity named ‘Product’ with an entity set named ‘Product’ and a key property name set to ‘Id’ of type ‘Int32’. This entity will contain three other properties: Name, Description and Image, respectively of types: string, string, and binary.

Unlike CodeFluent Entities Entity, Framework does not provide types like ‘Image’ or ‘email’. Right now, it’s not really important but we will get back to it in an upcoming article dedicated to the generation and you will see that it saves you tons of work regarding BLOBs storage.

We will now add a one-to-many relation between these two entities. To do so, right click on the ‘Category’ entity, hit ‘Add New > Association’ and a popup will show up. In this popup, modify the fields according to the following screenshot to create our relation properly.

addrelation

addrelation1

As you can see on the screenshot above, Entity Framework created navigation properties and a foreign key property named ‘CategoryId’ for us.

This is pretty much all we can do for this project with Entity Framework 5 since we don’t need: complex properties, inheritance, or function import functionalities.

Finally, regarding the validation of our properties (e.g. required attributes), we will have to do it in partial classes once we will have generated our model classes thanks to T4 Templates.

Note: we could have choose to customize T4 templates in order add those required attributes directly in the generation process but we wanted to keep things as close as possible to what is provided out-of-the-box.

 

Comparison and conclusion

On these two articles, we talked about CodeFluent Entities and Entity Framework designers’ capabilities and we are now able to do some comparison between them.

Starting with the property types we have seen that CodeFluent Entities offers a lot more types for properties. CodeFluent Entities advanced types as ‘image’ allows developers to gain a lot of time because as you will see in the upcoming post treating about generation CodeFluent Entities will generate columns to store information about the image and it will also generate for you a BLOB handler.

Regarding relations between our entities CodeFluent Entities allows you to set cascade for save and delete directly when you create the relation.

One of the most important problem with Entity Framework is the generation process. Unlike CodeFluent Entities, which have a continuous generation process that allows you to update your model at any time and generate over the current one, using Entity Framework, if you want to update and regenerate your model, you will have to drop the existing database, recreate a new one and regenerate model classes by adding new code generation item.

Another key point is the impossibility to add attributes, rules or custom methods directly from the model with Entity Framework. While CodeFluent Entities provides these features out-of-the-box, with Entity Framework you will have to either customize your T4 template, create partial classes to extend the code generated or write T-SQL to create your stored procedure.

Finally, CodeFluent Entities allows you to create instances directly from the model, therefore it gives the possibility to have data in your database directly after the generation.

Note: You can find more detailed information about the differences between the CodeFluent Entities and the Entity Framework designers reading this white paper (http://www.softfluent.com/docs/codefluent/codefluent-entities-entity-framework.pdf)

In conclusion, we can see that CodeFluent Entities modeler is more powerful and flexible than Entity Framework designer while providing continuous generation and more features.

 

Cheers,

The SoftFluent Team.

CodeFluent Entities and Visual Studio 2013 preview


As announced on the //Build/ 2013 event, the Visual Studio 2013 preview is available for download.

Visual Studio 2013 preview sign in

Visual Studio 2013 preview sign in

 

Visual Studio 2013 home page

Visual Studio 2013 home page

You can discover the new features of Visual Studio 2013 here:

The Visual Studio 2013 download includes the .NET framework 4.5.1 preview, so this is the opportunity to discover it:

Finally, the CodeFluent Entities latest build (61214.714) is compatible with the Visual Studio 2013 preview version.

CodeFluent Entities and Visual Studio 2013 preview

CodeFluent Entities and Visual Studio 2013 preview

You can download the latest version of CodeFluent Entities here, or update your version using the Licensing tool.

Remember that you can follow the latest new features and bug fixes of CodeFluent Entities subscribing to this RSS.

So you can start playing around 🙂

And if you missed the //Build/ 2013:

Regards,

Pablo Fernandez Duran