Posts Tagged ‘WPF’

WPF Universal Converter

February 3, 2015 Leave a comment

When you create an application using WPF, you often have to write converters to change one value to the desired type. The .NET Framework already provides some basics converter such as BooleanToVisibilityConverter. These converters are very specifics and not configurable. For example you cannot change the visibility from Collapsed to Hidden. We do not want to spend time to write common converter so we create the UniversalConverter.

The converter is located in the CodeFluent.Runtime.dll or CodeFluent.Runtime.Client.dll. Please use the Nuget Package Manager to add this Package on your project:


Let’s see how to use it!

Basic conversion

    <windows:UniversalConverter x:Key="TypeConversionUniversalConverter" />

<CheckBox IsChecked="{Binding Converter={StaticResource TypeConversionUniversalConverter},
   Mode=OneWay}" DataContext="true"/>
<CheckBox IsChecked="{Binding Converter={StaticResource TypeConversionUniversalConverter}, 
   Mode=OneWay}" DataContext="yes"/>

UniversalConverter uses ConvertUtilities to convert the value to the desired type so string values “true” and “yes” will be converted to the Boolean value “true”.

Switch Case syntax

You can create a list of cases to fit all your needs. For instance:

<windows:UniversalConverter x:Key="BooleanToVisibilityConverter">
        <cfr:UniversalConverterCase Operator="Equal" Value="True" C
  onvertedValue="Visible" />
        <cfr:UniversalConverterCase Operator="Equal" Value="False" 
  ConvertedValue="Collapsed" />

As a C# switch you can set a default value:

<cfr:UniversalConverter x:Key="BooleanToVisibilityConverter" DefaultValue="Visible">
        <cfr:UniversalConverterCase Operator="Equal" Value="False" 
  ConvertedValue="Collapsed" />

There are currently 13 operators:

  • Equal,
  • NotEqual,
  • GreaterThan,
  • GreaterThanOrEqual,
  • LesserThan,
  • LesserThanOrEqual,
  • Between: minimum and maximum value included => [min:max[,
  • StartsWith,
  • EndsWith,
  • Contains,
  • IsType: type match exactly,
  • IsOfType: type or direved types,
  • JavaScript: Yes, you can use JavaScript to evaluate a condition!

And some options:

  • StringComparison
  • Trim
  • Nullify

Here’s a list of examples using different operators:

Check if a string contains NewLine using JavaScript

<cfr:UniversalConverter x:Key="HasMultipleLinesConverter" DefaultValue="False">
        <!--look for a CR or LF in the string string-->
        <cfr:UniversalConverterCase Value="/\r|\n/.exec(Value)!=null" 
  ConvertedValue="True" Operator="Javascript" />

Set error message background and foreground color

<cfr:UniversalConverter x:Key="ErrorTextBackgroundConverter" DefaultValue="Red">
        <cfr:UniversalConverterCase Value="" ConvertedValue="Transparent" />
<cfr:UniversalConverter x:Key="ErrorTextForegroundConverter" DefaultValue="White">
        <cfr:UniversalConverterCase Value="" ConvertedValue="Black" />

Test if a value is over 21

<cfr:UniversalConverter x:Key="IsOver21Converter" DefaultValue="false">
        <cfr:UniversalConverterCase Operator="GreaterThanOrEqual" Value="21" 
  ConvertedValue="true" Options="Convert" />

Is teenager

<cfr:UniversalConverter x:Key="IsTeenagerConverter" DefaultValue="false">
        <cfr:UniversalConverterCase Operator="Between" MinimumValue="13" 
  MaximumValue="20" ConvertedValue="true" Options="Convert" />

Compare types

<cfr:UniversalConverter x:Key="TypeConverter" DefaultValue="false">
        <cfr:UniversalConverterCase Operator="IsType" Value="System.String" 
  ConvertedValue="Type = String" />
        <cfr:UniversalConverterCase Operator="IsType" Value="System.Int32" 
  ConvertedValue="Type = int" />
        <cfr:UniversalConverterCase Operator="IsOfType" 
  Value="BaseClass, MyAssembly" ConvertedValue="Type is of type BaseClass" />

Is empty

<cfr:UniversalConverter x:Key="IsEmptyConverter" DefaultValue="Not empty">
        <cfr:UniversalConverterCase Operator="Equal" Options="Trim, Nullify" 
  ConvertedValue="Empty" />

<TextBox x:Name="TextBox"/>
<TextBlock Text="{Binding ElementName=TextBox, Path=Text, 
  Converter={StaticResource IsEmptyConverter}}" />

If you need more examples, please let us know. Our team will be happy to help you J.

Happy converting,

The R&D team

CodeFluent Entities and ComponentOne

October 6, 2014 Leave a comment

CodeFluent Entities generates code which can be used easily with many third party component providers. We already show before how to use CodeFluent Entities with Syncfusion. Today we’ll see how easy it is to work with ComponentOne (C1) WPF components!

The sample application displays a list of users and their contacts using a ComponentOne DataGrid. Additionally you can export user list to Excel.

The solution contains 4 projects:

The CodeFluent Entities model is very simple:

The email has a validation rule to ensure you can only save a user with an invalid email address to the database.

The relation between User and Contact is configured to save contacts after user. This means that when you call User.Save, associated contacts are also saved. This functionality is very useful in a master-detail view as we are creating!

Now we can create the WPF application. Here’s the main part of the XAML:

<!-- Convert blob to image -->
<design:BinaryLargeObjectValueConverter2 x:Key="BlobConverter"/>


<c1:C1DataGrid x:Name="DataGrid" ItemsSource="{Binding}" AutoGenerateColumns="False" RowDetailsVisibilityMode="VisibleWhenSelected">
    <c1:DataGridImageColumn Binding="{Binding Photo, Converter={StaticResource BlobConverter}}" Header="Photo" IsReadOnly="True" />
    <c1:DataGridTextColumn Binding="{Binding FirstName}" Header="First name" />
    <c1:DataGridTextColumn Binding="{Binding LastName}" Header="Last name"  />
    <c1:DataGridTextColumn Binding="{Binding Email}" Header="Email"  />
    <c1:DataGridBoundColumn Binding="{Binding Contacts.Count}" Header="Contacts" IsReadOnly="True" />

  <!-- Handle validation using IDataErrorInfo (this will validate the Email property) -->

      <StackPanel Orientation="Vertical">
        <TextBlock Text="Contacts" FontSize="14"/>

        <c1:C1DataGrid ItemsSource="{Binding Contacts}" AutoGenerateColumns="False" BeginningNewRow="C1DataGrid_BeginningNewRow">
            <c1:DataGridTextColumn Binding="{Binding FirstName}" Header="First name" />
            <c1:DataGridTextColumn Binding="{Binding LastName}" Header="Last name" />

<Button Grid.Row="1" HorizontalAlignment="Left" Click="ButtonExportToExcel_OnClick">Export Users to Excel</Button>
<Button Grid.Row="1" HorizontalAlignment="Right" Click="ButtonSaveAll_OnClick">Save all</Button>


When the window is opened, we load all users:

private readonly UserCollection _userCollection;

public MainWindow()
  // Load all users and bind them to the grid
  _userCollection = UserCollection.LoadAll();

  this.DataContext = _userCollection;

To save all users and their contacts, we have to call SaveAll method:

private void ButtonSaveAll_OnClick(object sender, RoutedEventArgs e)
   // Thanks to the cascade save, contacts are also saved

When a contact is added, we have to set its User property with the selected user:

private void C1DataGrid_BeginningNewRow(object sender,
DataGridBeginningNewRowEventArgs e)
  var contact = e.Item as Contact;

  if (contact == null)

  var user = DataGrid.CurrentRow.DataItem as User;

  if (user != null)
    contact.User = user;

Finally we can export user collection to Excel:

void ButtonExportToExcel_OnClick(object sender, RoutedEventArgs e)
  DataGrid.Save("export.xlsx", FileFormat.Xlsx);

That’s it. With only a few lines of code, CodeFluent Entities and ComponentOne you can create a fully functional application.

The code sample is available on our GitHub repository:

Happy componenting,

The R&D Team

Generate your application with CodeFluent Entities and Syncfusion – Part 2

February 14, 2014 2 comments

In Part 1 of this serie, we looked at building an ASP.NET Back Office Application with CodeFluent Entities.
Now, we would like to generate a WPF application using Syncfusion components that consumes the same datas.

There is nothing complicated here thanks to CodeFluent Entities.

We will describe the different steps to create a fully generated WPF application starting from a CodeFluent Entities custom template.

Create a custom producer

Using a custom producer, we will generate a “sexier” interface than the ASP.NET one as we’ve built before. This producer is based on a custom template and it uses Syncfusion’s components.

With a few simple steps the custom producer can be created:

  • Add a new Class Library project to your solution : ContactManager.SyncfusionProducer
  • Then, add the following references to the project : CodeFluent.Runtime, CodeFluent.Producers.UI, CodeFluent.Model, CodeFluent.Model.Common, CodeFluent.Producers.CodeDom
  • Create the WPFSyncfusionProducer class that inherits from the CodeFluent.Producers.UI.UIProducer

First of all, you simply need to override the two following properties

protected override string DefaultCategoryPath
        return ("SyncfusionWPF");

protected override string NamespaceUri
        return "";

Finally, you should not forget to override the Produce method to include your generation logic:

public override void Produce()

    Dictionary<string, string> context = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

    ... // (check the attached source code for more details

    foreach (string sourceDirectory in this.GetFullSourceDirectories(this.CategoryPath, false))
        BaseProducer.TransformAllFiles(this, this.FullTargetDirectory, sourceDirectory, context, new BaseProducer.TransformCallback(this.TransformFile));

The dictionary will help us to reuse some properties directly inside your templates files.

We also shipped a compiled version of this producer directly in the attached solution. Just read the Readme text file before opening the solution. Note if you try to compile the project before copying the custom producer, you’ll get compiler errors.

How to deploy a custom producer?

Once your Syncfusion producer compiled, you should ask yourself how to use it. There is nothing complicated there. Create a Custom.config file in the %appdata%\CodeFluent.Modeler.Design directory with the following content:

     <producerDescriptor  name="SyncfusionWPF" 
                          displayName="Syncfusion WPF" 
                          category="Syncfusion Producers"
                          typeName="ContactManager.SyncfusionProducer.WPFSyncfusionProducer, ContactManager.SyncfusionProducer" />

Then copy and paste the compiled producer « ContactManager.SyncfusionProducer.dll » into the CodeFluent Entities installation directory: C:\Program Files (x86)\SoftFluent\CodeFluent\Modeler.

Then, add a new producer with the following configuration:

Add new producer

What is a CodeFluent Entities Template ?

CodeFluent Entities provides a template engine which allows you to generate configuration files, documentation, extra sources, or any text files you might need. A template is simply a mixture of text blocks and control logic that can generate an output file

This is what it looks like:

Transform and Copy

The producer previously created will consume the template files to generate the final application. Obviously it includes some WPF Syncfusion components to improve the user experience.

Create your custom Template

The Syncfusion WPF template is available at the end, nevertheless the most interesting parts are described thereafter.

Here’s a quick code snippet to generate a file by entity:

[%@ template
enumerableTargetPathFunc='Path.Combine(Path.GetDirectoryName(TargetPath), entity.Name) + "View.xaml"'
inherits="CodeFluent.Producers.UI.BaseTemplate" %]

This instruction means that we are going to iterate through all the entities in our project. The name of the generated file will be “[EntityName]View.xaml” and depends of the entity name.

Inside the user control template source file, we are going to use the Syncfusion Grid component and iterate through all properties of entity to generate the right visible columns types:

<syncfusion:GridDataControl x:Name="GridFusion"


				[% foreach (ViewProperty vProp in entity.DefaultView.Properties) {
					if (vProp.UIEnabled)
Write(vProp, null, RendererTemplateSearchModes.None, RendererType.Read);


You’ll find the documentation for the CodeFluent Entities template engine by following this link.

Generate your application

Once your WPF application source code is generated, simply add Syncfusion references to your project and build it to get the following result:

Contact Manager Tiles View

Contact Manager Tiles View

Contact Manager Contact list

Contact Manager Contact list

By combining the CodeFluent Templating capabilities and the power of Syncfusion’s components together, you get a good mixture to generate functional and amazing applications. 🙂

But what happens if we modify the model (add/update/remove entities, properties, rules, etc.)? Just rebuild your project and it updates automatically your applications, your database and your Business objects Layer.

Using CodeFluent Entities, you define your business models in a centralized place; choose target platforms or technologies (including, but not limited to, data access), generate, and do it again continuously, as much as needed, without losing existing data.

Please leave feedback on how you liked this article and what we could improve. You can also find additional resources about Syncfusion here.

The source code is available on our GitHub repository.

Happy coding !

The R&D team.

Exploring the CodeFluent Runtime: The Ribbon Control

January 17, 2014 Leave a comment

Hey, unless you lived on another planet the last 7 years, you guys should know what is a Ribbon is in terms of user interface. It’s a sophisticated set of toolbars and buttons placed on several tabs that allows you to quickly find the commands to complete a task. Since the release of Microsoft Office 2007 (Word, Excel, PowerPoint), this kind of control has become greatly appreciated by developers to provide a great user experience to their applications.

Office Ribbon

Office Ribbon

Now, the free CodeFluent Runtime Client Library that we, at SoftFluent, provide, will allow us to easily integrate a similar control in your Windows Forms applications. First of all, just take a look at the following screenshot of this RibbonControl schema:


The RibbonControl consists of different tabs called RibbonTab (crazy huh?). Each tab (as ‘Home’ and ‘View’ above) can include one or several groups of controls of RibbonPanel type (as ‘Clipboard’, ‘Font’, ‘Paragraph’, and ‘Insert’ above). Each panel consists of a list of RibbonItems objects (RibbonItem is not a control, it’s just a wrapper object). Each RibbonItem can embed standard controls such as a Button or a DropDownList.

Now, I’m going to explain how to create the RibbonControl introduced above programmatically (as of today, we don’t provide a cool Visual Studio designer integration, so this is in fact the only way to use this control…)

Add a RibbonControl in a Windows form (Winforms technology) :

The first easy step is to add a RibbonControl, in the same way that you would add a button to a form. The RibbonControl inherits from the Control class:

var ribbonControl1 = new CodeFluent.Runtime.Design.RibbonControl();


Add RibbonTabs to RibbonControl:

var homeTab = new CodeFluent.Runtime.Design.RibbonTab("Home");
var viewTab = new CodeFluent.Runtime.Design.RibbonTab("View");


Add RibbonPanel to RibbonTab:

var clipBoardPanel = new CodeFluent.Runtime.Design.RibbonPanel("Clipboard");
var fontPanel = new CodeFluent.Runtime.Design.RibbonPanel("Font");
var paragraphPanel = new CodeFluent.Runtime.Design.RibbonPanel("Paragraph");
var insertPanel = new CodeFluent.Runtime.Design.RibbonPanel("Insert");


Here is the result:

Add RibbonItem to RibbonPanel:
Finally, we add some standard controls to the RibbonPanel :

var copyButton = new CodeFluent.Runtime.Design.RibbonButton("Copy");
copyButton.Mode = CodeFluent.Runtime.Design.RibbonItemMode.Icon;
copyButton.IconIndex = 0;

var pasteButton = new CodeFluent.Runtime.Design.RibbonButton("Paste");
pasteButton.Mode = CodeFluent.Runtime.Design.RibbonItemMode.Icon;

var pasteOptionDdl = new CodeFluent.Runtime.Design.RibbonDropDownList("Paste options");

pasteOptionDdl.Items.Add(new CodeFluent.Runtime.Design.RibbonDropDownItem("Paste"));
pasteOptionDdl.Items.Add(new CodeFluent.Runtime.Design.RibbonDropDownItem("Paste special"));

Just compile your code to get the desired result :


RibbonControl provides an ImageList property that can’store all the icons we need (such as ‘Copy’ / ‘Paste’ buttons here). So, for example, we can add two images to our Windows Forms project and to the image collection (ImageList) of the RibbonControl:

ribbonControl1.ImageList = new ImageList();
ribbonControl1.ImageList.ImageSize = new System.Drawing.Size(32, 32);


To assign one of these icons to RibbonItem, simply assign the RibbonItem’s IconIndex property, which corresponds to the index of an image in this list:

pasteButton.IconIndex = 1;

Note that you can also resize all images in the collection this way :

ribbonControl1.ImageList.ImageSize = new System.Drawing.Size(32, 32);

In order to handle different sizes of icons, the RibbonControl exposes a second image collection, the SmallImageList. To assign an icon of this collection, just use the SmallIconIndex property.

Convenient and easy, don’t you think ?

Add RibbonControl in WPF application

Since WPF day one, it’s possible to host Windows Forms controls in your WPF application. So, if you need to use the RibbonControl in xaml, check out this article.

There are expensive ribbon controls out on the market offering much more features than this one.  Its main advantage is it’s simple and … free. This control is provided 100% free of charge. Its license is tied to the CodeFluent Runtime Client license (which basically allows you to do anything with it…). The support is provided on a best-effort basis, so if you have any questions about this control or our products, feel free to visit the SoftFluent forum.

Happy ribboning!

The R&D team.

Generating a WPF Smart Client using the Smart Client Producer

October 22, 2012 Leave a comment


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.


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:


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


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:


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:


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:


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:


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):


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)


Thibault Nestor

CodeFluent Entities: Metro Style

June 15, 2012 Leave a comment

Visual Studio 2012 RC is now available with its user interface updates and so is CodeFluent Entities Winking smile

From now on, CodeFluent Entities includes three styles by default:

  • Class Designer Style,
  • Blend Style,
  • the new Metro Style

Here’s a screenshot of this new Metro Style in Visual Studio 2012 RC:



Same style in Visual Studio 2010:



What I really like about this new Metro Style is that it uses vector icons, making your model look a lot nicer when you zoom in closely:

Close-up using the Class Designer Style:


Close-up using the Metro Style:



From the “Solution Explorer”, doing a right-click on the “Surfaces” folder and selecting “Surface Rendering Configuration”, you can select one of the other provided styles or even create your own:



Hope you like it,

Carl Anderson

CodeFluent Entities is not an ORM

March 20, 2012 1 comment

CodeFluent Entities is a unique product integrated into Visual Studio 2008/2010/vNext which allows you 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.

For instance, adding an instance of the SQL Server Producer to your project will translate your model into a database (schemas, tables, stored procedures, views, constraints, etc.):

Adding an instance of the Business Object Model Producer will translate your model into .NET classes (C# or VB.NET) consuming the persistence layer:

Adding a WCF Producer will generate WCF services, contracts and proxies exposing your .NET classes:

Adding a WPF Smart Client Producer will generate a WPF application consuming the WCF services thanks to the generated proxy:

And that’s just an example of what you can do: you can also build ASP.NET web sites, SharePoint apps, Windows Forms apps, Silverlight apps, etc.

Your application is layered following best practices, all its business logic is in the middle-tier (the Business Object Model generated by the Business Object Model producer), and supporting a new technology gets down to adding a new producer or creating screens on the generated code.

Last but not least, you can create your own producer which translates this inferred meta-model into what you need.



Carl Anderson