Archive

Archive for the ‘Pet Shop Reloaded’ Category

[Pet Shop Reloaded] The End

November 24, 2013 Leave a comment

Across this series of posts we have seen how is to design and build a business application using CodeFluent Entities and Entity Framework 5 and as you have seen, we can say that CodeFluent Entities can be located as a superset of Entity Framework (taking into account that CodeFluent Entities does not rely on Entity Framework).

Richer Modeler

As you could see, the CodeFluent Entities modeler is a very advanced one. The number of notions supported by CodeFluent Entities is larger than those of Entity Framework:

  • namespaces
  • model search engine
  • aspects and dynamic modeling
  • code snippets
  • methods
  • attributes
  • rules
  • rules editor
  • instances
  • forms
  • forms editor
  • configuration properties
  • model design customization
  • menu/action ribbon
  • inferred model
  • multi surface/file model
  • naming conventions
  • user defined types

Performance and readability

Entity Framework generate SQL code dynamically which can be ok when you have a small application and when you don’t need to debug/understand your SQL code. Indeed, dynamically generated code is not easy to read and can present performance issues when dealing with complex queries. All SQL code generated by CodeFluent Entities is generated in design time so you know in advance exactly the code that will be called.

linq-to-entities

linq-to-entities

Using CFQL

Using CFQL

The first image shows a query using Entity Framework and Linq-to-Entities, we can also see the dynamically SQL generated code translated from the C# code. The second image shows the same query using CodeFluent Entities and its language agnostic query system (CFQL), all this in design time.

Multipart model

When working with a large model or when several members of a team modify the same model it is really handy to split the model in different parts (files), this is not possible with Entity Framework without losing information and you may have experienced the consequences: merge conflicts, Visual Studio slows down…

No Mapping

When modeling your business domain with CodeFluent Entities you don’t need to make any specific mapping, you can easily add, remove and update elements in your model and CodeFluent Entities does the rest.

Continuous generation

CodeFluent Entities embraces the notion of Continuous Generation, it means that you can “tune” your model (update, go back) until it suits your needs and then generate it over and over again without losing any data, this is possible thanks to the CodeFluent Entities diff engine. This way you can more easily support functional changes.

Write less code

CodeFluent Entities will save you thousands of lines of code, code that the development team would have to write, code that would need to be tested and code that would always have a risk to have errors.  As all we know:

the less code we write…

  • the less that can go wrong
  • the sooner we’ll be done
  • the fewer bugs we write
  • the less we have to maintain
  • the better…

We haven’t seen everything

We have only covered a piece of the potential of CodeFluent, it provides a huge set of producers:

  • WPF
  • WindowsForms
  • Azure
  • Windows 8
  • ASP.NET MVC
  • WCF
  • REST/JSON web services
  • SharePoint
  • Silverlight proxy
  • advanced web services proxies
  • automatic traces
  • cache features
  • documentation files
  • Linq-to-Sql
  • Access and Excel lists
  • MS Build tasks
  • templates
  • web controls
  • and more…

That is explained by saying that CodeFluent Entities is not an ORM, it is a full model-driven software factory.

Code metrics

Let’s see a comparison of code metrics between the application built with CodeFluent Entities and Entity Framework.

We used the Visual Studio 2012 tool for code metrics analysis (Analyze -> Calculate Code Metrics for Solution).

We focalize on 3 indexes: Lines of Code, Maintainability Index and Cyclomatic Complexity. For each index the less is better.

Entity Framework – Code Metrics:

Entity Framework Code Metrics

Entity Framework Code Metrics

CodeFluent Entities – Code Metrics:

CodeFluent Entities Code Metrics

CodeFluent Entities Code Metrics

The code metrics analysis has not been applied to generated code, that’s why the “PetShopReloaded” project has a value of 0 Lines of Code for the CodeFluent Entities solution.

We needed to modify the t4 templates (Model.tt and Model.Context.tt) for Entity Framework in order to generate the System.CodeDom.Compiler.GeneratedCodeAttribute attribute so the generated code has not been taken in account by the code metrics tool. CodeFluent Entities generated that attribute by default.

As we can see we will need to maintain more code (and more complex) for the solution built with Entity Framework.

Finally

If you are convinced by all the advantages that CodeFluent Entities can provide to your software engineering process but you have already started with Entity Framework, don’t worry, CodeFluent Entities provides a “Entity Framework Importer” (http://www.softfluent.com/documentation/Importer_EntityFrameworkImporter.html) 🙂

Regards,

The SoftFluent team

[Pet Shop Reloaded] Using the generated code – Part 2

August 13, 2013 Leave a comment

In the previous article, we talked about using the code generated by CodeFluent Entities. On this one, we will first focus on the code generated by Entity Framework then we will summarize in a conclusion what is provided by the two solutions.
 

I – Use of Entity Framework generated code

In order to use the code generated by Entity Framework we will need to have some assemblies referenced in our project like “System.Data.Entity”, “EntityFramework”. Nevertheless, in our case we choose an ASP.NET MVC project and those are included out-of-the-box in the solution.

First of all, we have seen in the previous article that CodeFluent Entities generates out-of-the-box a BLOB handler for our images stored in the database. Obviously, Entity Framework doesn’t generate it for us, therefore we have to create our own BLOB handler.

To do so, we will add a new .ashx file at the root of our solution named “ImageHandler.ashx”. This file will contain the following code.

public class ImageHandler : IHttpHandler
{
  public void ProcessRequest(HttpContext context)
  {
    ModelContainer _db = new ModelContainer();
    string idStr, entityType;
    int id;

    if ((idStr = context.Request.QueryString.Get("ID")) != null && (entityType = context.Request.QueryString.Get("type")) != null && int.TryParse(idStr, out id))
    {
      if (entityType == "product")
      {
        Product product = _db.Product.Single(p => p.Id == id);
        context.Response.Clear();
        context.Response.ContentType = "image/jpg";
        context.Response.BinaryWrite(product.Image);
        context.Response.End();
      }
      else if (entityType == "item")
      {
        Item item = _db.Item.Single(i => i.Id == id);
        context.Response.Clear();
        context.Response.ContentType = "image/jpg";
        context.Response.BinaryWrite(item.Image);
        context.Response.End();
      }
    }
  }

  public bool IsReusable
  {
    get
    {
      return true;
    }
  }
}

As you can see, our class inherits from “IHttpHandler”, and based on the type it will either return the product image or the item image.

Once the handler created we will need to modify the “Web.config” file to reference our “ImageHandler” according to the following code.

<configuration>
  . . .
  <system.webServer>
    . . .
    <handlers>
      <add name="ImageHandler" verb="*" path="*.ashx" type="EF.PetShopReloaded.WebApp.ImageHandler,EF.PetShopReloaded.WebApp" />
      . . .
    </handlers>
  </system.webServer>
  . . .
</configuration>

In order for our blob handler to work we need to add a new route to be ignored in our “RouteConfig.cs” file as it is showed in the code below.

routes.IgnoreRoute("{handler}.ashx");

Our “Web.config” file is set up, our web application is able to reach our database, display images stored in, and use generated providers.

To be able to request data stored we also needed to instantiate our “ModelContainer” thanks to the following code.

public static ModelContainer _db = new ModelContainer();

As we did in the previous article with the code generated thanks to CodeFluent Entities, we will create a “CategoryController” containing an “Index” ActionResult method which will be used to retrieve products based on their category name.

public class CategoryController : Controller
{
  [HttpGet]
  public ActionResult Index(string name)
  {
    var products = EF.PetShopReloaded.WebApp.MvcApplication._db.Product.Where(c => c.Category.Name == name).ToList();

    if (products.Count != 0)
    {
      ViewBag.CategoryName = name;

      return View(products);
    }
    else if (products.Count == 0)
    {
      ViewBag.CategoryName = "No such category";

      return View(products);
    }
    else
      return RedirectToAction("Index", "Home");
  }
}

Let’s focus on the line

var products = EF.PetShopReloaded.WebApp.MvcApplication._db.Product.Where(c => c.Category.Name == name).ToList();

We used LINQ-to-Entities to retrieve all the products by name, in this example this is a very simple query and maybe we won’t have any problem when trying to debug it. However when we have more complicated queries it will be harder to debug them if there is a problem, this because Entity Framework generate SQL code on the fly, so we will need to use a profiler tool to see the actual query that is sent to the SQL server.

Obviously we can also manipulate data thanks to the code generated by Entity Framework. As we have seen in the article treating about the creation of the model of the application with CodeFluent Entities we are able to create instances to add data at generation but such a feature isn’t provided by Entity Framework and we had to create data manually from code. Therefore, we will use these data creation scripts to illustrate how to manipulate data with Entity Framework.

Regarding data creation we will take as example the “CreateCategories” class which can be find under the “Data” folder. As you can see in the code below, we are adding new categories and persisting them by calling the “SaveChanges” method.

public class CreateCategories
{
  public CreateCategories(ModelContainer _db)
  {
    _db.Category.Add(new Category() { Name = "Birds", Description = "Birds" });
    _db.Category.Add(new Category() { Name = "Backyard", Description = "Backyard" });
    _db.Category.Add(new Category() { Name = "Bugs", Description = "Bugs" });
    _db.Category.Add(new Category() { Name = "Endangered", Description = "Endangered" });
    _db.Category.Add(new Category() { Name = "Fish", Description = "Fish" });

    _db.SaveChanges();
  }
}

In order to update data, we just need to get the category we want to modify, update its properties and finally call the “SaveChanges” method to persist changes.

//Update sample
Category category = _db.Category.Single(c =&gt; c.Name == "Birds");
category.Name = "New name";

_db.SaveChanges();

For deletion, a “Delete” method is provided by CodeFluent Entities, the sample below shows how to delete an entity with Entity Framework.

//Delete sample
_db.Category.Remove(selectedCategory);

_db.SaveChanges();

Taking for example the view where we show our items, we just want to display the content of the product list we passed from our controller. Therefore, we are creating a view which have a model type of “IEnumerable<EF.PetShopReloaded.WebApp.Models.Product>”. This view also uses the layout of the web application. Since we have passed a list we need an enumerator, in this case we are using a “foreach”, to display its content. As we did in the previous article we will once again add some style to make it look nicer.

@model IEnumerable<EF.PetShopReloaded.WebApp.Models.Product>

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2 style="color: #444444;">@ViewBag.CategoryName</h2>

@foreach (var item in Model) {
    <a class="category" href="@Url.Action("Index", "Product", new { item.Category.Description, item.Name })">
        <p class="categoryTitle">@item.Name</p>
        <img id="@item.Id" src="~/ImageHandler.ashx?ID=@item.Id&type=product" style="width: 100%; height: 200px; margin:0; padding:0;"/>
        <p style="text-align:justify; width: 278px; padding: 6px; height:35px; margin: 0; font-size: 9pt;">@item.Description</p>
    </a>
}

As you can see, the “src” property of the “img” tag isn’t a simple variable. Since our images are stored in the database as BLOBs, as we said earlier we need an http handler. In this case, the url is simpler than the one showed in the previous article but the handler is also less complex and flexible.

To conclude, we can say that CodeFluent Entities provides ready-to-use code for you developers allowing you to focus on the application you are working on.

 

II – Conclusion

In this two part article we have seen how to use code generated by both CodeFluent Entities and Entity Framework. We have seen that the code generated by CodeFluent Entities is more efficient, providing us ready-to-use and platform independent code whilst letting us focus on using it inside our application.

In the next article, we will talk more about statistics (e.g. number of lines of code, performances) to conclude this blog post series about “Pet Shop Reloaded”.

 

Cheers,

The SoftFluent Team.

[Pet Shop Reloaded] Using the generated code – Part 1

August 5, 2013 Leave a comment

In this article, we will talk about using the code generated by CodeFluent Entities and Entity Framework. On the first part of this article we will focus on using the code generated by CodeFluent Entities then on an upcoming article we will see how to use the code generated by Entity Framework and the differences between the two approaches.

Use of CodeFluent Entities generated code

In order to use the code generated by CodeFluent Entities do not forget to add a reference to our class library project which contains the generated files as well as a reference to the “CodeFluent.Runtime” and the “CodeFluent.Runtime.Web”. Those DLL can be found in the installation directory of CodeFluent Entities, by default in “C:Program Files (x86)SoftFluentCodeFluentx64”.

First of all, we need to modify the “Web.config” file according to the screenshot below to add our connection string, add the generated blob handler in the “HttpHandler” section and register membership and role providers generated by CodeFluent Entities which are based on the AspNet membership and role providers.

9

In order for our blob handler to work we need to add a new route to be ignored in our “RouteConfig.cs” file as it is showed in the code below.

 routes.IgnoreRoute("{handler}.ashx");

Once our “Web.config” file is set up, our web application is able to reach our database, display images stored in, and use generated providers.

We are now able to create a controller and a view associated to this controller to show how it works.

Therefore, I will create a “CategoryController” containing an “Index” ActionResult method which will use our custom method to load products by their category name.

Once our “Web.config” file is set up, our web application is able to reach our database, display images stored in, and use generated providers.

We are now able to create a controller and a view associated to this controller to show how it works.

Therefore, I will create a “CategoryController” containing an “Index” ActionResult method which will use our custom method to load products by their category name.

[HttpGet]
public ActionResult Index(string name)
{

ProductCollection products = ProductCollection.LoadByCategoryName(name);

if (products != null && products.Count != 0){

ViewBag.CategoryName = name;

return View(products);

}

else if (products != null && products.Count == 0){

ViewBag.CategoryName = "No such category";

return View(products);

}

else

return RedirectToAction("Index", "Home");

}

As you can see in the code above, we are getting all the matching products from our database and we returning this ProductCollection to our view.

Before going further, we will take a look to what was generated inside this “ProductCollection” class focusing on the “LoadByCategoryName” method.

[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]

public static PetShopReloaded.ProductCollection LoadByCategoryName(string category)

{

PetShopReloaded.ProductCollection ret = PetShopReloaded.ProductCollection.PageLoadByCategoryName(int.MinValue, int.MaxValue, null, category);

return ret;

}

public static System.Data.IDataReader PageDataLoadByCategoryName(CodeFluent.Runtime.PageOptions pageOptions, string category)

{

if ((category == default(string)))

{

throw new System.ArgumentNullException("category");

}

CodeFluent.Runtime.CodeFluentPersistence persistence = CodeFluentContext.Get(PetShopReloaded.Constants.PetShopReloadedStoreName).Persistence;

persistence.CreateStoredProcedureCommand(null, "Product", "LoadByCategoryName");

persistence.AddParameter("@category", category);

if ((pageOptions != null))

{

System.Collections.IEnumerator enumerator = pageOptions.OrderByArguments.GetEnumerator();

bool b;

int index = 0;

for (b = enumerator.MoveNext(); b; b = enumerator.MoveNext())

{

CodeFluent.Runtime.OrderByArgument argument = ((CodeFluent.Runtime.OrderByArgument)(enumerator.Current));

persistence.AddParameter(string.Format("@_orderBy{0}", index), argument.Name);

persistence.AddParameter(string.Format("@_orderByDirection{0}", index), ((int)(argument.Direction)));

index = (index + 1);

}

}

System.Data.IDataReader reader = CodeFluentContext.Get(PetShopReloaded.Constants.PetShopReloadedStoreName).Persistence.ExecuteReader();

return reader;

}

CodeFluent Entities automatically generates “LoadBy” methods in collection classes for each entity relationship. For example, in the “ProductCollection” class we have a “LoadByCategory” method, as a Product has a relation with Category. We have also defined a “LoadByCategoryName” method to meet our specific needs. This method was generated using CFQL which is a platform independent language (https://blog.codefluententities.com/?s=cfql).

image

You can see that the code generated by CodeFluent Entities is clear and intelligible. Plus, if your business needs requires something really specific you can still extend what was generated by CodeFluent Entities since all the classes generated are partial classes. Therefore, you can focus on what matter for you and your application and not on the plumbing code.

CodeFluent Entities also generates methods to create, modify and delete data. Regarding creation or modification, a “Save” method is provided. This method will either save modifications made to an object or create this one if it doesn’t exist and it can be used as shown in the code sample below.

//Creation sample
Product product = new Product() { Name = "Demo" };
product.Save();

//Update sample
Product product = Product.Load(MyProductId);
product.Save();

For deletion, a “Delete” method is provided by CodeFluent Entities, a sample is shown below.

//Delete sample
Product product = Product.Load(MyProductId);
product.Delete();

CRUD methods are generated by default by CodeFluent Entities for all entities.

Taking for example the view where we show our items, we just want to display the content of the “ProductCollection” we passed from our controller. Therefore, we are creating a view which have a model type of “ProductCollection”. This view also uses the layout of the web application. Since we have passed a collection we need an enumerator, in this case we are using a “foreach”, to display its content. We are also adding some style to make it look nicer.

@model PetShopReloaded.ProductCollection

@{

Layout = "~/Views/Shared/_Layout.cshtml";

}

<h2 style="color: #444444;">@ViewBag.CategoryName</h2>

@foreach (var item in Model) {

<a href="@Url.Action("Index", "Product", new { item.Category.EntityDisplayName, item.Name })">

<p>@item.Name</p>

<img id="@item.Id" src='@(Request.ApplicationPath + CodeFluent.Runtime.Web.UI.BinaryLargeObjectHttpHandler.BuildUrl(null, CodeFluent.Runtime.Web.UI.WebControls.BinaryLargeObjectUrlType.Image, "PetShopReloaded.Product", "Product_Image", null, null, null, null, null, -1, -1, 0, new object[] { item.Id }))' style="width: 100%; height: 200px; margin:0; padding:0;"/>

<p style="text-align:justify; width: 278px; padding: 6px; height:35px; margin: 0; font-size: 9pt;">@item.Description</p>

</a>

}

As you can see, the “src” property of the “img” tag isn’t a simple variable. Since our images are stored in the database as BLOB’s as we said earlier we need an http handler. This BLOB handler was also generated by CodeFluent Entities.

public partial class HttpHandler : CodeFluent.Runtime.Web.UI.BinaryLargeObjectHttpHandler

{

private CodeFluent.Runtime.CodeFluentContext _context;

public override CodeFluent.Runtime.CodeFluentContext CodeFluentContext

{

get

{

if ((this._context == null))

{

if ((this.EntityClrFullTypeName == "PetShopReloaded.Item"))

{

this._context = CodeFluentContext.Get(PetShopReloaded.Constants.PetShopReloadedStoreName);

return this._context;

}

if ((this.EntityClrFullTypeName == "PetShopReloaded.Product"))

{

this._context = CodeFluentContext.Get(PetShopReloaded.Constants.PetShopReloadedStoreName);

return this._context;

}

this._context = CodeFluentContext.Get(PetShopReloaded.Constants.PetShopReloadedStoreName);

}

return this._context;

}

}

public override CodeFluent.Runtime.BinaryServices.BinaryLargeObject LoadBinaryLargeObject(System.Web.HttpContext context, string propertyName, object[] identifiersValues)

{

if ((this.EntityClrFullTypeName == "PetShopReloaded.Item"))

{

PetShopReloaded.Item Item = PetShopReloaded.Item.Load(((int)(ConvertUtilities.ChangeType(identifiersValues[0], typeof(int), -1))));

if ((Item == null))

{

return null;

}

if ((propertyName == "Item_Image"))

{

return Item.Image;

}

}

if ((this.EntityClrFullTypeName == "PetShopReloaded.Product"))

{

PetShopReloaded.Product Product = PetShopReloaded.Product.Load(((int)(ConvertUtilities.ChangeType(identifiersValues[0], typeof(int), -1))));

if ((Product == null))

{

return null;

}

if ((propertyName == "Product_Image"))

{

return Product.Image;

}

}

return null;

}

}

Remembering the model of our application you will notice that this generated BLOB handler will be able to handle image from “Product” and “Item” tables, which also are the only entities where we defined properties of type “image”. Also you can check-out the Blob http Handler article for more information.

To conclude, we can say that CodeFluent Entities provides ready-to-use code for you developers allowing you to focus on the application you are working on.

NB. For our application Pet Shop Reloaded we have used the generated BOM classes in a Web context (ASP .NET MVC), but know that you can also use it in other contexts like a WPF or a Windows Forms application.

Cheers,

The SoftFluent Team.

[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

[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.

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

June 28, 2013 Leave a comment

In this post we will treat the model designing aspect of the application. In the first part we will see how to design our business model with CodeFluent Entities then we will show how to do it with Entity Framework 5. Finally, we will compare both designers’ capabilities and show which benefits you can have by using CodeFluent Entities.

Using CodeFluent Entities model designer (aka modeler)

CodeFluent Entities is a software completely integrated into Visual Studio (2008/2010/2012 and 2013 soon). In fact, Visual Studio is strictly speaking not mandatory (you can edit files with any text editor, or use the Portable Modeler tool we talked about here https://blog.codefluententities.com/2012/09/11/the-codefluent-entities-portable-modeler/), but it’s by far the easiest way to start with CodeFluent Entities.

Designing an application with CodeFluent Entities allows you to directly create from the model:

– Entities

– Properties

– Relations

– Rules

– Attributes

– Custom methods

– And much more…

As you can see in the screenshot below, the CodeFluent Entities’ designer is composed by a designing surface and a ribbon.

modeler

The ribbon contains buttons which allows you to perform actions like adding entities, methods and so on. Those actions are also available by right clicking the surface.

add entity

Our first action will be to add an entity, to do so you can hit the ‘Add entity’ button from the ribbon or by a right click on the surface then ‘Add > Entity’. According to our project we will name it ‘Category’.
Once this entity added, we will add a first property named ‘Id’ of type ‘Int’ which will be our primary key. By default, with CodeFluent Entities, the first property added is considered as the primary key but of course, you can change it through the settings of the property.

new property

You may have noticed there is a lot of property types, more than available with Entity Framework 5. The reason is CodeFluent Entities type system is a composite one since it must adapt to the underlying target type.

When designing your model you are not targeting any specific technology. The CodeFluent Entities model is totally technology agnostic.

CodeFluent Entities also provides extra types through its runtime such as email, image, audio, film. An exhaustive list of types can be find over the documentation.

In order to demonstrate other features, we will add three other properties: Description, Name, and Products, all of type string. We will get back to this ‘Products’ property a bit later.

Then we will add another entity named ‘Product’ which will contain five properties: Id, Description, Image, Name, and Category, respectively of type integer, string, image, string and string.

We will now see how to create relations between two entities properties. This can be done directly when the property is added by checking ‘Advanced’ for the type of the property and then selecting the property we want to bound it to. We can also do it through the properties of a property by changing its ‘Type Name’. And finally we can ‘Shift + Left click’, on the property and bound it to the property of our choice.

In this case, we will bound the ‘Category’ property to the ‘Products’ property in order to create a one-to-many relation as it is showed in the following screenshot.

relation

relation1

You may have notice that there is also the possibility to create cascade save and delete depending on your needs.

In the introduction, we talked about custom methods. Now that we have two entities we can create a custom method in our ‘Product’ entity which will be named ‘LoadByCategoryName’. In order to add a custom method, we can either click the ‘Add method’ ribbon button or right clicking on the entity and hit ‘Add > Method’.

With CodeFluent Entities you will use CFQL (CodeFluent Query Language) to create custom methods. CFQL syntax is really close to SQL syntax, which allows you to use your SQL knowledge to create methods.

CFQL allows you to keep your model logic independent of any technology. CFQL code will be afterwards converted automatically to stored procedures in the specific target language (SQL Server, Oracle, MySQL…).

As you can see in the following screenshot, this method allow us to retrieve products based on their category name.

CFQL

In the CodeFluent Entities designer we are also able to add attributes (CLR attributes) or rules to our properties. For instance, we will add an attribute to the ‘Description’ property of our ‘Product’ entity to specify this property is required thanks to the ‘System.ComponentModel.DataAnnotations’ namespace.

In order to add this attribute we will focus on the ‘Description’ property then we can either click the ‘Add attribute’ button in the ribbon or right clicking on the property hit ‘Add attribute’. In the attribute name we can directly reference the attribute, in this case ‘System.ComponentModel.DataAnnotations.RequiredAttribute’, or we can browse through namespaces to find the one which fit our needs by hitting the button next to the ‘Attribute name’ textbox as it is shown in the screenshot below.

requiredattribute

To conclude, on CodeFluent Entities designer we will talk about the inferred model. You can access it through the ribbon by hitting the ‘View Inferred Model’ button.

The inferred model allows you to foresee what will be generated by CodeFluent Entities: classes, tables, relations, attributes, and so on. Therefore, you can see if you designed your application the way you wanted to.

inferredmodel

The CodeFluent Entities Modeler is much richer than what you have seen in this post. You can take an overview on this video (http://www.youtube.com/watch?v=gsfrHJqCpgc), and for the Modern UI (http://www.youtube.com/watch?v=UUXoiz4mWB8).

Cheers,

The SoftFluent Team.

[Pet Shop Reloaded] Getting Started

June 26, 2013 Leave a comment

 

We know now what are the functional and technical context of our application: Pet Shop Reloaded. We can now start to prepare our working environment.
 
 

Installation

 

Getting ready with CodeFluent Entities

 
CodeFluent Entities is fully integrated into Visual Studio and really easy to install. We need to go to the installation page of CodeFluent Entities, download an .msi file and run it.
 

Download CodeFluent Entities

Download CodeFluent Entities


 
We just need to follow the wizard installer.
 
Installing CodeFluent Entities

Installing CodeFluent Entities


 
The installer will add a Visual Studio extension so you can access all the CodeFluent Entities features directly from your favorite IDE. So now that we have successfully installed CodeFluent Entities, let’s open Visual Studio and see that there is now a CodeFluent Entities menu.
 
CodeFluent Entities Menu

CodeFluent Entities Menu


 
You need to request a License to use CodeFluent Entities, there is a totally free, unlimited in time and full-featured license for personal use.
 
Request a FREE License

Request a FREE License


 
We will also find the CodeFluent Entities project templates when adding a new project from Visual Studio.
 
CodeFluent Entities project templates

CodeFluent Entities project templates


 
For the Pet Shop Reloaded we will add a new CodeFluent Entities blank project.

To discover CodeFluent Entities you can use a sample model provided with the project templates.

 

Getting ready with Entity Framework 5

 
Entity Framework on its version 5 is already integrated into Visual Studio 2012.
 
If you are using Visual Studio 2010 you will need to manually install the latest version of Entity Framework (version 5) from NuGet, you can refer to this page or this one to know more about installing the Entity Framework from NuGet.

If you use Visual Studio 2010 you will also need to install the DbContext generator, see the “Additional Steps in Visual Studio 2010” point.

To add a new Entity Framework model (.edmx), we need to add a new item in an existing project. For the Pet Shop Reloaded application we will host the Entity Framework model right on the ASP.NET MVC project.

Entity Framework does not contain an independent project template, it is added to an existing C# project.

 
So we add a “New Item” and on the “Data” tab we choose “ADO.NET Entity Data Model”:
 

Add a Entity Model

Add a Entity Model


 
As we are going to use the Model First approach as our Model Creation Workflow, we select the “Empty Model” option.
 
Empty Entity Model

Empty Entity Model


 
There are essentially 3 different Model Creation Workflows: Model First, Data First and Code First. If you want to know more about this you can take a look at this blog post.
 
You can extend the Entity Framework behavior by modifying or adding .tt templates.
 
 

Topology

 

The CodeFluent Entities project

 
CodeFluent Entities has its own project on Visual Studio terms. As you have a “Class Library” project, a “WPF” project or an “ASP.NET MVC” project, you will have a “CodeFluent Entities” project in your Visual Studio Solution.
 
The image below shows the main structure of a CodeFluent Entities project.
 

CodeFluent Entities project structure

CodeFluent Entities project structure


 

  • References: to add assembly references.
  • Files: to store templates for example.
  • Surfaces: contains the Modeler design surfaces (you can split your model on different design surfaces).
  • Parts: where are stored the XML files (.cfp file extension) that contain the definition of our model (entities, properties, producers…).
  • UserTypes: custom types that can be used as property types on the model.
  • Stores: persistence configurations.
  • Aspects: contains the available aspects.
  • Producers: “code generators” for different layers of our application(s) (Persistence, Business Object Model, Web Services, Web site, Azure, SharePoint…).
  • Model: contains a tree view of our model grouped by “namespaces”.

 

The Entity Framework structure

 
The Entity Framework model relies on a XML file with an .edmx extension. As we said earlier, an Entity Framework Model must be integrated in a Visual Studio project. For the Pet Shop Reloaded application we are going to call the Entity Framework model “Model.edmx”.
 

Entity Framework files structure

Entity Framework files structure


 
Under the Model.edmx file we can see different items (essentially code generators, .tt files, aka T4 templates).

On earlier versions of Entity Framework (before version 5) the code generation templates are not located under the .edmx file but at the project level.

 

  • Model.edmx: the Entity Framework model.
  • Model.Context.tt: will generate the Entity Framework Context.
  • Model.Designer.cs: default code generation (disabled by default so the T4 templates are used to generate the code).
  • Model.edmx.diagram: a XML definition of our model diagram.
  • Model.tt: T4 template that will generate POCO classes from our model.

 
 

Updates and extensions

 
 

Updating the CodeFluent Entities version

 
It is important to always have the latest version of CodeFluent Entities (in general it is the case for software products), this way you will have the newest features and fixes.
 
CodeFluent Entities is shipped with a tool called the “SoftFluent Licensing”, you will find it under the CodeFluent Entities installation folder: Program Files (x86)\SoftFluent\CodeFluent\ModelerSoftFluent.Licensing.Client.exe
 
This tool allows you to know if there is a newer version of CodeFluent Entities.
 

CodeFluent Entities Licensing

CodeFluent Entities Licensing


 
For each build version you will find the list of new features and bug fixes.
 
Update the CodeFluent Entities version

Update the CodeFluent Entities version

CodeFluent Entities does not need any external component, plugin or extension to work, it provides a lot of features and concepts. And if you need more or a specific feature you can easily extend CodeFluent (templates, producers, aspects…).

 

Updating and extending Entity Framework

 
Entity Framework is available as a NuGet package (or integrated to Visual Studio) so it can be updated from Visual Studio (or the NuGet console). You can also find extensions or templates (code generators) online.
 
If you consider that the default code generation of Entity Framework is not enough for your project, then you can modify or add T4 templates to adapt your model to your needs.
 
 


On the next blog post we are going deeper on each product, starting on how we will design the model of the Pet Shop Reloaded application.
 
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