Archive

Archive for April, 2013

Using the Cache Sub-Producer

April 24, 2013 Leave a comment

 
CodeFluent Entities provides an integrated cache system for the Business Object Model (BOM) layer.  The Object Model Cache (OMC) is not enabled by default. To add the cache feature to your BOM you need to first add a Cache sub producer.
 

The Cache Sub-Producer

The Cache Sub-Producer


 
If you set the “Is Default Enable” attribute to “True” the cache feature will be enabled for all the entities in your model. You can also decide to enable or not the cache feature by entity or by method.
 
Enable Cache on an Entity

Enable Cache on an Entity


 
As you can see in the image above, you can independently specify whether you want to enable the cache feature for Collections or not by changing the value of the “Is Collection Enabled” attribute.
 
If you enable the cache feature, when calling a “LoadXXX” method (ex. Load, LoadById…) on your entity will make that a cache verification is performed before trying to load the data from the data source (SQL server for example).
 
If you want to bypass the cache you can call the “NoCacheLoadXXX” method (ex. NoCacheLoad, NoCacheLoadById…). When saving or deleting an instance of an entity, the cache is cleared (for that entity) and you can clear manually the cache calling the “CacheClear” method on an entity (public static method).
 
You may considerate some points when using a Cache system:

  • Complexity will be added to your application.
  • Unexpected behaviors may appear if not using it correctly.
  • The Object Model Cache provided by default is an in-memory cache, so it cannot be shared between servers.
  • It is not interesting to use a Cache system if the cached data changes too often. It’s best to cache immutable or almost immutable data.

 
An example scenario when the Object Model Cache feature could be useful may be when storing “referential” data on a data base or data that does not change too often.
 
CodeFluent entities provides three types of Cache implementations:

  • Simple Cache Manager, based on the ASP .NET cache (that can be used outside of ASP.NET)  (CodeFluent.Runtime.Caching.SimpleCacheManager, CodeFluent.Runtime).
  • Simple Localized Cache Manager, a sub-class of the Simple Cache Manager that can manage localized keys (CodeFluent.Runtime.Caching.LocaleCacheManager, CodeFluent.Runtime)
  • Enterprise Library Cache Management, you must install the Enterprise Library in order to use it (CodeFluent.Runtime.Caching.EnterpriseLibraryCacheManager, CodeFluent.Runtime).

 
You can specify the type of cache you want to use on the “Runtime Cache Type Name” attribute (the full type name). You can use a different cache systems by scope (entity, method).
 

Runtime Cache Type Name

Runtime Cache Type Name


 

You can use a different or custom type of cache not provided by CodeFluent Entities, you only need to implement the CodeFluent.Runtime.Caching.ICacheManager interface.

 

Finally, you can disable the cache feature by configuration (only for the Simple Cache Manager and the Simple Localized Cache Manager), for a testing or development environment for example. You only need to add the following code to your app.config or web.config file:
 

<appSettings>
   <add key="CodeFluent.Runtime.Caching.SimpleCacheManager.Enabled" value="false"/>
</appSettings>

 
 

Regards,
 
Pablo Fernandez Duran
 
 

Remove the current date and time to generated files

April 22, 2013 Leave a comment

 
 
CodeFluent Entities adds some information to generated files every time a code production is run.
 
This information contains general information (for all producers) and specific information (for each producer):
 

  • The CodeFluent Entities Build version.
  • The current date and time.
  • The Runtime version.
  • The Target version.
  • The Culture.
  • The Encoding.
  • – …

 

Generation information

Generation information


 
You might want to avoid CodeFluent Entities to add some of this information to generated code.
 
For example, each time a code production is made almost all generated files will have a new “generation date” even if the generated code is the same.
 
When using a source control system you will need to checkin/commit every single file even if  only the generation date has changed. This can lead to conflicts and unnecessary merges.

 

File Diff

File Diff

 

Well, CodeFluent Entities provides an option to remove the “generation date and time” when running producers.  
This options is found in the “advanced properties tab” at the project level  (right click on the CodeFluent Entities project > Properties).
  

Set the defaultProducerProductionFlag flag to RemoveDiffs to avoid having the “date and time” on generated files.

  

Default Producer Production Flags

Default Producer Production Flags

  

Since the CodeFluent Entities build 702 (march 2013) the RemoveDiffs production flag option now also removes the Runtime Version value added to generated files.

   

Regards,

Pablo Fernandez Duran

Using the LINQ to SQL Sub-Producer

April 17, 2013 Leave a comment

 
CodeFluent Entities gives you the possibility to make your generated Business Object Model (BOM) compatible with the LINQ to SQL data access infrastructure.
 
CodeFluent Entities ships a LINQ to SQL producer, that is in fact a Sub-Producer of the Business Object Model (BOM) Producer.
 
Let’s start by setting a model to work with.
 
For this post I will create a very simple model. A “Person” entity who has zero or more “Pets” of a given kind.
 

Pet management model

Pet management model


 
I will also add Class Library project to my solution so I can store the generated code by CodeFluent Entities.
 
I will add a Persistence producer (SQL Server) and a Business Object Model Producer. I will set the Target Directory to my Class Library project for both producers.
 
Now I can add my Linq-To-Sql producer. As said before, this producer is a Sub-Producer of the BOM Producer, so I have to add it to the BOM Producer.
 
Add Sub-Producer

Add Sub-Producer


 
LINQ to SQL Sub-Producer

LINQ to SQL Sub-Producer


 
As you can see, there is no configuration required for this Sub-Producer.
 
We need to set the “Default Entity Tracking Mode” to “None” at the project level to avoid any problem with the LINQ to SQL query provider.
 
Default Entity Tracking Modes

Default Entity Tracking Modes


 
Let’s build our CodeFluent Entities project, and open a BOM class so we can see what has been generated.
 
LINQ to SQL attributes

LINQ to SQL attributes


 
We now see that our class has been decorated with LINQ to SQL attributes. We also see that the “System.Data.Linq” namespace is not defined. To fix that we need to add a reference to the “System.Data.Linq” assembly in our BOM project.
 
We have now a LINQ to SQL compliant BOM.
 
Let’s test it using LINQ to SQL.
 
For that I will add a simple Console application. Then I add a reference to my BOM project, to the CodeFluent.Runtime assembly and to the System.Data.Linq assembly. And add the right application configuration.
 
We will use the DataContext class provided by the LINQ to SQL infrastructure to manipulate data (insert, delete, update and read). And we can retrieve the connection string from the CodeFluentContext class.
 

string connectionString = CodeFluentContext.Get(PetsManagement.Constants.PetsManagementStoreName).Persistence.ConnectionString;
using (DataContext context = new DataContext(connectionString))
{
}

 
Let’s start by adding some data to our database:
 

string connectionString = CodeFluentContext.Get(PetsManagement.Constants.PetsManagementStoreName).Persistence.ConnectionString;
using (DataContext context = new DataContext(connectionString))
{

    Person bart = new Person { Name = "Bart" };
    Pet bartsDog = new Pet { Name = "Santa's Little Helper", Age = 2, Kind = PetKind.Dog };
    bartsDog.Owner = bart;
    Pet bartsCat = new Pet { Name = "Snowball II", Age = 3, Kind = PetKind.Cat };
    bartsCat.Owner = bart;//not true, is Lisa

    Person pablo = new Person { Name = "Pablo" };
    Pet pablosDog = new Pet { Name = "Shiny", Age = 17, Kind = PetKind.Dog };
    pablosDog.Owner = pablo;
    Pet pablosDog2 = new Pet { Name = "Vanilla", Age = 10, Kind = PetKind.Dog };
    pablosDog2.Owner = pablo;

    Person ferb = new Person { Name = "Ferb" };
    Pet ferbsPet = new Pet { Name = "Perry", Age = 32, Kind = PetKind.Platypus };
    ferbsPet.Owner = ferb;

    context.GetTable<Person>().InsertAllOnSubmit(new[] { bart, pablo, ferb });
    context.GetTable<Pet>().InsertAllOnSubmit(new[] { bartsDog, bartsCat, pablosDog, pablosDog2, ferbsPet });

    context.SubmitChanges();
}

 
Now let’s retrieve all the pets grouped by “Pet kind”.
 

string connectionString = CodeFluentContext.Get(PetsManagement.Constants.PetsManagementStoreName).Persistence.ConnectionString;
using (DataContext context = new DataContext(connectionString))
{
    var petsByKind = from pet in context.GetTable<Pet>()
                        group pet by pet.Kind into gr
                        select gr;

    foreach (IGrouping<PetKind, Pet> kindGroup in petsByKind)
    {
        Console.WriteLine("----" + kindGroup.Key + "----");
        foreach (Pet pet in kindGroup)
        {
            Console.WriteLine(pet.Name + " : " + pet.Owner.Name);
        }
    }
}

 
The result is:

Pets grouped by kind

Pets grouped by kind


 
Let’s now delete a cat named “Snowball II” which owners name is “Bart”.
 

string connectionString = CodeFluentContext.Get(PetsManagement.Constants.PetsManagementStoreName).Persistence.ConnectionString;
using (DataContext context = new DataContext(connectionString))
{
    Pet petToDelete = (
                        from person in context.GetTable<Person>()
                        where
                            person.Name == "Bart"
                        from pet in person.Pets
                        where
                            pet.Kind == PetKind.Cat &&
                            pet.Name == "Snowball II"
                        select pet
                        )
                        .FirstOrDefault();

    if (petToDelete != null)
    {
        context.GetTable<Pet>().DeleteOnSubmit(petToDelete);
        context.SubmitChanges();
    }

}

 
Thanks to the LINQ to SQL Sub-Producer we can use the LINQ to SQL infrastructure with our BOM, but there are several limitations and several concepts/features that can be done by CodeFluent Entities and not supported by LINQ to SQL: The CodeFluent Entities model is richer than LINQ to SQL (rules, validation, aspects, advanced relations, automatic tracking, cache, circular dependencies, multi-databases…).
  

Regards,
Pablo Fernandez Duran

CodeFluent Entities and Syncfusion for an amazing application!

April 15, 2013 1 comment

When applications are beautiful, fast and robust at the same time, we qualify them as amazing. If you think it also means a long development process, then you have not seen applications using both SoftFluent and Syncfusion products altogether!

SoftFluent and Syncfusion have partnered to help you build these amazing applications in no time.  CodeFluent makes the application highly functional, while Syncfusion makes the application interface elegant and user-friendly.

CodeFluent Entities is a unique product integrated into Visual Studio which allows developers to generate database scripts, code, web services and UIs in the Microsoft .NET platform. 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.

Syncfusion, Inc. provides the broadest range of enterprise-class software components and tools for the Microsoft .NET platform. With Syncfusion, developers can move beyond simply coding applications to delivering real business innovation—the elegant user interfaces, business intelligence dashboards, and sophisticated reporting that today’s business users need, in the formats they demand.

Whether you need to build applications with WinForms or WPF, or websiteswith WebForms or MVC, SoftFluent and Syncfusion provide all the necessary tools to help you.

To show you how it works, we built a full application using CodeFluent Entities and Syncfusion components. With Visual Studio 2012, we have created a WPF application that consumes web services to communicate with an SQL Server 2008 database. The database we used is a sample database of Microsoft SQL Server, called AdventureWorks.

.

The application can be created in five steps:

.

1. CodeFluent Entities project

Create a CodeFluent Entities project in Visual Studio 2012. You also need a class library project that contains the business-object model, a class library project (Proxy) that contains your web service contracts, and the WPF application.

.

2. Import the AdventureWorks database

If you right-click on the CodeFluent Entities project, you will have the option to import an existing database or model as you can see on the screenshot below.

1

Then follow the instructions to import the AdventureWorks database.

.

3. Set up the producers

Once the database has been imported, you can view the visual model inside the CodeFluent Entities project (Surface > Default) as you can see here:

2

Now that you have your model, you need to add producers. These producers are responsible for generating code for your application.

The first producer is the BOM (Business Object Model) producer, which corresponds to the business logic. The code generated will be classes for each entity of your model. This code is exceptionally readable and can be customized using partial classes, if needed. Also, this producer contains a sub- producer responsible for generating services.

The second producer is the SQL producer responsible for generating SQL scripts, such as tables, views, and stored procedures.

The third producer is the WPF ClickOnce Smart Client, which is responsible for generating UIs. These UIs are generated using templates, located in the CodeFluent Folder. We will discuss this in more detail later.

The fourth producer is the Template, responsible for creating a host for the web services.

The fifth producer is the Command Line Execution producer, responsible for running a batch file that will insert data in your database.

3

.

4. Generation

The model is ready to be generated. In a single click, the CodeFluent Entities project will load your model in memory, and run each of the producers to generate ASP.NET code (C# in this example), SQL scripts and WPF controls. The application is almost ready to run. The last steps are to:

  1. Set up the connection string in your WPF application.
  2. Set up the application that hosts the web services to run at the same time as the WPF application.

That is all you need to do in order to run the application! When you launch the application, you will have a list of all entities, and you will be able to manipulate the data of these entities with generic methods such as load, load all, update, delete, and save. Each of these actions will consume the web services that are being hosted in the other application.

.

5. SyncFusion Components

The full running application uses standard ASP.NET controls for your WPF application. Though these components are functional, they are not always the best-looking ones. This is where Syncfusion comes in to transform a functional application into an amazing application.

CodeFluent Entities generates reusable controls for the application, so that one control can be used in several pages. As a result, the work consists in updating these ASP.NET standards controls by using Syncfusion controls, to end up with a highly functional and beautiful application:

4

Interface displaying the list of departments

.

5

Interface displaying the edition of a department in a popup

.

6

Interface displaying the edition of the SalesTerritory field that corresponds to a list prefilled with a related entity

.

Using the power of CodeFluent Entities to generate functional applications quickly, and the power of Syncfusion’s beautiful components, you can create amazing applications in no time.

.

6. Unlimited possibilities

To go further with CodeFluent Entities and Syncfusion integration, you can reuse Syncfusion components in other applications at no cost. Indeed, CodeFluent Entities uses templates to generate components, such as the view page, the edit form and so on. These templates are available in the CodeFluent folder (where it was installed, usually in \CodeFluent\Modeler\Templates\SmartClient).

Extremely simple to read and to understand, these templates can be modified to produce pages with custom components, such as the ones provided by Syncfusion. By doing so, each CodeFluent Entities project can reuse these templates to produce amazing applications. Although you have developed a WPF application in this example, you can do the same with all other types of applications, such as WinForms, WebForms, MVC, mobile or any combination of these technologies.

.

If you want to download the sample project demo please click here: http://www.softfluent.com/downloads/AdventureWorksReloaded.zip

CodeFluent Entities and the Localization Aspect: how to show localizable properties in the design surface

April 12, 2013 Leave a comment

Using CodeFluent Entities, you can use “Member Format Expressions” (a.k.a “MFEX”) to customize the way names of entities and properties are formatted. We already have blogged about that feature here:

https://blog.codefluententities.com/2012/01/12/codefluent-entities-member-format-expressions-part-1/
https://blog.codefluententities.com/2012/01/13/member-format-expressions-part-2/

In this post, we’re going to explain how to create an MFEX that will display this on the surface when selected:

As you clearly see, I have defined two localized properties on my model (on the Name property of the Campaign entity, and on the Name property of the Space entity). But wait! A red ‘Localizable’ text is appended to the right of the property name. How do I do this?

Let start with this expression, demonstrated in the previous blog post:

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

With this expression, key properties will be shown in red and other properties will be shown in blue. The condition syntax is in fact a .NET expression. IsKey is a property (of Boolean type) of the CodeFluent.Model.Property class. If I was writing C# code, I could do this ‘if (myProperty.IsKey)’ etc… But MFEX conditions also support “dot navigation”, so you could write this:

<font condition=Rules.Count color=’red’>{#Name}<else/><font color=’blue’>{#Name}</font></font>

In this case, we are navigating on the Rules property of the CodeFluent.Model.Property class, and on the Count property of the CodeFluent.Model.RuleCollection class. Count is of type Int32 and the condition evaluator needs a Boolean, so it just tests the resulting Int32 against 0, so the condition is equivalent to “Rules.Count > 0”. So this expression will show in red all the properties that have CodeFluent Entities rules defined on it.

Well, it turns out MFEX also supports (partially) methods in conditions. So, here is how to display localized properties:

{Name} <font color="red" condition="'true'=Element.GetAttribute('localizable','http://www.softfluent.com/codefluent/patterns/localization/2008/1')">Localizable</font>

Note : it’s important to respect the difference between the single quote and the double quote characters here.

So, the condition is an expression with an operation. = is the ‘equality insensitive’ operator. It means it uses equality but is case insensitive in the case of string comparison. Here is the list of available operators:

  • == or = : Equal
  • != or <> : NotEqual
  • [=CS] : EqualCaseSensitive
  • [!=CS] : NotEqualCaseSensitive
  • >= : GreaterThanEqual
  • <= : LesserThanEqual
  • > : GreaterThan
  • < : LesserThan
  • [StartsWith] : StartsWith
  • [StartsWithCS] StartsWithCaseSensitive
  • [EndsWith] : EndsWith
  • [EndsWithCS] : EndsWithCaseSensitive
  • [Contains] : Contains
  • [ContainsCS] : ContainsCaseSensitive

The condition will compare the literal string ‘true’ with the result of a method call that starts on the Element property of the CodeFluent.Model.Property class, which is of System.Xml.XmlElement type. XmlElement has a method called GetAttribute that simply gets an XML attribute given it’s local name (without a prefix if it’s in a specific XML namespace) and the XML namespace.

So, with this condition, we are accessing the XML element underlying the CodeFluent Entities Property concept. When a property is marked as localized, the corresponding XML text (in memory) is just modified like this:

  <Campaign namespace="SoftFluent.Advertising1" >
    <Id />
    <Name _loc:localizable="true" />
  </Campaign>

Happy MFEXing!

The CodeFluent R&D Team.

Create Windows Azure Mobile Services in a few minutes thanks to CodeFluent Entities

April 5, 2013 Leave a comment

You may have heard that a lot of new features were added to Windows Azure during the last few months.

Today we will focus on Windows Azure Mobile Services. First of all, what is it?

Long story short, Windows Azure Mobile Services allows you to expose your data through JSON web services. Microsoft provides SDKs for Windows Store and Windows Phone 8 apps, pre-configured projects for iOS and Android, and JavaScript libraries for HTML.

The SDKs offer a large number of methods that provide access to your data stored in Azure.

So let us create a new CodeFluent Entities project. As an example for this article, we will use the “advertising sample” model. I will also add a class library project which will contain our SQL scripts.

We will not need more for this article since we are just going to generate the SQL Azure database with CodeFluent Entities.

First, we will add the SQL Azure Producer to our project. Regarding the configuration of the producer, we will only set the property “Produce Scripts” of the SQL Azure section to “true”.

1

Also, and this is really important, we will set the “Produce Schema” property to “true”. This property can be found by clicking on the “Advanced Properties” button as shown in the following screenshot.

2

You may wonder why this is so important. It is simply because Windows Azure Mobile Services will use the name we are going to define for our service to map it with the schema name of our database tables. So choose it carefully!

In this example, we are going to name our schema “sampleadvertising”. To do so, we have to open the properties of our entities and fill in the schema property as shown below.

3

Once we have updated the “Schema name” property of each entity we want to expose, we can build our project to produce our database.

When the project has been produced, check the database in SQL Azure to make sure we have our custom schema name on our tables.

4

Let us go back on Windows Azure to create our mobile service. According to the schema name we used in this example, we will name it “sampleadvertising” and we will associate it with the database created earlier.

5

6

Now that our service has been created, click on the “Data” tab of our service to “add a table”. Here we will add tables which names are identical to our database tables; for instance, “Campaign”.

7

8

Note: for the purpose of this article we will set the authorization for all CRUD methods to “Everyone”. Do not do the same on production especially if you work with sensitive data.

Those tables are not new database tables, they are only created to associate the tables created thanks to CodeFluent Entities with our mobile service and therefore expose our database data.

Once the table is added, we can access our data from everywhere in a standardized format.

9

From now on, we will show how to use our data from a sample Windows Store application.

First of all, we need to install the Windows Azure Mobile Services SDK which can be found at this address: https://go.microsoft.com/fwLink/?LinkID=257545&clcid=0x40C

Once the SDK is installed, let us add a new project to our solution, a blank C# Windows Store app, named “SampleAdvertising.App”.

Then add a reference to the SDK we have previously installed.

10

Let us open the file “App.xaml.cs” to register our mobile service. In our case, we will add the following code:

    <br />public static MobileServiceClient MobileService = new MobileServiceClient(&quot;https://sampleadvertising.azure-mobile.net/&quot;);     <br />

In this particular example, we will not need to register the application key since we have set the permissions to “everyone”.

Now that our service is registered, I will show you how to consume our database data.

For instance, we will query our table “Customer” to get the customer “SoftDia”. To do so, we will create an async method that will get our “Customer” table. Then we will use the “ReadAsync” method with a query filter based on our “Customer_Name” column.

Finally, we will get a JsonObject from this IJsonValue and display its content in our Visual Studio output.

Here is the code used:

    <br />GetCustomerByName(&quot;SoftDia&quot;);</p>  <p>private async void GetCustomerByName(string customerName)</p>  <p>{</p>  <p>IMobileServiceTable customerTable = App.MobileService.GetTable(&quot;Customer&quot;);</p>  <p>IJsonValue myCustomer = await customerTable.ReadAsync(&quot;$filter=(Customer_Name eq '&quot; + customerName + &quot;')&quot;);</p>  <p>JsonObject myCustomerObject = myCustomer.GetArray()[0].GetObject();</p>  <p>foreach (var item in myCustomerObject)</p>  <p>{</p>  <p>Debug.WriteLine(item.Key.ToString() + &quot;: &quot; + item.Value.Stringify());</p>  <p>}</p>  <p>}    <br />

And this is what we get from our “Customer” table

11

Cheers,

Aymeric ROLAND