Archive

Author Archive

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
{
    get
    {
        return ("SyncfusionWPF");
    }
}

protected override string NamespaceUri
{
    get
    {
        return "http://www.example.com/codefluent/producers.syncfusion/2011/1";
    }
}

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

public override void Produce()
{
    base.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:

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

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
enumerable="Producer.Project.Entities"
enumerableItemName="entity"
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"
                                        AllowEdit="False"
                                        AutoPopulateColumns="False"
                                        AutoPopulateRelations="False"
                                        ColumnSizer="Star"
                                        IsSynchronizedWithCurrentItem="True"
                                        NotifyPropertyChanges="True"
                                        ShowAddNewRow="False"
                                        ShowGroupDropArea="True"
                                        UpdateMode="PropertyChanged"
					                    PersistGroupsExpandState="True"
                                        VisualStyle="Metro"
                                        Grid.Row="1">

            <syncfusion:GridDataControl.VisibleColumns>

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

            </syncfusion:GridDataControl.VisibleColumns>
        </syncfusion:GridDataControl>

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.

Download the zipped source code here.

Happy coding !

The R&D team.

Generate your application with CodeFluent Entities and Syncfusion – Part 1

February 14, 2014 3 comments

Building an application from scratch, including business logic layer, data access layer and an amazing user interface design is a difficult ordeal. In most of cases it also means a long development process.

CodeFluent Entities allows you to generate components such as scripts, code, web services and UIs. 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 that can be combined to obtain your own application following your desired architecture, using your desired technologies.

An application generated by CodeFluent Entities uses standard components of .NET Framework. Today, we want to let you know that you use the power of Syncfusion to build your application. This set of components makes it easy to build attractive applications with incredible design.

CodeFluent Entities Syncfusion

We’ll show you how to create the application from scratch. It includes multiple user interfaces such as an ASP.NET Back Office to manage your data and a great WPF client application using Syncfusion WPF components.

CodeFluent Entities and Visual Studio makes it extremely easy to create a project with a sample model. In the Add New Project dialog box select the ContactManager Sample Model template:

Add a new ContactManager sample Model

You also need two additional projects:

  • A Class Library named ContactManager which represents the Business Object Model (BOM in the CodeFluent Entities language). Just add a Persistence empty directory.
  • An ASP.NET Empty Web Application named ContactManager.WebApplication which represents the ASP.NET Back Office :

Once projects created, let’s take a look at the ContactManager model supplied by CodeFluent Entities :

Contact Manager Model

Now that you’ve created the model, you need a way to generate database scripts, Back Office web application and the business objects using CodeFluent Entities producers.

Producers

What is a producer?

A producer uses information available from the model to generate code. CodeFluent Entities provides more than 20 producers that allow to generate the database (SQL Server, Azure, Oracle, PostgreSQL and MySQL), the Business Object Model (C# or VB.NET), web services as well as user interfaces such as a web site.

Configuring the producers

We need to use the Business Object Model (BOM) producer to generate the object-oriented layer:

  • From the project ContactManager.Model, select Add New Producer.
  • Select the Business Object Model (BOM) producer
  • Configure the Target Project : ContactManager

Then you need to configure the « SQL Server » producer in order to generate database scripts (tables, views, stored procedures, etc.). From the project ContactManager.Model, select Add New Producer:

  • Select the SQL Server producer from Persistence Layer Producers
  • Target the Persistence directory from your ContactManager project
  • Configure the Target version attribute and select the version according to your SQL Server database.
  • Define the Connection String attribute

Finally we will add an « ASP.NET Web Site » producer to generate the user interface of the website. From the ContactManager.Model project, click « Add New Producer » :

  • Select the ASP.NET Web Site V2 from Web Producers.
  • Select the technology of your site by changing a Template Category
  • Target the directory of our ASP.NET project: ContactManager.WebApplication

The application is now ready to be generated. In a single click (or press F5) just build the solution to generate your application.
Before compiling the solution, don’t forget to add a reference to the « ContactManager » project to your « ContactManager.WebApplication » project references.

Below you will find some screenshots of the generated application. No handwriting code and a full ready-to-use Back Office web application :) .

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

The generated home page

The generated home page

Clicking on an entity gets you to the entity page.

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.

Contact list

Contact list

The generated website also supports CRUD operations to create, edit and delete your data.

You’ve now created a simple Back Office ASP.NET application that uses all the generated layers. In the second part, let’s develop a WPF application with Syncfusion components that uses WCF web services.

Download the zipped source code here.

Happy coding

The R&D team.

Multi-database deployment with PowerShell and the Pivot Script Runner – Part 1

February 13, 2014 2 comments

We are working on a solution designed with CodeFluent Entities, which stores and manages data within a SQL Server database created by the SQL Server Producer.
Sometime in the past, we deployed this solution on many servers and, now, we want to keep them all up to date.
Recently, we have made some important changes and we want to deploy them on our many databases.

How to set up and automate the process of updating a range of databases while preserving their content?

Pivot Script Producer

To answer this question, we have developed a new producer called “The Pivot Script Producer”. It provides the opportunity for generating one or more XML files which are a database snapshot of the current CodeFluent Entities project model.

Pivot Runner

These files, generated by the pivot script producer, are intended to be consumed by the PivotRunner tool of the CodeFluent.Runtime.Database library.
Using a connection string, it updates the targeted database from the files we have previously sent to him.

The New SQL Server Pivot Script producer article shows that we can directly use the PivotRunner API from the library. But, even easier, we can just call one of the provided programs: CodeFluent.Runtime.Database.Client.exe or CodeFluent.Runtime.Database.Client4.exe, located in the CodeFluent Entities installation folder.

At this stage, we can very easily and quickly update one database. But we still want to apply this process on several databases!

PowerShell Script

Let’s use the PowerShell strengths ! :)

Powershell is a scripting language developed by Microsoft and default running on any Windows system since Windows Seven. With a fully object-oriented logic and a very close relationship with the .NET Framework, it has become an essential and very simple and useful tool. And that’s why Powershell is so cool!

Thus, we could easily imagine a script that takes a list of servers as first parameter, and the generated files path as the second one to select and update the targeted databases (here, only the online databases whose name starts with “PivotTest_”).

param([string[]]$Hosts, [string]$PivotFilePath)

if ($Hosts -eq $null -or [string]::IsNullOrWhiteSpace($PivotFilePath))
{
    Write-Error "Syntax: .\UpdateDatabases.ps1 -Hosts Host1[, Host2, ...] -PivotFilePath PivotFilePath"
    break
}

[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null

Write-Host "-========- Script started -========-"

$Hosts | foreach {
    $srv = new-object ('Microsoft.SqlServer.Management.Smo.Server') $_

    $online_databases = $srv.Databases | where { $_.Status -eq 1 -and $_.Name.StartsWith("PivotTest_") }
    
    if ($online_databases.Count -eq 0)
    {
        Write-Error "No database found"
        break
    }

    Write-Host "Database list:"
    $online_databases | foreach { Write-Host $_.Name }

    [string]$baseConnectionString = "$($srv.ConnectionContext.ConnectionString);database="
    $online_databases | foreach {
        & “CodeFluent.Runtime.Database.Client.exe” “runpivot” $PivotFilePath "$($baseConnectionString)$($_.Name)"
}
}

Write-Host "-========-  Script ended  -========-"

The script above shows us how easily some .NET Framework features can be used. In particular the Microsoft.SqlServer.Management.Smo namespace that provides an intuitive way of SQL Server instances manipulation.

We could just call one of the CodeFluent Runtime Database programs described above, but the idea of using directly the PivotRunner through a custom PowerShell command is much more attractive!

Indeed, Powershell gives us that opportunity. These customs commands are called “Cmdlets” and can be built under C#.NET, as we will see later in the second part of this article :)

Happy deploying

The R&D team.

Exploring the CodeFluent Runtime: Web Controls – Part 2

February 5, 2014 1 comment

In Part 1 of this series, we looked at some useful controls from the CodeFluent.Runtime.Web assembly.
On the same subject, we’ll explore in this post some other very useful controls for ASP.NET WebForms application.

The first controls are DataSource controls; They aren’t visual but very convenient as they can be bound to any DataBound controls like GridView, ListView, etc.

CountryDataSource (CodeFluent.Runtime.Web.UI.CountryDataSource) gives you a list of countries with a lot of properties, including localization information (EnglishName, NativeName, Location, Region, etc.). The type of the enumerated item is CodeFluent.Runtime.Utilities.Country. You can learn more about this type in the related article on our blog.

<cfe:CountryDataSource ID="CountryDataSource1" runat="server"/>
<asp:GridView ID="GridView2" runat="server" DataSourceID="CountryDataSource1" AllowPaging="true">

CountryDataSource

CultureDataSource (CodeFluent.Runtime.Web.UI.CultureDataSource) gives you a list of CultureInfo (System.Globalization.CultureInfo) and can be bound with any DataBoundControl (GridView, DropDownList…).

<cfe:CultureDataSource ID="CultureDataSource1" runat="server" />
<asp:GridView ID="GridView3" runat="server" DataSourceID="CultureDataSource1" AllowPaging="true">

CultureDataSource

CodeFluent Entities comes with another cool Web Control: the CultureDropDownList.

CultureDropDownList (CodeFluent.Runtime.Web.UI.WebControls.CultureDropDownList) displays automatically for you a DropDownList filled with cultures. With a single line of code, you can let the user change the UI Culture of your website.
First, add this control to your page:

<cfe:CultureDropDownList id="cultures" runat="server" CultureCookieName="culture" AutoPostBack="true" TitleMemberName="EnglishIEStyle" TextMemberName="NativeName" CultureList="en-us;fr-fr" />

The CultureList property lets you set the cultures you want to display. By default, all available cultures (on the current computer) are loaded.

Then, just add the following code in the Global.asax file.

protected void Application_AcquireRequestState(object sender, EventArgs e)
{
    CultureDropDownList.SetRequestCulture(Request, "culture"); 
}

The second parameter corresponds to the name of the cookie set in the CultureDropDownList in the page.

Because the CultureDropDownList control is set to AutoPostBack=”true”, when the user selects another culture, the website page will automatically reload with the selected culture. Of course, you need to put in place the ASP.NET globalization mechanism and provide the corresponding resources files :).

FreeForm Control
Now, another topic. Let’s imagine you have several forms to implement as pages on your site, most of them used to get simple input from your users. Let’s suppose you want to send email with the content of the forms. This can be useful for polls for example.

For this, you can use the FreeForm control (CodeFluent.Runtime.Web.UI.WebControls.FreeForm). It allows you to create an arbitrary form, add all the child controls you want to it and then add a piece of code to gather all the user input data. Here is a quick example.

We start with a simple markup:

<cfe:FreeForm ID="FF" runat="server" OnFormChanged="OnFormChanged" DecamelizeOptions="Default" >
    <ItemTemplate>
        <asp:Panel ID="Panel3" runat="server" GroupingText="Personnal Information">
            <asp:Label ID="Label1" runat="server" Text="Preferred Name:" /><br />
            <asp:TextBox ID="TextBox1" runat="server" Text='<%#Bind("PreferredName") %>' /><br />
            <asp:Label ID="Label2" runat="server" Text="City:" /><br />
            <asp:TextBox ID="TextBox3" runat="server" Text='<%#Bind("City") %>' /><br />
        </asp:Panel>
        <asp:Panel ID="Panel4" runat="server" GroupingText="Business Information">
            <asp:Label ID="Label3" runat="server" Text="Your Company:" /><br />
            <asp:TextBox ID="TextBox4" runat="server" Text='<%#Bind("YourCompany") %>' /><br />
            <asp:Label ID="Label4" runat="server" Text="Describe your primary role and function:" /><br />
            <asp:TextBox ID="TextBox5" runat="server" Text='<%#Bind("DescribeYourPrimaryRole_x0026_Function") %>' /><br />
        </asp:Panel>
        <br />
        <asp:Button ID="Button2" runat="server" Text="OK" />
    </ItemTemplate>
</cfe:FreeForm>

We have a form with 4 textboxes and their corresponding labels into 2 panels, plus a standard button to submit :

When the user submits the button, the whole input data will be transformed into a dictionary instance automatically. Each control will provide a dictionary entry in that instance. Notice that all the Text attributes of the textboxes have a standard ASP.NET bind token attached. That token will become the entry field key, and the entry value will be the data entered by the user (whatever the type of this data and the type of the control). To get this dictionary you just need to attach to the FormChanged event and read the Values property of the FormChangedEventArgs parameter, like this:

<script runat="server">
    protected void OnFormChanged(object sender, FormChangedEventArgs e)
    {
        StringBuilder sb = new StringBuilder();

        foreach (DictionaryEntry de in e.Values)
        {
            sb.AppendLine(de.Key + "=" + de.Value + "<br/>");
        }
        
        // NOTE: instead, send email here with the content of the StringBuilder
        litResult.Text = sb.ToString();
    }
</script>     

You may have noticed that we have defined the field names using camel-case and also some weird hexadecimal notation. The FreeForm control has the ability to “decamelize” these keys and unescape the Unicode characters represented by their hexadecimal values. This trick allows us to use anything for key names (although the Bind syntax is much more restrictive). You can define several options in the DecamelizeOption attribute (None, ForceFirstUpper, ForceRestLower, UnescapeUnicode, UnescapeHexadecimal, ReplaceSpacesByUnderscore, ReplaceSpacesByMinus, ReplaceSpacesByDot, KeepFirstUnderscores, DontDecamelizeNumbers, KeepFormattingIndices).

So, this simple example gives you the following result:

Of course, you will hopefully implement something more useful in your project :) You can also imagine having a form generator for power-users, letting them design simple forms and process the Key/Value Dictionary generated by the FreeForm control in a pretty much automatic way.

NumericTextBox Control
Do you need a numeric-only textbox input?. CodeFluent.Runtime.Web has a solution for you: the NumericTextBox control.

The NumericTextBox control (CodeFluent.Runtime.Web.UI.WebControls.NumericTextBox) prevents user from entering non-numeric characters. You can define the value type with the TargetTypeName attribute, define the MaximumNumbers, MaximumIntegerNumbers, MaximumDecimalNumbers or the Negative or Positive Sign. Note this control can be used inside a FreeForm control we say previously.

<cfe:NumericTextBox ID="NumericTextBox1" runat="server" Value='<%# Bind("NumberOfEmployees") %>' TargetTypeName="System.Int32" />

There is also associated DataControlField, NumericTextField CodeFluent.Runtime.Web.UI.WebControls.NumericTextField) fields controls that you can use in GridView, DetailsView, etc.

<cfe:NumericTextField DataField="Age" HeaderText="Age" TargetTypeName="System.Int32"/>

Captcha Control
The Captcha control (CodeFluent.Runtime.Web.UI.WebControls.CaptchaControl) displays an image with some simple text inside, but supposedly quite difficult to read for machines. You can define the image size, the complexity of the produced image, and a timeout duration. Notice that the image is generated by the BinaryLargeObjectHttpHandler of CodeFluent Entities (Learn more about Blob here).

The Captcha control comes with its validator, the CaptchaValidator control (CodeFluent.Runtime.Web.UI.WebControls.CaptchaValidator). As any validator, you just need to declare the ControlToValidate and the CaptchaControlID associated.

In this example, we just display a message if the text entered corresponds to what was generated by the Captcha control.

<cfe:CaptchaControl ID="CaptchaControl1" runat="server" Width="200px" Height="50px" Expiration="120"
    Options="FontWarpFactorMedium, BackgroundNoiseLevelHigh,LineNoiseLevelHigh" />
<br />
Please enter the code or press F5 to refresh the browser
<br />
<cfe:CaptchaValidator ID="CaptchaValidator1" runat="server" ControlToValidate="Verify" CaptchaControlID="CaptchaControl1"
    SetFocusOnError="True" ErrorMessage="The code doesn’t match or there was a timeout" ForeColor="Red" />
<br />
<asp:TextBox ID="Verify" runat="server" EnableViewState="False" AutoCompleteType="None" />
<asp:Button ID="btValidate" runat="server" Text="Validate" OnClick="btValidate_Click" /><br />
<asp:Label ID="lblResult" runat="server" Text="You enter the correct text! Thank you for validating." Visible="false" ForeColor="Green"/>

In the button Click event, call Page.IsValid to validate the captcha:

<script runat="server">
    protected void btValidate_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            lblResult.Visible = true;
        }
        else
        {
            lblResult.Visible = false;
        }
    }
</script> 

Have a look at the Captcha image here:

Captcha

As you’ve seen in this serie, CodeFluent.Runtime.Web can be very useful to us, web developers who are tired to write a lot of code-behind to do simple actions. With these controls you just need to drag and drop them on your page, save and enjoy.

These controls are located in the CodeFluent.Runtime.Web assembly, part of the CodeFluent Entities product ! Try them!

Happy controling!

The R&D team.

Multi-database architecture with CodeFluent Entities

January 29, 2014 1 comment

In this article, we’ll see how to use multiple stores in your CodeFluent Entities application. In a previous post, we explained that the Modeler doesn’t provide a “Store Name” property in the producer’s configuration property grid. It’s now fully supported in the product so you don’t need to modify your XML parts by hand.

However, before we go any further, let’s bring some theory. The CodeFluent Entities “store” concept can be seen as a virtual storage unit and is mainly used by the persistence layer producers. Your CodeFluent Entities model contains by default one store which is always visible in your model, in the Visual Studio’s solution explorer tree view:

If you need to add a new Store, right-click on the “Stores” node and select “Add new Store”. Simply choose a name and your application now contains two stores: CarRental and CarRentalReferential.

Okay, great… but why would I want to do this?

When you develop an application, you may feel the need to dispatch your tables (inferred from model entities) in more than one database. For example, I want to create the Customer table in the CRM Database, and the Product table in the Master Data Database. Well, this is exactly why the store concept exists. Another example is shown here in this diagram:

Multidatabase Architecture with CodeFluent Entities

Now, how to configure the “City”, “Address” and “Country” entities so their inferred tables will be generated to the CarRental database? It’s very easy : just select each of them, open the Properties window (F4), select the property grid Advanced tab (pointed by the red arrow below), and specify the target store like this:

Then you can define two persistence producers in your project and assign each of them a specific store:

Now don’t forget to configure your store and set it a specific connectionString. By building your model, CodeFluent Entities will generate the code corresponding to each store. The right things in the right places ;) !

Store SQL result

To conclude, I’d like to point out that, by design and by default, you can’t create model-level relationships between entities from different stores. Databases could be located in different servers or in different storage systems. But if you know what you’re doing, and still need this, you can change this default behavior by setting the allowCrossStoreRelations attribute on your project.

Happy Storing!

Antoine Diekmann

Exploring the CodeFluent Runtime: Web Controls – Part 1

January 28, 2014 1 comment

Today, on the series “Exploring the CodeFluent Runtime” we’re going to explore the ASP.Net Web Controls inside the CodeFluent.Runtime.Web namespace. This is all provided as part of CodeFluent Entities.

In the CodeFluent.Runtime.Web assembly, you’ll find several controls usable in ASP.Net WebForms applications. The first we’ll see are controls used to render UI relatively to the data (bindings).

BooleanControl (CodeFluent.Runtime.Web.UI.WebControls.BooleanControl) displays what’s defined in FalseTemplate or TrueTemplate according to a boolean value.

<cfe:BooleanControl ID="BooleanControl1" runat='server' Value='<%# Eval("MyBooleanValue") %>' AutoBind="true">
    <TrueTemplate>
        This template will be displayed if Value is evaluated as "true"
    </TrueTemplate>
    <FalseTemplate>
        This template will be displayed if Value is evaluated as "false"
    </FalseTemplate>
</cfe:BooleanControl>

CompareControl (CodeFluent.Runtime.Web.UI.WebControls.CompareControl) displays FalseTemplate or TrueTemplate according to what’s defined by the ValueToCompare attribute and an Operator (Equal, NotEqual,
GreaterThan, GreaterThanEqual, LessThan, LessThanEqual, DataTypeCheck). For the DataTypeCheck operator, the ValueToCompare will be the full name of the type to check.

<cfe:CompareControl ID="CompareControl1" runat='server' Value='<%# Eval("MyValueToCompare") %>' Operator="GreaterThan" ValueToCompare="0">
    <TrueTemplate>
        Value is greater than 0
    </TrueTemplate>
    <FalseTemplate>
        Value is less than or equal to 0
    </FalseTemplate>
</cfe:CompareControl>
 
<cfe:CompareControl ID="CompareControl2" runat='server' Value='<%# Eval("MyValueToCompare") %>' Operator="DataTypeCheck" ValueToCompare="System.Int32">
    <TrueTemplate>
        Value is a System.Int32
    </TrueTemplate>
    <FalseTemplate>
        Value is not a System.Int32
    </FalseTemplate>
</cfe:CompareControl>

MultiCompareControl (CodeFluent.Runtime.Web.UI.WebControls.MultiCompareControl) is similar to the CompareControl but is more like a switch.

<cfe:MultiCompareControl ID="MultiCompareControl1" runat="server" Value='<%#Eval("MyValueToMultiCompare") %>'>               
    <case ValueToCompare="10" Operator="GreaterThan">
            Value is greater than 10
    </case>
    <case ValueToCompare="0">
    Value is equal to 0
    </case>
    <default>
    Value is not equal to 0 and is less than or equal to 10
    </default>
</cfe:MultiCompareControl>

ExistsControl (CodeFluent.Runtime.Web.UI.WebControls.ExistsControl) displays FalseTemplate or TrueTemplate depending on a given value. The value is tested against “null”, “DBNull”, or an empty string (possibly trimmed).

<cfe:ExistsControl ID="ExistsControl1" runat='server' Value='<%# Eval("Email") %>' Trim="true">
    <TrueTemplate>
        This template is displayed only if Value is not null or empty 
    </TrueTemplate>
    <FalseTemplate>
        This template is displayed when Value is null
    </FalseTemplate>
</cfe:ExistsControl>

When you work with enumerations into your Model, you want to be able to display and edit them easily into your forms or GridView. We have a solution for you! Let me introduce the Enum Controls.

EnumCheckBoxList (CodeFluent.Runtime.Web.UI.WebControls.EnumCheckBoxList) derives from the standard CheckBoxList control but is automatically filled with the fields of the enumeration type you define EnumTypeName parameter. Note this also supports multi-valued enumerations (with a [Flags] custom attribute).

EnumRadioButtonList (CodeFluent.Runtime.Web.UI.WebControls.EnumRadioButtonList) derives from the standard RadioButtonList control. As the EnumCheckBox, you only need to define the EnumTypeName attribute

EnumDropDownList (CodeFluent.Runtime.Web.UI.WebControls.EnumDropDownList) derives from the standard DropDownList and works the same way.

Another control that allows you to quickly bind your data is the BoolControl (CodeFluent.Runtime.Web.UI.WebControls.BoolControl). The BoolControl is a visual custom control that displays a System.Boolean or Nullable<System.Boolean> bound value. Depending whether the value is nullable or not, it can display a True/False or True/False/Undefined visual. It can use a CheckBox, DropDownList, horizontal button list, ListBox or horizontal or vertical radio button list to display these 2 or 3 items. It also supports read-only rendering and custom texts, interesting for localization purposes.

Is Customer:

<cfe:BoolControl ID="BoolControl1" runat="server" Value='<%# Bind("IsCustomer") %>' TrueText="Yes" FalseText="No" UnspecifiedText="Undefined" BoolControlType="HorizontalRadioButtonList" />

Contact Method:

<cfe:EnumCheckBoxList ID="EnumCheckBoxList1" runat="server" Value='<%# Bind("MethodToContact") %>' EnumTypeName="BlogCFE.ContactManager.ContactMethod" />
Origin (RadioButton):
<cfe:EnumRadioButtonList ID="EnumRadioButtonList1" runat="server" Value='<%# Bind("Origin") %>' EnumTypeName="BlogCFE.ContactManager.ContactOrigin" />
Origin (DropDown):
<cfe:EnumDropDownList ID="EnumDropDownList1" runat="server" Value='<%# Bind("Origin") %>' EnumTypeName="BlogCFE.ContactManager.ContactOrigin" />           

Here is the result:

For each of these controls, an associated DataControlField exists so you can use them in GridView, DetailsView, etc.

<cfe:BoolField DataField="IsCustomer" HeaderText="Is Customer" TrueText="Yes" FalseText="No" BoolControlType="DropDownList" />
<cfe:EnumCheckBoxListField DataValueField="MethodToContact" HeaderText="Contact method" EnumTypeName="BlogCFE.ContactManager.ContactMethod" />
<cfe:EnumRadioButtonListField DataValueField="Origin" HeaderText="Origin (RadioButton)" EnumTypeName="BlogCFE.ContactManager.ContactOrigin" />
<cfe:EnumDropDownListField DataValueField="Origin" HeaderText="Origin (DropDown)" EnumTypeName="BlogCFE.ContactManager.ContactOrigin" />        

the result in a grid view:

List of Contacts

As you’ve seen, these controls can avoid you to write a lot of code focusing more on a declarative way of programming.

In the next article, we’ll introduce the DataSources controls and another couple of cool utilities.

The R&D team.

Exploring the CodeFluent Runtime: Country utilities

January 21, 2014 1 comment

The CodeFluent.Runtime.Utilities.Country class is a cool tool that provides information about countries, regions, geographic locations and currencies.

Below is a figure showing a WPF application with a DataGrid that contains a list of countries with the information this class provides: locale identifier, region, english name, native name (in the corresponding language), currencies, etc.)

Country

XAML :

<Grid>
    <DataGrid x:Name="MyDataGrid" />
</Grid>

C# :

MyDataGrid.ItemsSource = CodeFluent.Runtime.Utilities.Country.AllCountries;

By running the code above, you’ll get a list of countries as a data source for your WPF DataGrid.

The Country object also exposes some useful methods such as:

GetCountry : find a country by its ISO-3166 two-letter code

CodeFluent.Runtime.Utilities.Country.GetCountry("AL")

It also supports principal subdivisions (e.g., provinces or states) of all countries coded in ISO 3166 so you can get locations and not only countries:

// *private joke* Carl, this one's for you !
var guadeloupe = CodeFluent.Runtime.Utilities.Country.GetCountry("GL");

// Get all locations installed on your system.
var allLocations = CodeFluent.Runtime.Utilities.Country.AllLocations;

GetCurrencyCountries : find countries for a given ISO currency symbol

var euroCountries = CodeFluent.Runtime.Utilities.Country.GetCurrencyCountries("EUR")

So here is the same grid with the list of countries that use EURO currency:

Country

Before leaving this topic, I suggest you have also have a look at the CultureComboBox control available in the CodeFluent.Runtime.Design namespace. It provides an associated Winforms ComboBox specialized for displaying countries.

The CodeFluent Runtime is  available with the full CodeFluent Entities product and with the CodeFluent Runtime Client 100% free assembly (available directly from Nuget).

Happy countrying!

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:

RibbonControl01

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();

this.Controls.Add(ribbonControl1);

Add RibbonTabs to RibbonControl:

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

ribbonControl1.Tabs.Add(homeTab);
ribbonControl1.Tabs.Add(viewTab);

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");

homeTab.Panels.Add(clipBoardPanel);
homeTab.Panels.Add(fontPanel);
homeTab.Panels.Add(paragraphPanel);
homeTab.Panels.Add(insertPanel);

Here is the result:
RibbonControl03

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"));
clipBoardPanel.Items.Add(copyButton);
clipBoardPanel.Items.Add(pasteButton);
clipBoardPanel.Items.Add(pasteOptionDdl);

Just compile your code to get the desired result :

RibbonControl03

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

ribbonControl1.ImageList.Images.Add(Image.FromFile(@"Images\copyButtonIcon.png"));
ribbonControl1.ImageList.Images.Add(Image.FromFile(@"Images\pasteButtonIcon.png"));

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.

Exploring the CodeFluent Runtime: The Template Engine

December 26, 2013 Leave a comment

As you probably know, we released a few year ago the CodeFluent Runtime as a free Nuget Package named CodeFluentRuntimeClient. This is a set of utilities which is usable across all types of .NET applications (WPF, WinForms, ASP.NET, console, Windows service, etc.) and aims to ease the developer’s life.

Today, I’d like to introduce you, as part of the Exploring the CodeFluent Runtime series, an easy-to-use class to generate documents from a template source file.
You should ask yourself what is a template in term of software development. It’s simply a mixture of text blocks and control logic that can generate an output file. With our template engine, the control logic is written in JavaScript as fragments of program code. By default, the engine is based on the fast IE9+ “chakra” JavaScript engine developed by Microsoft for its Internet Explorer web browser.

Before we go any further it’s important to briefly describe the two following classes from the CodeFluent.Runtime.TemplateEngine namespace:

Template: Defines properties and characteristics of an ActiveX Scripting template and provides a set of methods to load and process a template file.

ParsedTemplate: In-memory and compiled representation of your template file (JavaScript).

The following diagram shows how the template engine internally works:

CodeFluentRuntimeClient Template

If you want to understand how to parse and execute JavaScript by C#, just have a look to this StackOverflow discussion. You’ll find how to interop with the JavaScript “IE9+ Chakra” JavaScript engine.

The easiest way to understand how to use the template engine is by way of an example. The first thing we have to do is create our template file.

Consider the following Rtf input file:

RTF Input file

Rtf Input file

You can download the template file here.

The “<% %>” tag represents the JavaScript code blocks. Let’s use the Template engine in order to process the template described above:

// The ComVisible indicates that the managed type is visible to COM.
[ComVisible(true)]
public class OrderLine
{
    public string ProductName { get; set; }
    public decimal UnitPrice { get; set; }
    public int Quantity { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        // initialize the argument dictionary.
        IDictionary<string, object> arguments = new Dictionary<string, object>();
        arguments.Add("orderLine1", new OrderLine() { ProductName = "Product A", Quantity = 5, UnitPrice = 12 });
        arguments.Add("orderLine2", new OrderLine() { ProductName = "Product B", Quantity = 10, UnitPrice = 30 });
        arguments.Add("orderLine3", new OrderLine() { ProductName = "Product C", Quantity = 4, UnitPrice = 40 });

        CodeFluent.Runtime.TemplateEngine.Template template = new CodeFluent.Runtime.TemplateEngine.Template();

        // Load the source template with the argument initialized above.
        template.Load("PurchaseOrder_Template.rtf", arguments.Keys.ToArray());

        using (StreamWriter writer = new StreamWriter(@"PurchaseOrder.rtf"))
        {
            // Run the template using the CodeFluent Runtime Template engine.
            template.Run(writer, arguments);
        }
    }
}

For running this code you have just to reference the CodeFluent Runtime Client Library and when executing it you’ll get the generated output file :

Rtf Output file

Rtf Output file

It’s good to know that the template engine is fully extendable. It would be helpful if you want to add your own keywords or business rules. For this purpose, you should inherit from the Template and/or ParsedTemplate objects.

On the same topic and through the CodeFluent Entities product, we are shipping a Template producer which is an engine that allow developers to generate text files from template containing C# code blocks.

Happy templating,

Antoine Diekmann

[Pet Shop Reloaded] The End

November 24, 2013 Leave a comment

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

Richer Modeler

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

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

Performance and readability

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

linq-to-entities

linq-to-entities

Using CFQL

Using CFQL

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

Multipart model

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

No Mapping

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

Continuous generation

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

Write less code

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

the less code we write…

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

We haven’t seen everything

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

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

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

Code metrics

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

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

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

Entity Framework – Code Metrics:

Entity Framework Code Metrics

Entity Framework Code Metrics

CodeFluent Entities – Code Metrics:

CodeFluent Entities Code Metrics

CodeFluent Entities Code Metrics

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

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

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

Finally

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

Regards,

The SoftFluent team

Follow

Get every new post delivered to your Inbox.

Join 41 other followers