Archive

Posts Tagged ‘Modeling’

Views, Auto-Lightweight and the Modeler

April 22, 2014 Leave a comment

In a previous post we saw how to create views and lightweight entities by using XML. Nowadays most of you are using the graphical modeler, so let’s see how to create views.

First, let’s create a simple model:

model

We can create a view that contains the supplier name and the country name. Select the supplier entity and click the “Add view” button from the ribbon:

ribbon - add view

You should see the following window:

Add view 1

Enter a valid name and select properties to include in the view. Only properties from the selected entity are shown. So to add the country name, we have to click the “Add” button and enter the binding expression “Country.Name” (auto completion prevents mistakes).

Add view 2

The « Auto infer lightweight entity » checkbox allows to generate an entity that contains selected properties. As the name suggests it’s a light entity: it’s not persistent, it has no CRUD methods (e.g. load, save, delete) nor extra properties by default, and it does not implement any interfaces other than the ICodeFluentLightEntity by default.

Now we can create a method that will load data from this view:

load from view

The generated code contains the SQL view :

CREATE VIEW [dbo].[vSupplierSupplierLight]
AS
SELECT [Supplier].[Supplier_Name], [Country].[Country_Name] AS 'CountryName'
FROM [Supplier]
INNER JOIN [Country]
ON ([Supplier].[Supplier_Country_Id] = [Country].[Country_Id])

And the inferred lightweight entity:

BOM

 

Happy View-ing!

The R&D 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 http://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.

Custom Sub Producer Example

November 16, 2012 Leave a comment

There are several ways to add custom code to the generated code. You could simply do it by using Partial classes (which would be a manual action), Snippets or Aspects. But what if you wanted to add custom code to a specific layer such as the Business Object Layer right before production? Well you would need to create your own Sub Producer.

Creating your own custom Sub Producers in CodeFluent Entities is pretty straightforward: all you have to do is to:

1. create a Class Library project referencing the following assemblies:

  • CodeFluent.Model.dll
  • CodeFluent.Model.Common.dll
  • CodeFluent.Producers.CodeDom.dll

2. create a class implementing the ICodeDomSubProducer interface.

3. build and Deploy the Class Library to the CodeFluent current directory (%ProgramFiles%\SoftFluent\CodeFluent\Modeler).

Everything is documented here with examples: Developing a Custom Sub-Producer.

Besides, since it easier to understand something we can actually see running, you’ll find a sample project to play with based on real world code on our forum: Ninject dependency injection.

 

Cheers,

Thibault NESTOR

CodeFluent Entities: Writing a custom aspect

July 27, 2012 1 comment

In the previous post, we’ve seen that CodeFluent Entities infers a meta-model from our model and that we could interact with this meta-model to apply application wide changes. In this post we’ll see how Smile

Step 1: Writing your aspect

As an example we’ll write an aspect which will add a “IsDeleted” property on all entities by default.

First of all, we added a new class library project named “Demo.Aspects” to our solution and added the following references: CodeFluent.Model.dll,  CodeFluent.Model.Common.dll and CodeFluent.Runtime.dll. Aspects can either be written in XML or in .NET. In my opinion, it’s easier to start writing aspects in .NET as you’ll have Visual Studio’s IntelliSense which will help you out using the API.

In practice, an aspect is a class implementing the IProjectTemplate interface. This interface contains a single method “Run” which takes as a parameter a “context”.

Here’s a sample implementation:

using System.Collections;
using System.Xml;
using CodeFluent.Model;

namespace Demo.Aspects
{
    public class MyAspect: IProjectTemplate
    {
        public static readonly XmlDocument Descriptor;
        public const string MyAspectNamespace = "http://www.mycompany.com/aspects/myaspect/2013/1";

        static MyAspect()
        {
            Descriptor = new XmlDocument();
            Descriptor.LoadXml(
@"<cf:project xmlns:cf='http://www.softfluent.com/codefluent/2005/1' defaultNamespace='MyAspect'>
    <cf:pattern name='My Aspect' namespaceUri='" + MyAspectNamespace + @"' preferredPrefix='mya' step='Tables'>
        <cf:message class='_doc'>This is some description for our custom aspect.</cf:message>
        <cf:descriptor name='enable'
            typeName='boolean'
            category='My Custom Aspect'
            targets='Entity'
            defaultValue='false'
            displayName='Add the MyCustomProperty'
            description='Description for our custom descriptor.' />
    </cf:pattern>
</cf:project>");
        }

        public XmlDocument Run(IDictionary context)
        {
            if (context == null || !context.Contains("Project"))
            {
                // we are probably called for meta data inspection
                return Descriptor;
            }

            // the dictionary contains at least these two entries
            XmlElement element = (XmlElement)context["Element"];
            Project project = (Project)context["Project"];

            foreach (Entity entity in project.Entities)
            {
                Property property = new Property();
                property.Name = "IsDeleted";
                property.TypeName = "bool";
                entity.Properties.Add(property);
            }

            // we have no specific Xml to send back, but aspect description
            return Descriptor;
        }
}

The method returns a XmlDocument which is described above as a string. It could also be written on a separate file.

As you can see this XML defines the aspect’s name, its XML namespace, and how it extends the CodeFluent schema (here it adds a “mya:enable” attribute on entities, whose default value is false).

Step 2: Using your aspect

Compile the “Demo.Aspects” project.

In the solution explorer, select the “Aspects” folder and click “Add Existing Aspect…”. Browse for our Demo.Aspects.dll that we created previously and here’s what you should see:

image

Great! As you can see, information returned by our descriptor is properly parsed and displayed Smile

Hit OK, and now by default all your entities should have an extra “IsDeleted” property added when the model is inferred, which means that a “IsDeleted” column will be created for all tables, all stored procedures will be updated to include this column, and it’s the same in the middle tier and the UI tier. You can view this by clicking on the “View Inferred Model” button available in the ribbon:

image

Useful Links

Hope this helps,

Carl Anderson

New CodeFluent Entities Release Available

January 17, 2012 3 comments

A new version of CodeFluent Entities is publicly available (1.0.60110.644) which contains a set of new features which we’ll overview in this post.

NewBuild

Feature #1: The Resource Grid

This new release provides a new culture-oriented grid form which allows batch resources edition (project-wide or node-specific).

image

 

Feature #2: The Instance Grid

Same as the the resource grid but for instances:

image

We can now edit multiple instances at once Smile

 

Feature #3: “Go To Xml”

Doing a right-click on a concept on the surface (entities, properties, views, methods, forms, etc.) you now have a “Go To Xml” option in the contextual menu which will take you to the XML node corresponding to the selected shape.

image

 

Feature #4: Support for non-latin characters

I’m sure all non-latin users will be glad to know that using the latest build, you can design your application using non latin-characters:

image

 

Feature #5: Minimize the Ribbon

Probably the sexiest feature in this release: you can now hide/show the ribbon using the upper-right corner arrow:

image

image

 

Interested in getting more details on what is shipped with each release? Subscribe to the CodeFluent Entities RSS Feed and you’ll automatically get all bug fixes and new features comprised in each build as soon as they are online!

 

Carl Anderson

CodeFluent Entities: Member Format Expressions (Final Part)

January 13, 2012 Leave a comment

Last post exploring this feature of the Modeler, detailing what you can do in conditions and the MessagesBrowser class.

Conditions

In the previous post, we’ve seen that we could specify a condition attribute in the <if> and <font> tags. A few notes on the condition attribute:

  • Property paths in condition attributes should not be surrounded by curly brackets (i.e. use IsKey instead of {IsKey}),
  • Shortcuts available on the right side of the statement to ease condition declaration,
  • Therefore prefer placing evaluated values on the left side of the statement rather than on the right.

The following operators are supported:

  • “==” or “=” for a case insensitive equals,
  • “[=CS]” for a case sensitive equals,
  • “!=”, “<>” for a case insensitive not equals,
  • “[!=CS]” for a case sensitive not equals,
  • “>=” for greater than equals,
  • “<=” for lower than equals,
  • “>” for greater than,
  • “<” for lower than,
  • “[StartsWith]” for a case insensitve starts with,
  • “[StartsWithCS]” for a case sensitive starts with,
  • “[EndsWith]” for a case insensitive ends with,
  • “[EndsWithCS]” for a case sensitive ends with,
  • “[Contains]” for a case insensitive contains,
  • “[ContainsCS]” for a case sensitive contains.

Here’s how to highlight all properties ending with “Id”:

<font condition=”Name [EndsWith] ‘Id'” color=’red’>{#Name}<else/>{#Name}</font>

Note: don’t forget to surround the right side statement with quotes so the evaluator knows it’s a string.

Please note that there are also shortcuts such as you don’t have to specify ‘> 0’ for numbers for instance:

{#Name}<font condition=’AllRules.Count’ color=’#007F0E’> (Rules={AllRules.Count})</font>

Will suffix properties with “(Rules=X)” in green:

image

 

The MessagesBrowser Class

The MessagesBrowser class is a class you can use as a property path and which allows you to access messages (a.k.a. resources) defined for the current concept (entity or property). For instance, if you defined English resources for each of your address properties in the documentation class:

image

Using the following expression you can display them:

{#Name} ({MessagesBrowser._doc.en-US})

Here’s the result:

image

Note: As of today, for performance results the MessagesBrowser class is cached and built on first access, so that defining a new resource or editing one will not be reflected on the surface.

Carl Anderson

CodeFluent Entities: Member Format Expressions (Part 2)

January 13, 2012 1 comment

In the previous post, we’ve seen that we could define expressions such as “{Name}” to display the property name, “{#Name}” to display the decamelized property name, and mix values and literals in expressions to do stuff such as “{#Name} (IsKey={IsKey})”.

In this post we’re going to go a little further by introducing “tags”. Three tags are supported in expressions:

  • Font: use it to define styles in your expression,
  • If: use it to define conditions,
  • Else: same as if.

For instance specify the following expression:

<font color=”blue”>{#Name}</font>

Will display all properties in blue:

image

We could also combine the tags to display key properties in red and the other ones in blue:

<if condition=IsKey><font color=”red”>{#Name}</font><else/><font color=”blue”>{#Name}</font></if>

Note: the value in the condition attribute is automatically evaluated, no need to wrap the property path between curly brackets.

And here’s the result:

image

So expressions don’t get too long the <font> tag also has a condition attribute so you don’t necessarily have to wrap it in a <if> tag. Therefore, you could get the same result using this expression:

<font condition=IsKey color=”red”>{#Name}<else/><font color=”blue”>{#Name}</font></font>

The <font> tag supports the following attributes:

Here’s another expression displaying the property type name in a light purple (Alpha=DD, Red=6E, Green=14, Blue=FF):

{#Name} : <font color=”#DD6E14FF”>{#DisplayTypeName}</font>

And here’s the result:

image

Once again use member format expressions with caution as they’ll be evaluated for all property names, so the lighter they are, the better performances will be and vice versa.

Carl Anderson

CodeFluent Entities: Member Format Expressions (Part 1)

January 12, 2012 1 comment

Using CodeFluent Entities, you can use “Member Format Expressions” to customize the way names of entities and properties are formatted:

image

Several expressions are provided by default but you can also define your own expressions by selecting “Choose” (you do this from the “Modeler Tab” of the ribbon or from the contextual menu):

image

Clicking “Add New” will allow you to define your own:

image

Creating this one will display “Test!” for all my properties:

image

It’s not that useful in practice, but still, it illustrates that you can set whatever you want in it and most importantly that it supports literals Smile

As you can see, the default expressions use property paths surrounded by curly brackets such as {Name} and {DisplayTypeName} to displays values from the model. You can access a list of available property paths by clicking on the “Insert Property Path” button which will display the following dialog:

image

For instance, here’s an expression displaying the property name and indicating if the property is a key between parenthesis:

image

Here’s the result on my Address entity:

image

If you prefix your property path with a ‘#’, the value will be decamelized. For instance the expression “{#Name} (IsKey={IsKey})” will display (the difference is visible on the Line1 and Line2 properties):

image

Sweet isn’t it?! Smile

It for sure is a nice feature too change as you can change how the model is presented with a single expression, however use format expressions with caution though, because as they’re evaluated to display each of your properties in your model, big expressions doing a lot of stuff and displaying a lot of text can become a performance killer on big models.

Carl Anderson

Adding your own models to the CodeFluent Entities Starter Wizard

December 29, 2011 Leave a comment

As mentioned in the posts “The Starter Wizard” and “New CodeFluent Entities Milestone”, the Modeler provides a wizard creating the structure of your solution as well as configuring your producers so they point to the freshly created projects.

Among the wizard pages, there’s a page allowing you to select a model template from which you want to start:

Models displayed in this page are the default official ones (blank, and sample ones), but just as you can add your custom producers or custom rules to the Modeler, you can add your custom models to his screen as well.

First you need to locate the custom configuration. You’ll find this information by:

  • opening Visual Studio,
  • go to “Tools > Options… > CodeFluent Entities”,
  • and select the advanced view using the advanced button at the top of the property grid.

As you’ll see, there’s a property named “Custom Configuration File Path” which points to a Custom.config file:

Open this file (or create it if necessary) and add the following XML content to it:

<codeFluent.Modeler>
  <starterWizardModelDescriptors>
    <starterWizardModelDescriptor name="Test" fileName="Test.cfxproj" description=”A custom model.” />
  </starterWizardModelDescriptors>  
</codeFluent.Modeler>

This indicates the Starter Wizard to display a model named “Test”, corresponding to the “Test.cfxproj” project, in the “Select your model” wizard page.

Note: the cfxproj file should be placed in CodeFluent Entities’ Visual Studio templates folder which is “C:\Program Files (x86)\SoftFluent\CodeFluent\VSTemplates\Projects”).

Save the file, open your wizard, here’s what you should see now:

And voilà: our custom model project is now proposed in the wizard!

Carl

Follow

Get every new post delivered to your Inbox.

Join 48 other followers