Archive

Posts Tagged ‘model-driven’

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

CodeFluent Entities Summer Contest

August 7, 2012 Leave a comment

 

You are a developer? A blogger? If so, you may have chance to win one of the packages given away by SoftFluent!

So what’s the catch?

The only thing you have to do is to share your opinion through an article on your blog or on a public platform.

What an easy way to win some money!

The deadline for the contest is the 31st of August. So why are you still reading rather than clicking the following link to get more information!

http://www.softfluent.com/community-support/codefluent-entities/summer-2012-blogger-contest

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

CodeFluent Entities: Basics, meta-model and aspects

July 26, 2012 Leave a comment

CodeFluent Entities is a product integrated into Visual Studio 2008/2010/2012 which allows developers to generate components such as scripts (e.g. T-SQL, PL/SQL), code (e.g. C#, VB), web services(e.g. WCF, ASMX) and UIs (e.g. ASP.NET, SharePoint, WPF).

The code generation process is model-first and continuous: from your declarative model, a meta-model will be inferred which code generators will then translate into code. Over 20 code generators (a.k.a. “producers”) are provided “out of the box” and can be combined to create your own application following your desired architecture, using your desired technologies.

cfe-visual

figure 1 

Figure 1 is in fact a little too simple: as mentioned earlier, producers don’t translate your model into code right away, instead a meta-model will be inferred first. This meta-model consists of of a ‘virtual’ persistence layer, a ‘virtual’ business object model and a ‘virtual’ user interface. By ‘virtual’ I mean that it’s all in-memory and that’s not actual code yet.

Schema

figure 2

You can actually view those virtual bits using the Meta-Model Explorer (CodeFluent.View.exe) or by clicking on the “View Inferred Model” button of your project tab in Visual Studio:

image

figure 3

Producers will then translate those virtual bits into actual scripts, code, web services and UIs.

This meta-model is the key. Thanks to it, before anything gets generated, CodeFluent Entities can ensure that your application is consistent and that it will all compile.

Furthermore, CodeFluent Entities provides what we call “CodeFluent Aspects” (formerly known as “CodeFluent Patterns”) which allow you to interact with this inferred meta-model and dynamically change it.

A set of built-in aspects are provided out-of-the-box but you can also create your own aspects. For instance, one could create an aspect that automatically adds tracking properties on all entities marked as “trackable”. It’s all done at generation time and can turn out to be very handy when working on big models and/or to externalize a feature that you have to implement often from one project to another.

More on this subject in a forthcoming post!

 

Cheers,

Carl Anderson

CodeFluent Entities: new ASP.NET Web Site Web Forms Template sneak peek

July 25, 2012 2 comments

A brand new ASP.NET Web Site Producer (v2) is shipped in alpha in the latest build available (666 and upper).

As mentioned in our Web Platform Roadmap post, this new producer will be shipped with three templates:

Here’s a sneak peek of what gets generated when using this new template (codename: “Airport”) Smile

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

image

 

Clicking on an entity gets you to the entity page:

image

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 in fact to business methods provided by the entity:

image

 

Unlike the Ajax/JSON template which consumes WCF JSON services, the ASP.NET Web Forms template is built directly on top of your generated .NET Domain Model, skipping this service layer. Yet, the generated .NET Domain Model (a.k.a. .NET Business Object Model) is not specific to ASP.NET and the exact same object model can be used from any other .NET technology such as SharePoint, WinForms, Console applications, services, etc.

 

Any feedback? Share them on this blog, on our forums or on our Facebook page!

Cheers,

Carl Anderson

CodeFluent Entities: How to reuse existing stored procedures

July 13, 2012 Leave a comment

In this post I’ll start from the NerdDinner application, which you can get from CodePlex (http://nerddinner.codeplex.com/). In the NerdDinner database I added the following sample stored procedure named “sp_SelectDinnersByCountry” that takes a county name as a parameter:

CREATE PROCEDURE [dbo].[sp_SelectDinnersByCountry] 
(
     @Country [nvarchar] (50)
)
AS
SET NOCOUNT ON
SELECT DISTINCT * 
    FROM Dinners 
    WHERE Country = @Country
RETURN

From there, I then imported the NerdDinner database into a brand new CodeFluent Entities model (as detailed on CodeFluent Entities’ Get Started page) and now what I want to do is to reuse my existing stored procedure, instead of creating a new one using CFQL.

Select the “Dinner” entity and add the following new method:

image

Now that our method is created we need to specify:

  • it’s name in the persistence layer as my stored procedure has a different name than the one in my model,

image

 

  • it’s return type (by default raw methods are void),

image

 

  • mark my method so it’s not generated by the SQL Server Producer,

image

 

As a consequence the Business Object Model Producer will generate a SelectByCountry method, which calls the sp_SelectDinnersByCountry stored procedure, and returns a DataSet, so now in my app I can do something like this:

System.Data.DataSet ds = Dinner.SelectByCountry("FRANCE");

 

Hope this helps,

Carl

CodeFluent Entities: Saving import configurations

July 11, 2012 1 comment

Using CodeFluent Entities you can import existing databases (Access, SQL Server, SQL Server CE, Oracle, MySQL, PostgreSQL) or existing models (Enterprise Architect, XMI, ADO.NET Entity Framework) into CodeFluent Entities models. The idea behind this import feature is that you’ll import your existing line of business once (see the Importers category for more info on this) and then drive your developments from your CodeFluent Entities model, as CodeFluent Entities is a model-first tool.

Recently we added the possibility to save and load import configurations so you can keep your settings and work on your import over and over again until the model imported tastes good.

For instance, let’s create a brand new blank model that we’ll name Northwind.Model and which will be a CodeFluent Entities version of Microsoft’s sample Access 2010 database Northwind.

image

Right-click and on your project and select “Import an Existing Database or Model…”, select the Access importer, configure it, hit next, next, next and you should get to this screen:

01-MyImportConfig

By saving it, we’ll be able to run this import with the exact same configuration without having to configure everything over again.

For instance, by importing the Northwind sample database for Access 2010 keeping the default settings, we get a String table which I don’t want in my .NET application.

Let’s delete all my entities in my model and import over again using the same import configuration (MyImportConfig.cfi):

02-MyImportConfig

Once this is done, let’s customize our import settings and specify in the “Table Full Name Filters” the “String” table name that we want to skip:

03-MyImportConfig

Let’s save our new config and import over again, tadaaaa, no more String entity:

image

Cheers,

Carl Anderson

CodeFluent Entities: Multiple surfaces, multiple parts

June 20, 2012 Leave a comment

As discussed in the “What is a CodeFluent Entities model?” post, CodeFluent Entities projects contain:

  • surfaces, which are graphic views of your model,
  • XML parts, which are storage units.

By default, when creating a new project, you have a single surface named “Default” and a single model part named <DefaultNamespace>.cfp which will both contain all your entities:

image

 

In the screenshot above you can tell that I have several namespaces, let’s say I want to chunk my model up, so I have one surface per namespace in addition to my default surface. Select the Surfaces folder, and create a new one, you’ll see that a dialog pops-up letting you choose which concepts you want to import:

image

 

Here’s the result after repeating this logic for each of my namespaces, isn’t it a lot more readable?!

image

 

Yet, all entities are still stored in the same, unique, model part “AdventureWorksReloaded.cfp”, making it hard to work collaboratively (doing edits on any of my surfaces would automatically check-out the AdventureWorksReloaded part as all entities are stored in this one).

This again can be changed: select a namespace and from the property grid, switch the default part to a new part.

image

image

 

If I do this for all my namespaces, in the end my main part will just contain project level settings, producers and import other parts:

image

 

Organizing my CodeFluent Entities project this way, each developer can be in charge of a functional namespace and work in his scope without stepping on someone else’s shoes.

Finally, you could even go one step further by enabling the “Create One Part Per Type” option which creates one part per entity or enumeration:

image

 

Not only is this a very handy option when collaborating on the same source-controlled model, but you can also get great performances on big models as it avoids to have one big XML file containing all your project.

 

Hope this helps,

Carl Anderson

Designing Databases with CodeFluent Entities: Inheritance

April 20, 2012 Leave a comment

CodeFluent Entities tries to reduce the impedance mismatch between relational worlds and object-oriented worlds as much as possible and a good example of this I guess is how CodeFluent Entities supports inheritance across layers of your application.

Using CodeFluent Entities, an entity hierarchy defined in your model will be translated following the Table-Per-Type pattern in the persistence layer, when, in the generated business object model, this will be a regular class inheritance.

For instance, say we have the following hierarchy:

Here’s the result in the database:

Furthermore, data access methods will be modified accordingly to load the objects as expected in .NET. For instance, here’s the “Load” stored procedure that is automatically generated for the DiscountProduct entity:

CREATE PROCEDURE [dbo].[DiscountProduct_Load]
(
@Id [uniqueidentifier]
)
AS
SET NOCOUNT ON
SELECT DISTINCT [DiscountProduct].*, Product].* 
  FROM [DiscountProduct]
   INNER JOIN [Product] ON ([DiscountProduct].[Product_Id] = [Product].[Product_Id])
  WHERE ([DiscountProduct].[Product_Id] = @Id)

RETURN

Cheers,

Carl Anderson

Designing Databases with CodeFluent Entities: Names

April 19, 2012 Leave a comment

As explained in previous posts, CodeFluent Entities is way more that an ORM: you’re not just mapping classes to database objects, instead you’re creating a model which will be translated into stuff. Therefore if you add persistence producers such as SQL Server, Oracle Database or SQL Azure a database will be created or updated from it (see continuous generation from more info).

Creating a database implies naming a lot of stuff: tables, columns, constraints, stored procedures, etc., so I thought I’d give you a little details on how it works and how you can control this to create your own database.

First, CodeFluent Entities deduces names automatically from your model:

  • Table names are identical to entity names,
  • Columns are named “<EntityName>_<PropertyName>”,
  • Procedures are named “<EntityName>_<MethodName>”

Users can override this logic by:

  • defining a “Persistence Name” in the Property Grid on the object you want to change (entity, property, method, view, ..)
  • setting a “Persistence Property Name Format” at the project level to customize all property names of your project (e.g. replace the default “{0}_{1}” by “{1}” to remove the entity name prefix from all column names),
  • changing the naming convention

In practice a naming convention is a class implementing a naming convention rule which CodeFluent Entities will use to name persistence objects. Consequently changing the naming convention used will change the way all objects are named.

Several naming conventions are provided out-of-the-box and they all derive from one another, hence they benefit from the features of their parents. The hierarchy is as follows:

  • BaseNamingConvention (default)
    • FormatNamingConvention: modifies the name format of tables, columns, procedures, parameters, constraints.
      • LowerCaseNamingConvention: sets all database object names in lower case.
      • UpperCaseNamingConvention: sets all database object names in upper case.
      • DecamelizeNamingConvention: decamelizes all names (FirstName –> First_Name)
        • DecamelizeLowerCaseNamingConvention: all in lower case and decamelized (FirstName –> first_name)
        • DecamelizeUpperCaseNamingConvention: all in upper case and decamelized (FirstName –> FIRST_NAME)

Furthermore you can create your own custom naming convention by implementing the INamingConvention or by deriving from existing ones.

 

Cheers,

Carl Anderson

Follow

Get every new post delivered to your Inbox.

Join 44 other followers