Archive

Archive for the ‘.NET Domain Model’ Category

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
 
 

Designing Databases with CodeFluent Entities: Inheritance

April 20, 2012 Leave a comment

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

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

For instance, say we have the following hierarchy:

Here’s the result in the database:

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

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

RETURN

Cheers,

Carl Anderson

CodeFluent Entities: Standing Against Anemic Domain Models

April 6, 2012 Leave a comment

A few years ago Martin Fowler wrote this great post regarding what he calls “Anemic Domain Models”:

The basic symptom of an Anemic Domain Model is that at first blush it looks like the real thing. There are objects, many named after the nouns in the domain space, and these objects are connected with the rich relationships and structure that true domain models have. The catch comes when you look at the behavior, and you realize that there is hardly any behavior on these objects, making them little more than bags of getters and setters. Indeed often these models come with design rules that say that you are not to put any domain logic in the the domain objects. Instead there are a set of service objects which capture all the domain logic. These services live on top of the domain model and use the domain model for data.

That’s exactly what we try to avoid: those business logic empty classes, often wrapped in an extra layer of procedural services, which in the end just create a procedural style design. Furthermore, many people think that anemic objects are real objects, thus completely missing the point of what object oriented design is all about.

image

Instead, as Eric Evans states about the Domain Layer (or Model Layer):

Responsible for representing concepts of the business, information about the business situation, and business rules. State that reflects the business situation is controlled and used here, even though the technical details of storing it are delegated to the infrastructure. This layer is the heart of business software.

And we completely agree: especially right now, on the verge of a new technology wave (e.g. HTML5 & WinRT) the real key is your architecture. If you already have this rich domain layer, upper layers should just be consumers of it, empty shells providing user interaction to the heart of your business software. Consequently supporting a new platform (going from desktop to web, or Web Forms to MVC for instance) gets down to creating this new shell.

That’s what CodeFluent Entities is all about thanks to it’s .NET Business Object Model Producer: it generates a full .NET domain layer containing your business logic and which can be used across all .NET technologies (Windows Forms, WPF, SharePoint, ASP.NET MVC, ASP.NET Web Forms, Windows Workflows, etc.) this way securing your investments.

This is possible as this producer (= code generator) can generate:

  • Classes: plain old classes (not deriving from a base technical class), human readable, that are all partial and meant to be easily extensible by developers, implementing an extensive set of interfaces (ICloneable, IComparable, IDataErrorInfo, IEquatable, INotifyPropertyChanged, etc.) to ease development of upper layers, and easily debuggable as no code is dynamically generated at run time
  • Enumerations: since CodeFluent Entities is not an ORM, you can create your own .NET enumerations or reuse existing ones,
  • Multiple namespaces: as it’s common to have more than a single domain in real enterprise class applications,
  • Rules: to validate your data, set-up transactions, and implement your business logic,
  • Methods: create your own methods aside default generated ones,
  • light objects as structures or non-persistent objects useful to gather-up cross entity information,
  • components as a binary large object http handler to manipulate blobs in web environments, or a cache manager based on the standard ASP.NET cache manager, and more.

Last but not least, we don’t think that tools can generate entire enterprise-class applications, that’s not what we’re saying. Developing applications is a complex operation that needs more than data access and/or UI controls. Instead what we’re saying is that we provide a tool to developers which helps them set-up rock-solid foundations for their .NET applications, built on a consistent domain model, which developers will have to extend and fill-in the gaps.

The recipe we provide through CodeFluent Entities ends-up creating .NET applications based on a rich Domain Layer built by the tool and developers, containing the full business logic of your application. It’s a complete and consistent API which can be used on all platforms (x86, x64, desktop, web) across all technologies (.NET 2 to 4) this way securing your investments.

Carl Anderson

CodeFluent Entities: Build cross language and technology applications

April 4, 2012 Leave a comment

We’ve seen in the previous post (CodeFluent Entities Supports Multiple Database Systems) that once you invested the time into designing your application in CodeFluent Entities, you can switch from a database system to another by switching producers (e.g. Oracle Database to SQL Server, SQL Server to SQL Azure).

Well, the same logic also applies to upper tiers, for instance using the .NET Business Object Model Producer you can generate C# or VB.NET classes by selecting your desired target language:

Furthermore, the code generated by the .NET Business Object Model Producer supports all .NET Framework versions from 2.0 to 4.0 and runs on all .NET platforms: ASP.NET Web Forms, ASP.NET MVC, Windows Forms, WPF, Silverlight (2 to 4), SharePoint, Windows Workflow Foundation, WCF, etc.

 

In the end, CodeFluent Entities allows you to quickly build rock-solid foundations for your application whilst decoupling your business logic from the technology.

 

Cheers,

Carl Anderson

Entity Framework and CodeFluent Entities

April 2, 2012 Leave a comment

One question that we get a lot is:

What’s the difference between CodeFluent Entities and Entity Framework?

or

How is CodeFluent Entities any different from Entity Framework?

In a nutshell, the ADO.NET Entity Framework is a data access method (it’s an ORM) which allows you to generate .NET classes mapped on to a database. On the other hand, and as explained in the “CodeFluent Entities is not an ORM post, CodeFluent Entities allows you to generate continuously components (from a model and not a database) such as scripts (e.g. T-SQL, PL/SQL), code (e.g. C#, VB.NET), web services (e.g. WCF) and UIs (e.g. ASP.NET, SharePoint).

Since we get this question a lot, we recently published an updated version of the “CodeFluent Entities & Entity Framework” document!

CodeFluent Entities & Entity Framework Download “CodeFluent Entities & Entity Framework” here (PDF)!

Furthermore, if you want to see CodeFluent Entities in action so you can make your own opinion, there’s the latest recorded live product demo which is available on our YouTube channel.Likewise, on April 13th we’ll be doing a 20-minute “CodeFluent Entities Tour” for DevProConnections so if you’re not familiar with the product and are looking for a quick way to know more this is definitely a great option for you.

Finally, and to me there are no better way, you can try the product yourself and see how it’s different from Entity Framework. To do this, SoftFluent provides a free version which is available online: check-out the Personal Edition.

Cheers,

Carl Anderson

CodeFluent Entities: Attributes

February 23, 2012 1 comment

Using CodeFluent Entities you can define attributes on other concepts such as Entities, Methods or Properties and what gets really interesting is that the .NET Business Object Model Producer translates those CodeFluent Entities Attributes into actual .NET attributes Smile

Now say you want to specify some specific attributes on your generated .NET classes or data annotations on your properties, defining attributes in your model would be the way to go!

To do so select your concept such as a property and click on “Add Attribute” in the ribbon, the following dialog will show up:

image

In the attribute name set the full type name of your attribute such as System.ComponentModel.DataAnnotations.RequiredAttribute”.

Note: Setting the attribute class using the drop down list in the lower part of the form allows you to specify where this attribute should be placed in the generated classes. Default is in the entity class, but you can also place it in the service class, the service interface, or the proxy class.

In the screenshot below we defined a Required data annotation attribute on the Name property of our entity:

image

Then here’s the output after generating our model over:

[System.ComponentModel.DataAnnotations.RequiredAttribute()]
[System.ComponentModel.DefaultValueAttribute(default(string))]
[System.Xml.Serialization.XmlElementAttribute(IsNullable=true, Type=typeof(string))]
public string Name
{
    (…)

To specify a parameter to your attribute, go back to your model, select your attribute and click on the Arguments property in the property grid:

image

And let’s add an error message to our required attribute:

image

Generate over and here’s the result:

[System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage="Name is required")]
[System.ComponentModel.DefaultValueAttribute(default(string))]
[System.Xml.Serialization.XmlElementAttribute(IsNullable=true, Type=typeof(string))]
public string Name
{
    (…)

 

Carl Anderson

CodeFluent Entities: Automatic Traces Sub-Producer

February 7, 2012 1 comment

Since fall, CodeFluent Entities ships an Automatic Trace sub-producer which can be added on top of the Business Object Model producer, and which will add traces to declared properties and methods.

To use it, right-click on your Business Object Model producer and select “Add New SubProducer”:

image

Keep everything by default and click “OK”:

image

Generate over again, and taadaa! All your .NET classes now have traces:

image

Please note that by default generated traces use the System.Diagnostics.Trace.WriteLine method, but this can be customized. For instance you could set the producer to use the System.Diagnostics.Debug.WriteLine or even your own custom method Winking smile

Isn’t life beautiful?

Carl Anderson

CodeFluent Entities: Generating a CHM documentation from your Business Object Model

January 19, 2012 2 comments

CodeFluent Entities provides a Documentation producer capable of generating all files and scripts required by Sandcastle to generate a Microsoft Compiled HTML Help (CHM) documentation out of your CodeFluent Entities generated .NET Business Object Model (BOM).

Step 1: Downloading Sandcastle

First, you need to download and install Sandcastle on your machine (http://sandcastle.codeplex.com/).

 

Step 2: Generate using CodeFluent Entities

Then in your model, add the Documentation sub-producer to your Business Object Model Producer:

image

As the Sandcastle Target Directory, set the directory in which you want the sub-producer to generate all the Sandcastle scripts.

If you generate over again, you’ll notice that all members of your BOM (classes, fields, properties, methods) now have remarks:

/// <summary>
///     Loads this instance.
/// </summary><param name=”id”>The id.</param>
public static SoftFluent.Advertising.Customer Load(int id)

 

Step 3: Get the XML documentation file & assembly

To build the CHM documentation Sandcastle needs as an input:

  • The XML documentation file,
  • The actual .NET assembly.

The XML documentation file isn’t created by default, to do so, in your project properties, in the Build tab, you need to check it:

image

Build your project so you’ll get both the XML documentation file made out of the generated remarks, as well as the compiled assembly (.dll).

 

Step 4: Check everything is in order

Those files, the XML documentation and dll, are passed to Sandcastle production tools by the BuildDocumentation.cmd script.

So, before running the script, make sure the paths used in it are correct!

Secondly, the MrefBuilder.exe tool uses reflection to extract information, therefore you need to specify all dependencies used by your BOM so it can load your assembly.

Once the MrefBuilder line of the script runs fine, you’re ready to run the script!

 

Step 5: Generate your documentation!

Run the script, and as a result you’ll have a Microsoft Compiled HTML Help documentation in the Chm directory:

image

 

Carl Anderson

CodeFluent Entities: The Business Object Model

November 10, 2011 Leave a comment

The Business Object Model (a.k.a. BOM) is generated by the Business Object Model Producer and is a .NET translation of your platform independent model which you designed in CodeFluent Entities.

In practice it’s a set of C# or VB.NET classes which was inferred from your entities. Two classes are generated per entity, one representing the entity (e.g. Customer) and one representing a collection of this entity (e.g. CustomerCollection). This set of classes is built to contain all the business logic of your application (entities, methods, rules, custom code, etc.) and to be easily used in upper layers.

By that I mean that this BOM can be used across all .NET applications may they be WPF, Windows Forms, ASP.NET Web Forms, ASP.NET MVC, WCF web services, ASMX web services, console applications, Windows Workflows and so on.

Furthermore, those classes are built to ease your life when building your app:

  • They are all serializable (XML, .NET binary / SOAP, WCF, etc.)
  • They are all partial
  • They do not derive from a base technical class but are plain old classes
  • They implement by default an extensive set of .NET inferfaces to ease your life (System.ComponentModel.IDataErrorInfo, System.IEquatable<T>, System.ComponentModel.INotifyPropertyChanged, System.ICloneable, System.IComparable<T>, etc.)

On a higher level, the BOM also provides application oriented features that are common to enterprise-class applications so developers won’t have to code them over and over again from one project to another. Here’s a bulk list of out-of-the-box features provided by the BOM:

  • Data Binding,
  • Data Validation,
  • Paging and Sorting,
  • Security,
  • Localization (with .NET resources, but also data localization),
  • Concurrency,
  • Transactions,
  • Caching,
  • Blob management.

I’m probably be missing some, but you get the general idea: let the tool take care of all the plumbing and recurrent but yet necessary code so you can spend time on what matters such as the UI.

Furthermore, since those features are implemented in the BOM, they’ll be shared by all clients using that BOM so that UI is just UI, meaning that if you started by developing a Windows Forms application and then need to go to WPF, you don’t have to write everything over, but just the UI specific code. And this is also true from desktop to web, web to mobile or even in-house to cloud.

To paraphrase Rockford Lhotka in his "Silverlight 6 doesn’t matter" post, in the end the key is architecture.

CodeFluent Entities: Blob Cache

November 9, 2011 Leave a comment

Blobs in CodeFluent Entities

CodeFluent Entities provides advanced Binary Large Objects (blobs) types from the designer, up to the UI layers. Supported binary types are: video, audio, file, picture and blob. With all these types, the tool defines optional metadatas such as FileName, ContentType, Attributes, Size, LastWriteTime, LastAccessTime and CreationTime.

For all these types, CodeFluent Entities provides built-in support for:

  • Streaming: the runtime classes provided support streaming from any client type (web, smart client, WCF) to the server. In the middle tier, the generated code never ever stores the full array of bytes in memory, this way avoiding the deadly Large Object Heap (LOH). Regarding the persistence tier, the data reader uses the SequentialAccess CommandBehavior, and its likewise in the web layer, the code and controls provided use the TransmitFile method, etc.
  • Chunking: CodeFluent Entities generates a reusable BITS server (supporting the BITS protocol 1.4 for download and upload, without dependency on IIS).
  • Displaying: the CodeFluent Entities web runtime provides ASP.NET custom controls to view, download and upload these blobs sparing developers the extra-work of writing the needed code. More than just ASP.NET, the runtimes also provide TypeConverters and WPF ValueConverters to ease data-binding in .NET applications.
  • Caching: blobs can be cached on the server and on the client to relieve the database, a feature which we’ll detail this post.

Server Cache

Generated blobs automatically cache themselves by default. In practice, when loading a blob property using CodeFluent Entities, it actually loads it from the database the first time and stores it on the disk; consequently, next calls won’t load it back from database anymore, unless a modification was done on the blob which will reload it and update the cache.

By default, blobs are cached in a directory in the user profile corresponding to the user running the application. This can be configured at run-time through the configuration file (app.config / web.config) of your application:

<configuration>
  <configSections>
    <section name="Sample" type="CodeFluent.Runtime.CodeFluentConfigurationSectionHandler, CodeFluent.Runtime"/>
  </configSections>
  <Sample cacheDirectoryPath="C:\Blobs" />
</configuration>

Note: Sample is my application name and default namespace in CodeFluent Entities.

Please note, that you can enable/disable this server caching feature whenever you want to from the configuration file:

<configuration>
  <configSections>
    <section name="Sample" type="CodeFluent.Runtime.CodeFluentConfigurationSectionHandler, CodeFluent.Runtime"/>
  </configSections>
  <Sample cacheEnabled="false" />
</configuration>

Client Cache

In ASP.NET applications, using the generated controls, once the blob was retrieved once, the browser will store it in its temporary files.

image

Then, on the second call, the browser will ask the blob once again whilst indicating that it already has a version of it in its temporary files by passing the date of it in the HTTP request header. The server will then send back a 304 response indicating to the navigator that the image does not need to be downloaded once again. Ergo, the image stored in the browser’s temporary files will be used.

image

Thanks to this mechanism, the image was downloaded once and not twice, the database was not called, and IIS served the file using http.sys kernel cache, due to the fact the CodeFluent Runtime uses the TransmitFile function (http://support.microsoft.com/kb/823409) :)

In conclusion, this is once again one of those little things, yet so important, that CodeFluent Entities does for us without having us to think about it, so we can focus elsewhere!

Follow

Get every new post delivered to your Inbox.

Join 49 other followers