Archive

Posts Tagged ‘Producers’

Using the SQL Server Template Producer to generate Clustered Indexes

November 27, 2012 Leave a comment

In this post we’ll see how using CodeFluent Entities’ SQL Server Template Producer, you can generate SQL scripts using  the built-in template engine whilst accessing the inferred meta-model, and then automatically deploy the generated script on your desired server.

By default SQL Azure and SQL Server add the clustered index on the primary key if a clustered index on the table does not already exist and if you do not specify a unique nonclustered index. In the case where the primary key is of GUID type it won’t be efficient. The reason for this is that GUIDs are generated in non-sequential order and SQL Server orders a clustered index sequentially. It will work – SQL Server will let you build a clustered index around a unique identifier column, however it will cause the SQL Server to do unnecessary work and cause performance slowdowns.

That being said, what we can do is using the SQL Template Producer to remove all inefficient clustered indexes and recreate them on the right columns. Let’s even go a bit further and create a little aspect that will add a property on each property to tell if a clustered index needs to be created or not on that particular property.

Add a new Part called IsClusteredIndexAspect and past it the following code (replacing the defaultNamespace’s value by yours):

<cf:project xmlns:cf=”http://www.softfluent.com/codefluent/2005/1” defaultNamespace=”yourNamespace”>

<cf:pattern name=”IsClusteredIndex Aspect” namespaceUri=”http://www.sample.com/aspects/isclusteredindexaspect/2012/11” preferredPrefix=”sa” step=”Tables”>

<cf:message class=”_doc”>
This aspect creates an extra IsClusteredIndex bool property on every property.
</cf:message>

<cf:descriptor name=”IsClusteredIndex” typeName=”boolean” targets=”Property” defaultValue=”false” displayName=”IsClusteredIndex” description=”Should the IsClusteredIndex Aspect apply to this property?” />

</cf:pattern>
</cf:project>

This will create our aspect and add a IsClusteredIndex property on each property in the “Aspects and Producers” property grid:

image

You can by now choose which property you want to use as a clustered index. Obviously this property should be set to true only on one property by entity since clustered index cannot be applied on several columns.

Now let’s write a script that will remove all clustered indexes and then create new ones based on the columns selected thanks to our aspect. In a file called “[Template]CreateIndexes.sql” add it the following code (Note that this code is only an illustration for this post, it does not take into account constraints, primary keys and so on):

[%@ namespace name="CodeFluent.Model"%]
[%@ namespace name="CodeFluent.Model.Persistence"%]
[%@ namespace name="CodeFluent.Producers.SqlServer"%]
/* [%=Producer.GetSignature()%] */

[%foreach (Entity e in Producer.Project.Entities)
{%]
    --remove any existing clustered index on e.Table.FullName
    --[...]
  
   [%foreach (Property p in e.Properties)
    {
        if (p.GetAttributeValue("sa:IsClusteredIndex", false))
        {%]      
        --create your index such as:
        CREATE CLUSTERED INDEX [CL_[%=p.Entity.Table.Name%]] ON [%=p.Entity.Table.FullName%] ([[%=p.Column.Name%]]);
        GO
        [%}
    }
}%]

 

Create a folder called “Template” under the file folder of your CodeFluent Entities project:

image

Right click on that folder and choose “Add existing item” then browse to your template file and select it.

Now in your CodeFluent Entities project, add an instance of the SQL Server Template Producer with your Template directory as the “Source Directory” and set the “Target Directory” to the project of you choice and then build over your model. The SQL Server Template Producer will generate a script file from your template, and run the script on the server removing and creating clustered indexes. Therefore using the template producer you can quickly create complex scripts by taking advantage of the meta model.

 

Cheers,

Thibault NESTOR

Generating unit test skeleton using the Template Producer

November 26, 2012 1 comment

We already introduced the Template Producer in a previous post with a small example showing how to generate a DGML graph from a CodeFluent Entities model. This post is another example to remind you how easy it is to generate text files using the Template Producer whilst accessing the inferred meta-model.

Let’s say we’d like to generate a skeleton for our unit tests. By skeleton I mean a vb or csharp file by entity that will contain test methods ready to be implemented.

Assuming we are writing a pretty simple bank application. Our model has an “Account” entity and 3 methods (to deposit, withdraw, and transfer funds) as follow:

image

Supposing we’re using Nunit as unit-testing framework, let’s create our template to be used by the Template Producer:

    1. Add a new folder called Templates into the File folder
      ScreenShot047
    2. Add it a new text file (Ctrl+shift+A) called “[Template]UnitTests.tplScreenShot049
    3. Past it the following code describing our skeleton:
[%@ namespace name="System"%]
[%@ namespace name="CodeFluent.Model"%]
[%@ namespace name="CodeFluent.Model.Code"%]
[%@ template enumerable='Producer.Project.Entities' enumerableItemName="entity" enumerableTargetPathFunc='Path.Combine(Path.GetDirectoryName(TargetPath), String.Format("{0}Tests", entity.ClrFullTypeName)) + ".cs"' %]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;

namespace [%= entity.Namespace %]
{
    [TestFixture]
    public class [%= String.Format("{0}Tests", entity.Name) %]
    {
        [SetUp]
        public void Init()
        {
            /* ... */
        }

        [TearDown]
        public void Cleanup()
        {
            /* ... */
        }

        [% foreach(Method m in entity.Methods) { if (!m.Enabled) continue; %]
            [Test]
            [%= String.Format("public void {0}Test()", m.Name)  %]
            {
                /* ... */
            }
        [% } %]
    }
}

Basically, what the template does is that it iterates through all entities of the project as well as each method to write a file by entity containing a test class with all test methods.

  1. Create a class library project called Bank.UnitTests to store all your unit tests and add it a reference to Nunit framework.
  2. Add a Template Producer and set the Source directory to your Templates folder created earlier and the Target directory to the Bank.UnitTests project.

The Template Producer instance will execute all templates placed in the Templates directory, and place output files in the Bank.UnitTests project directory.

Building your model should produce one file called Bank.AccountTests.cs with all the test methods ready to be implemented:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;

namespace Bank
{
    [TestFixture]
    public class AccountTests
    {
        [SetUp]
        public void Init()
        {
            /* ... */
        }

        [TearDown]
        public void Cleanup()
        {
            /* ... */
        }

        [Test]
        public void DepositTest()
        {
            /* ... */
        }

        [Test]
        public void WithdrawTest()
        {
            /* ... */
        }

        [Test]
        public void TransferFundsTest()
        {
            /* ... */
        }

    }
}

As you can see, this short and simple example gives you an idea of what it is possible to do by taking advantage of the meta model using the Template Producer.

Want to know more? You’ll find more information on the Template Producer here.

Cheers,

Thibault NESTOR

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

SQL Azure producer now has its “Diff engine”!

October 30, 2012 1 comment

CodeFluent Entities provides an out-of-the-box SQL Azure producer. Using this producer you can generate SQL Azure scripts and automatically run them on your SQL Azure database.

Although this producer enables you to work on a local SQL Server instance in order to benefit of the producer’s Diff Engine on the local instance, it was missing its own Diff Engine! Indeed, for each generation the producer was dropping tables before recreating them.

This new build 686 brings to the SQL Azure Producer its own Diff Engine. It means that as of today, either using SQL Azure or SQL Server producer, you can continuously generate without loosing data.

The SQL Azure producer’s property grid as been reorganized so the distinction between Local SQL server and Online SQL Azure properties is clearer. Besides, you’ll find a new property under the Online SQL Azure category called “Create Diffs” to enable or disable the SQL Azure Diff Engine. The Diff Engine is enable by default.

 

azure

 

Cheers,

Thibault Nestor

Generating a WPF Smart Client using the Smart Client Producer

October 22, 2012 Leave a comment

Hello!

In a previous posts, we showed you the output of the WPF Smart Client Producer. In this post we’ll show you how to generate a WPF smart client. It will be a WPF application consuming WCF services thanks to a proxy and the data will be stored in a database Smile.

Creating the solution

Start by creating a new CodeFluent Project. We’ll use the “ContactManager Sample Model” for the purpose of this article.ContactManagerModel

Add a new Class Library project named “ContactManager” to your solution. It will be used to host the generated files corresponding to your Business Object model and WCF service’s contracts. Add it a folder called “ServicesConfig” that will be used to store your WCF service’s configuration files.

Add a new Class Library project named “ContactManager.Proxy” to your solution. It will be used to host the generated files corresponding to the proxy.

Add a new SQL Server Database project named “ContactManager.Persistence” to your solution. It will be used to host your generated SQL scripts.

Add a new WPF application project named “ContactManager.SmartClient” to your solution. It will be used to host the generated files of your WPF application. Remove the MainWindow.xaml file since we are going to generate our own. Also, by default, Microsoft Visual Studio 2010 sets the target framework to .NET Framework 4 Client Profile. Go to the property of your project and change the target to .NET Framework 4 in order to use the standard libraries.

image

Adding the producers

The Business Object Model Producer

To generate your Business Objects model, add the Business Object Model Producer to your CodeFluent Entities project by clicking “Add new producer” on the “Producers” folder in Visual Studio’s Solution Explorer, expand the Business Layer Producers node and select it:

image

In the Target Directory field, select your Class Library project called ContactManager.

image

Click OK.

The SQL Server Producer

To generate your persistence scripts, add the SQL Server Producer (or the one that suits your configuration) to your CodeFluent Entities project by clicking “Add new producer” on the “Producers” folder in Visual Studio’s Solution Explorer, expand the Persistence Layer Producers node and select it:

image

In the Connection String field enter your connection string used to connect to your SQL Server. Also in the Target Directory field, select your SQL Server Database project called ContactManager.Persistence. Finally in the Target Version field, select your SQL Server version.

The Service Object Model Producer

To generate your WCF service and your proxy, add the Service Object Model Producer to your CodeFluent Entities project by clicking “Add new SubProducer” on your  “Business Object Model” producer in Visual Studio’s Solution Explorer, expand the Business Layer Producers node and select it:

image

In the Target Directory field, select your Class Library project called ContactManager.Proxy and click OK.

The Template Producer

Note: The Template producer is not mandatory. However, it is really handy if you want to be able to quickly run and test your WCF service using the CodeFluent Entities Hoster.

Lets now generate the configuration files of your WCF service. Add the Template Producer to your CodeFluent Entities project by clicking “Add new producer” on the “Producers” folder in Visual Studio’s Solution Explorer, expand the Utility Producers node and select it:

ScreenShot032

In the Source Directory field select the “Server” folder located at “CodeFluent Entities installation folder > Modeler >Templates > ServiceModel”. And in the Target Directory field, select the folder called ServicesConfig located in your Class Library project called ContactManager, then click OK.

The WPF Smart Client Producer

Then, to generate your WPF smart client, add the WPF Smart Client Producer to your CodeFluent Entities project by clicking “Add new producer” on the “Producers” folder in Visual Studio’s Solution Explorer, expand the Application Producers node and select it:

image

In the Target Directory field, select your WPF application project called ContactManager.SmartClient and click OK.

Generating code

Now to start generating code, build your CodeFluent Entities project called ContactManager.Model.

Here is the visual studio solution you should have by now, each project containing the generated code (your database should have been created too):

image

Building and running the application

At this stage, your application has been generated and is almost ready to be built and run. Since your WPF application uses the Proxy you need to add your Class Library project called ContactManager.Proxy as a reference to your WPF application project called ContactManager.SmartClient project.

Now you can build your solution, then run your WCF service as you usually do or thanks to the CodeFluent Entities Hoster using your generated service configuration files. Finally start your WPF application.

Tip: If you use the CodeFluent Entities Hoster, a quick and easy way to ensure the executable is automatically copied to the output directory is to add a reference to it. This is absolutely not required to compile your Business Object model (your Class Library called ContactManager), it’s just a shortcut to have the executable in the output directory without having to create post-build events.

And tadaaa! You’ve created your 100% functional WPF smart client without a single line of code!

SmartClient (1)

SmartClient (2)

Enjoy!

Thibault Nestor

User Interfaces generated by CodeFluent Entities using out-of-the-box producers

October 16, 2012 2 comments

Over the past articles we showed you how to use the following UI producers provided out of the box by CodeFluent Entities:

· Windows Store producer

· ASP.NET Web Forms Producer / AJAX/JSON

· WPF Smart Client Producer

· SharePoint Web Part Producer

In this article I want to emphasize the fact that CodeFluent Entities is totally UI-agnostic. Indeed from the same and unique model you can generate screens that will be rendered in the targeted platforms of your choice. Here is for instance the list of all UI producers available:

UI_Producer

Let see all the user interfaces that CodeFluent Entities has been able to generate from the exact same model, using those different producers.

Note that the generated applications are not just a set of user interfaces; they are actually complete interactive applications sharing the same business object model, database and are 100% functional.

We used the “ContactManager Sample Model” supply by CodeFluent Entities:

ContactManagerModel

Here is the ContactManager model:

ContactManagerSurface

Since we’ve already seen how to use the producers provided by CodeFluent Entities in previous blog posts I’m going to skip their configurations and directly present you the generated UIs:

UI generated using the Windows 8 Store Producer:

The homepage generated by default lists all namespaces and their contained entities:

Windows Store (1)

Clicking on an entity gets you to the entity page.
On this entity page you’ll find a screenshot of the entity from which this page was generated.

Right Clicking on this page or typing Ctrl+Z will bring up a menu at the bottom where you’ll find the list of actions available on this entity. Those actions correspond in fact to business methods provided by the entity:

Windows Store (2)

Here is the screen displaying for the Contact entity when clicking on the “LoadAll” button and then selecting a contact:

Windows Store (3)

Bringing back the menu by hitting Ctrl+z or right clicking will enable you to create, edit or delete an entry:

Windows Store (4)

For instance, pushing the Edit button will give you the following screen:

Windows Store (5)

UI generated using the ASP .NET MVC Producer:

The homepage generated by default lists all namespaces and their contained entities:

ASP NET WebApp (1)

Clicking on an entity gets you to the entity page.
On this entity page you’ll find a screenshot of the entity from which this page was generated.

On the left side of the page you’ll find a list of actions available on this entity. Those actions correspond to business methods provided by the entity:

ASP NET WebApp (2)

Here is the screen displaying for the Contact entity when clicking on the “LoadAll” button:
It lists all the contacts through an HTML table and enables sorting.
From it you can detail, edit or remove a contact.

ASP NET WebApp (3)

Clicking on the “Details” hyperlink will bring up the following screen:

ASP NET WebApp (4)

Clicking on the “Edit” hyperlink will enable you to edit the entry:

ASP NET WebApp (5)

UI generated using the ASP .NET AJAX Producer:

The homepage generated by default lists all namespaces and their contained entities:

ASP NET AJAX-JSON (1)

Clicking on an entity gets you to the entity page.
On this entity page you’ll find a screenshot of the entity from which this page was generated.

On the left side of the page you’ll find a list of actions available on this entity. Those actions correspond to business methods provided by the entity:

ASP NET AJAX-JSON (2)

Here is the screen displaying for the Contact entity when clicking on the “LoadAll” button:
It lists all the contacts through an Ajax grid supporting sorting and paging.
From it you can detail, edit or remove a contact.

ASP NET AJAX-JSON (3)

And the one when clicking on the “Edit” button:

ASP NET AJAX-JSON (4)

UI generated using the ASP .NET WebForms Producer:

The homepage generated by default lists all namespaces and their contained entities:

ASP NET WebForms (1)

Clicking on an entity gets you to the entity page.
On this entity page you’ll find a screenshot of the entity from which this page was generated.

On the left side of the page you’ll find a list of actions available on this entity. Those actions correspond to business methods provided by the entity:

ASP NET WebForms (2)

Here is the screen displaying for the Contact entity when clicking on the “LoadAll” button:
It lists all the contacts through an HTML table and enables sorting.
From it you can edit or remove a contact.

ASP NET WebForms (3)

And the one when clicking on the “Edit” button:

ASP NET WebForms (4)

UI generated using the Smart Client (WPF) Producer:

The first screen generated by default lists all namespaces and their contained entities:

SmartClient (1)

Clicking on an entity will load all the data corresponding to it:
From it you can create, edit or remove an entry.

SmartClient (2)

Clicking on an entry will open a window to edit it:

SmartClient (3)

UI generated using the SharePoint WebParts Producer:

The homepage generated by default lists all namespaces:

SharePoint (1)

Clicking on a namespace lists all its entities:

SharePoint (2)

Clicking on an entity gets you to the entity page:
It lists all the data of that entity through a Web Part.
From it you can create a new entry, detail, edit or delete one.
SharePoint (3)

For instance, clicking on an entry brings up its details:

SharePoint (4)

and clicking on the “Edit” button brings up the editor:

SharePoint (5)

As you can see, from a same model we have generated several UIs all consistent with each other.

Besides, thanks to the Platform Independent Form Editor you can also define forms directly on their entities which will then be translated into actual screens by user interface producers. We talked about it in details in this article.

Finally, in the case you did not find the desired producer, I remind you that you can create your own template and use it with the Template Producer or you can even create your own custom producer. All you’ll need to do would be to implement the IProducer interface.

To sum up, CodeFluent Entities is able to generate 100% functional applications with the UI of your choice just by using the right producer.

Cheers,

Thibault Nestor

Introducing the CodeFluent Entities Windows Store producer

October 4, 2012 4 comments

In this article, we’ll see how to use the brand new CodeFluent Entities “Windows Store” producer.

We’re going to create a complete back-end application that will host web services exposing data which will be consumed by a Windows Store application.

I will use an existing model provided out-of-the-box by CodeFluent Entities for this demo, namely the “ContactManager” model.

Creating the solution

Since my Windows Store application is going to consume web services, I’ll need to do some work before I can add the “Windows Store” producer.

First, I’ll add two projects to my solution, a standard C# class library project and an empty Web Application project. My class library project will contain the CodeFluent Entities generated business entity classes, SQL scripts and WCF services. Here is what I will do for this:

· Add the “Business Object Model” producer, make it point to my class library project;

· Add a “Service Object Model” sub-producer to this producer. For this sub-producer I’ll specify “Enable JSON” as “JSON options” and I don’t want to produce a proxy so I’ll set the “Produce Proxy” property to “False”;

· Create a new folder named “Scripts” to my class library project which will contain my generated SQL scripts to generate my database. Note we could also create a specific “SQL Server Database” project to hold these files;

· Add a new persistence “SQL Server” producer, and set its target directory to the “Scripts” folder we’ve just created;

· Now, my empty web application project will host my standard WCF .svc files. To quickly generate these, I will add an instance of the “Template” producer (Add new producer > “Utility Producers” > Template). Since I want to generate JSON, I’ll specify for the “Source Directory” the “Services” folder located at “CodeFluent Entities installation folder > Modeler >Templates > ServiceModel > JsonWebServices > Services” and for the “Target Directory” my empty web application folder.

Adding the Windows Store project

I’ll now add a new Windows Store Visual Studio project, a JavaScript Grid App project. Note: this is the only project type supported by the CodeFluent Entities Windows Store producer for the moment. This is pretty much what we have to do regarding the Windows Store project.

Adding the Windows Store producer

Now that our standard Windows Store project is added, I’ll need to add an instance of the brand new CodeFluent Entities Windows Store producer to my model:

Screenshot (11)

Screenshot (12)

Since the Windows Store application will consume the web services that will be generated, I’ll need to reference the “Server Url“ in the Windows Store producer configuration. In this case, the “Server Url” is the URL of the web application I added earlier: http://localhost:49774/ (Please adapt to your settings). I’ll also set the “Base Services Url” to http://localhost:49774/Services.

Then I’ll set the “Target Directory“ property to point to the Windows Store project folder I added and leave other properties to their default values according to the screenshot below.

Screenshot (8)

I’m now ready to build all that!

Generating the code and launch the app

To generate, as usual, I’ll right click on my CodeFluent Entities project and hit ‘Build’.

Note: you may get back a CodeFluent Entities CF3708 error while trying to generate. It means the project attribute ‘createDefaultMethodForms’ is set to false. To set it to True, go to your CodeFluent Entities project properties, find the attribute in the ‘UI’ section, and set it to True. Starting with build 1.0.61003.684, the ‘createDefaultMethodForms’ attribute is set to True by default, on new projects.

Now that all our layers are generated, I’ll need to specify on my solution properties that I want multiple startup projects.

So I’ll set as first startup project my web application project which host my services and as second startup project my Windows Store application project like this:

Screenshot (13)

Now let’s hit ‘F5’ to run my projects and voilà! Here is my complete Windows Store connected application consuming my WCF/JSON web services, without a single line of code!

Screenshot (5)Screenshot (6)Screenshot (7)

Cheers,

Aymeric ROLAND.

Introducing CodeFluent Entities PostgreSQL Producer

August 20, 2012 Leave a comment

CodeFluent Entities 2012 – Build 060809 introduced a new Persistence layer producer: the PostgreSQL Producer!

The producer supports PostgreSQL 8.4 and above (8.3 is soon to be discontinued) and relies on the ADO.NET data provider Npgsql 2.0.11. The producer will try to load dynamically the Npgsql assembly. (You might need to copy the Npgsql.dll and Mono.Security.dll in your CodeFluent Entities installation directory if you don’t want to register Npgsql in the GAC).

Please also note the PostgreSQL Producer also requires the liboss-uuid library to be installed on your server. On Windows, this library is shipped with the standard Windows packages of PostgreSQL 8.4+, and on Unix/Linux, you may need to install the postgresql-contrib package and its dependencies like libossp-uuid16, for the producer to be able to deploy the generated script on your server.

Getting started

The producer is available in the Persistence Layer Producers section of the Add New Producer window:

as well as directly from the Starter Wizard:

This is how you can set the connection string (in the Wizard pages):

A first model

I created a new project with the Start Wizard and design this very simple two-entity model:

Basically all the employees have a first name, a last name, a birth date, and a job. Each job has salary – of type currency, a name and employees. I added two instances to the model: an employee named John Doe, born on June 12th, 1974 with a job named CEO and which salary is 30,000.

I just set the Target Version of the PostgreSQL Producer to version 9.0 which the version I am currently running on my computer, and built the project.In the output window I can see the result of the generation process; the PostgreSQL producer generated 11 files and succeeded:

All the automatically generated .SQL script files are available in the Persistence project of the solution:

If I connect to my database with an administration tool I can see that a new database has been created with the named I specified in the Connection String, and populated with my model and instances:

And I haven’t written a line of code yet!

Consuming the generated persistence layer

Consuming the PostgreSQL generated database is as easy as configuring the right connection string in the client project. In my case I created a Console Application Project named MyCompany.Management.Client.

To prepare it, I had to reference my BOM Project – in my case MyCompany.Management – that was automatically created by the Starter Wizard, Npgsql.dll and CodeFluent Entities runtime, i.e. CodeFluent.Runtime.dll and CodeFluent.Runtime.PostgreSQL.dll. Note that you might need to set the Copy Local property to True for the Npgsql.dll reference if the dll is not registered in the GAC.

I also had to change the target framework of the project from .NET Framework 4.0 Client Profile to the full .NET Framework 4.0.

As I am using the PostgreSQL Producer I have to set the correct Connection String in App.config file:

<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="MyCompany.Management" type="CodeFluent.Runtime.CodeFluentConfigurationSectionHandler, CodeFluent.Runtime" />
  </configSections>
  <MyCompany.Management persistenceTypeName="PostgreSQL" connectionString="Server=localhost;Database=MyCompany_Management;User Id=postgres;Pwd=password" />
</configuration>

Note it is important to specify the persistenceTypeName=“PostgreSQL” attribute.

Here is now the code of my console application :

using System;
namespace MyCompany.Management.Client
{
  class Program
  {
    static void Main(string[] args)
    {
      // Create a new employee
      Employee newbie = new Employee();
      newbie.FirstName = "Jane";
      newbie.LastName = "Doe";
      newbie.BirthDate = new DateTime(1990, 01, 15);

      // Persist Jane Doe
      newbie.Save();

      // Load all the employees
      EmployeeCollection employees = EmployeeCollection.LoadAll();
      foreach (Employee employee in employees)
      {
        Console.Write("- {0} {1}, born on {2:MM-dd-yyyy}",
          employee.FirstName,
          employee.LastName,
          employee.BirthDate);

        if (employee.Job != null)
        {
          Console.Write(", is {0} with a salary of {1:C}",
            employee.Job.Name,
            employee.Job.Salary);
        }

        Console.WriteLine();
      }
    }
  }
}

It creates a new employee, saves it, and then loads a list of all the employees. As we can see, there is no specific code about PostgreSQL. Its use is completely transparent at this level.

And here is the result:

And the populated table:

Happy PostgreSQL-ing!

Baudouin Giard

Introducing CodeFluent Entities MySQL Producer

August 16, 2012 Leave a comment

CodeFluent Entities 2012 – Build 060703 introduced a new Persistence layer producer: the MySQL Producer! The producer supports MySQL 5.1 and above and relies on the MySQL Connector for .NET version 6.5.4.0. The producer will try to load dynamically the MySql.Data assembly. You might need to copy the MySql.Data.dll in your CodeFluent Entities installation directory if you don’t want to register the MySQL Connector in the GAC.

Getting started

The producer is available in the Persistence Layer Producers section of the Add New Producer window:

as well as directly from the Starter Wizard:

This is how you can set the connection string (in the Wizard pages):

A first model

I created a new project with the Start Wizard and designed this very simple model composed of two entities:

Basically all the employees have a first name, a last name, a birth date, and a job. Each job has salary – of type currency, a name and employees.

I added two instances to the model: an employee named John Doe, born on June 12th, 1974 with a job named CEO and which salary is 30,000.

I also set the Target Version property of the MySQL Producer to version 5.5, which is the version I am currently using on my computer, and built the project, like any other CodeFluent Entites project. In the output window I can see the result of the generation process. The MySQL producer has generated 9 files and succeeded:

All the automatically generated .SQL script files are available in the Persistence project of the solution:

If I connect to my MySQL database with an administration tool I can see that a new database has been created with the named I specified in the Connection String, and populated with the tables automatically inferred from my model as well as instances:

 

 

 

And I haven’t written a line of code yet!

Consuming the generated persistence layer

Consuming the MySQL generated database is as easy as configuring the right connection string in the client project. I my case, I created a Console Application Project named MyCompany.Management.Client.

To prepare it, I had to reference my BOM Project – in my case MyCompany.Management – that was automatically created by the Starter Wizard, MySql.Data.dll (the MySQL ADO.NET provider) and the CodeFluent Entities runtime, i.e. CodeFluent.Runtime.dll and CodeFluent.Runtime.MySQL.dll. Note that you might need to set the Copy Local property to True for the MySql.Data.dll reference if the dll is not registered in the GAC.

I also had to change the target framework of the project from .NET Framework 4.0 Client Profile to the full .NET Framework 4.0.

As I am using the MySQL Producer I have to set the correct Connection String in App.config file:

<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="MyCompany.Management" type="CodeFluent.Runtime.CodeFluentConfigurationSectionHandler, CodeFluent.Runtime" />
  </configSections>
  <MyCompany.Management persistenceTypeName="MySQL" connectionString="Server=localhost;Database=MyCompany_Management;User Id=root;" />
</configuration>

Note that it is important to specify the persistenceTypeName=“MySQL” attribute, otherwise we would be using the default persistence layer which is SQL Server. Here is the code of my console application :

using System;
namespace MyCompany.Management.Client
{
  class Program
  {
    static void Main(string[] args)
    {
      // Create a new employee
      Employee newbie = new Employee();
      newbie.FirstName = "Jane";
      newbie.LastName = "Doe";
      newbie.BirthDate = new DateTime(1990, 01, 15);

      // Persist Jane Doe
      newbie.Save();

      // Load all the employees
      EmployeeCollection employees = EmployeeCollection.LoadAll();
      foreach (Employee employee in employees)
      {
        Console.Write("- {0} {1}, born on {2:MM-dd-yyyy}",
          employee.FirstName,
          employee.LastName,
          employee.BirthDate);

        if (employee.Job != null)
        {
          Console.Write(", is {0} with a salary of {1:C}",
            employee.Job.Name,
            employee.Job.Salary);
        }

        Console.WriteLine();
      }
    }
  }
}

It creates a new employee, saves it, and then loads a list of all the employees. As we can see, there is no specific code about MySQL. Its use is completely transparent at this level.

And here is the result:

And the populated table:

 

Happy MySQL-ing!

Baudouin Giard

CodeFluent Entities: Basic Tips To Lower Generation Time

April 10, 2012 Leave a comment

First let’s start with some metrics. For this post I created 4 models:

  • Sample10 containing 10 entities of 10 properties,
  • Sample100 containing 100 entities of 10 properties,
  • Sample300 containing 300 entities of 10 properties,
  • Sample500 containing 500 entities of 10 properties

 

image

Screenshot of the Sample500 default surface

 

Furthermore, each model has the same two producers configured:

  • The SQL Server Producer,
  • And the Business Object Model Producer.

Note: A producer is a code generator translating the platform independent model you designed into scripts (e.g. T-SQL, PL/SQL), code (e.g. C#, VB.NET), services (e.g. ASMX, WCF) or UIs (e.g. SharePoint Web Parts, ASP.NET).

Finally, I’ve got a local SQL Server 2008 which my SQL Server targets and I’m generating the .NET Business Object Model in C#.

Now, keeping the default settings and generating each model from scratch using CodeFluent Entities (generate the persistence scripts, create the database, deploy them and generate the .NET API) takes:

  • 9 seconds for Sample10
  • 44 seconds for Sample100
  • 3 minutes 2 seconds for Sample300
  • 6 minutes 11 seconds for Sample500

 

Here are a few tips to lower generation time.

 

Set “Create Default Application” to “False”

By default, CodeFluent Entities infers a “virtual application” from your model: forms and grids will be created to display and edit each of your entities,  resources to display text, screens to call methods, etc.

Therefore, if you’re not generating the UI or are not currently working on it, disabling the creation of this default application will save you a whole lot of time.

To do this:

  • In the solution explorer select your CodeFluent Entities project,
  • and either from the property grid or from the project properties panel set the “Create Default Application” property to “False”.

image

 

Generate over again and the generation process should be much faster. For example:

  • Generating Sample300 drops to 2 minutes 10 seconds: we gained 52 seconds (28.5% gain)
  • Generating Sample500 drops to 2 minutes 51 seconds: we gained 3 minutes 20 seconds (53.9% gain)

Consequently, if not working on the generated UI or simply not using it, disabling this feature will save you a lot of time Winking smile

 

Disabling Producers You Are Not Using

Frequently when building your app, you’ll be doing just a little change here and there such as modifying a validation rule which only impacts the .NET class, or a method body which only impacts a stored procedure. In such cases, if your application is pretty big, a way to gain time is to disable unnecessary producers before generating over again.

For instance, if my change in the model only impacted .NET classes, let’s just disable the SQL Server Producer, so that I’m skipping the persistence layer update:

image

This will for sure save me some time.

 

Note: another point of interest is that CodeFluent Entities projects can have different producers enabled/disabled by configurations (see project properties, Build panel).

image

This way you could have several configurations (e.g. Persistence Dev, .NET Dev, UI Dev) with just the producers you need enabled in each one of them, and then switch from one another when needed.

 

Hope this helps,

Carl Anderson

Follow

Get every new post delivered to your Inbox.

Join 700 other followers

%d bloggers like this: