You are here: Architecture > BusinessFoundation > Working with Data > Working with Entity Objects

Working with Entity Objects

Introduction

This section describes how to work with entity objects from Business Foundation (BF). The entity objects use request-response system to call methods. You should create request passing target entity object, request parameters and call Execute method, BF would find handler to process request, call handler and return response with execution result.

All classes are available in Mediachase.BusinessFoundation.Data.Business namespace.

DataContext initalization

DataContext has User and UserTimeZone properties. Entity objects and modules can use them to provides programmatic access to the current user id and time zone. You should initialize User and UserTimeZone properties before working with entity objects.

When you create DateTime or Date meta field you can pass using user time zone and DateTime value would be converted to user time zone automatically.

Recommendation: In ASP.NET application, we recommend to initialize DataContext in the Global. Application_BeginRequest method.

EntityObject class

EntityObject class represents Meta class object. Meta class is an abstract representation of something, whereas an entity object is a usable example of the thing the meta class represents.

Entity object can be untyped or typed. Use the EntityObject object and its properties to retrieve and update the entity object in the persistent storage. You could not create a new EntityObject directly. You should use BusinessManager class and request-response system for calling Entity object methods.

BusinessManager class

BusinessManager class represents methods for processing entity object's request-response. You should call BusinessManager static methods to initialize entity object, create entity object, update entity object, delete entity object, list entity objects and execute custom method for entity objects.

Example: Creation of a new entity object

EntityObject page = BusinessManager.InitializeEntity("Class_1");
page["Title"] = "Title Text";
page["Description"] = "Description Text";
PrimaryKeyId pageId = BusinessManager.Create(page);

Request-Response system

BF has request-response system to process entity object methods. You should create request passing target entity object, request parameters and call Execute method, BF would find handler to process request, call handler and return response with execution result.

Example: Load entity object

LoadRequest request = new LoadRequest(new EntityObject(metaClassName, primaryKeyId));
LoadResponse response = (LoadResponse)BusinessManager.Execute(request);
EntityObject entityObject = response.EntityObject;

You can override the default method handler, add custom plugins or define a custom method.

Pipeline events

When instance of request is created and you call BusinessManager.Execute method, BusinessManager creates pipeline and the following events are executed by the BusinessManager class while the request is processed.

  1. Call PreExecute method of the appropriate IRequestHandler class for the request.
  2. Call Execute method of the appropriate IPlugin classes that are subscribed to PreMainOperation event.
  3. Open Transaction
  4. Call PreExecuteInsideTransaction method of the appropriate IRequestHandler class for the request.
  5. Call Execute method of the appropriate IPlugin classes that are subscribed to PreMainOperation (In-Tranasaction) event
  6. Call Execute method of the appropriate IRequestHandler class for the request.
  7. Call PostExecuteInsideTransaction method of the appropriate IRequestHandler class for the request.
  8. Call Execute method of the appropriate IPlugin classes that are subscribed to PostMainOperation (In-Tranasaction) event
  9. Commit Transaction
  10. Call PostExecute method of the appropriate IRequestHandler class for the request.
  11. Call Execute method of the appropriate IPlugin classes that are subscribed to PostMainOperation event

Handler

A request handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to a business manager. The most common handler is a default entity object handler that processes default methods. When users execute method, the request is processed by the business manager through the handler. You can create your own handler that executes custom method.

Create Handler

To create a custom handler, you create a class that implements the IRequestHandler interface. You should implement PreExecute, PreExecuteInsideTransaction, Execute, PostExecuteInsideTransaction, PostExecute methods.

BF has BaseRequestHandler helper class, that you can use as a base class for custom handler, it implements the IRequestHandler and has virtual methods.

Register Handlers

After you have created a custom handler class, you must register it in the Application config file. This enables application to call the handler. In the application's config file, create a mediachase.businessFoundation.data/businessManager section.

The following example shows how to register an handler that responds to requests for the Test method for Class_1 meta class. The handler is defined as the class SampleHandler in the assembly SampleHandlerAssembly.

<businessManager>
<handlers>
<add metaClass="Class_1" method="Test" type="SampleHandler, SampleHandlerAssembly" />
</handlers>
</businessManager>

metaClass attributes supports search mask with * and ? chars.
method attributes supports search mask with * and ? chars.

Plugin

Event pipeline can be extended with plugins. Plugin can be added before or after method execution, in or out transaction scope. Plugin can modify request, response, cleaun up data, provide custom logic and etc.

Create Plugin

To create a custom plugin, you create a class that implements the IPlugin interface. You should implement Execute methods.

Register Plugins

After you have created a custom plugin class, you must register it in the Application config file. This enables application to call the plugin. In the application's config file, create a mediachase.businessFoundation.data/businessManager section.

The following example shows how to register a plugin that responds to any requests for the Test method for any meta class. The handler is defined as the class SamplePlugin in the assembly SamplePluginAssembly.

<businessManager>
<plugins>
<add metaClass="*" method="Update;Create" eventStage="PreMainOperationInsideTranasaction" type="SampleHandler, SampleHandlerAssembly" />
</plugins>
</businessManager>

metaClass attributes supports search mask with * and ? chars.
method attributes supports search mask with * and ? chars and multiple methods separated by semicolons.
eventStage supports several event stage items separated by ‘|’.

Default Methods

BF implements several methods:

Initialize

Call Initialize method to create a new instance of entity object.

InitializeEntityResponse response = (InitializeEntityResponse)BusinessManager.Execute(new InitializeEntityRequest(metaClassName));
EntityObject obj = response.EntityObject;

 

Call Initialize method of BusinessManager to simplify method execution.

Load

Call Load method to load instance of entity object by primary key.

LoadResponse response = (LoadResponse)BusinessManager.Execute(new LoadRequest(new EntityObject(metaClassName, primaryKeyId)));
EntityObject obj = response.EntityObject;

 

Call Load method of BusinessManager to simplify method execution.

Create

Call Create method to store entity object in the persistent storage.

CreateResponse response = (CreateResponse)BusinessManager.Execute(new CreateRequest(target));
PrimaryKeyId newPk = response.PrimaryKeyId;

 

Call Create method of BusinessManager to simplify method execution.

Update

Call Update method to update entity object in the persistent storage.

BusinessManager.Execute(new UpdateRequest(target));

 

Call Update method of BusinessManager to simplify method execution.

Delete

Call Delete method to delete entity object from the persistent storage.

BusinessManager.Execute(new UpdateRequest(target));

 

Call Delete method of BusinessManager to simplify method execution.

List

Call List method to select collection of entity object from the persistent storage.

ListResponse response = (ListResponse)BusinessManager.Execute(new ListRequest(metaClassName, filters, sorting));
EntityObject[] objs = response.EntityObjects;

 

Call List method of BusinessManager to simplify method execution.

Custom Methods

To create a custom method you should create and register a custom handler and define custom request, response.

All requests should be inherited from Request class.
All response should be inherited from Response class.

Filtration and Sorting

Call List method to return array of entity object from the meta class.

Additional information about FilterElement and SortingElement you can find in the Filters and Sorting section.

Typed entity objects

Entity object can be typed or untyped. You can use either typed or untyped entity objects (Entity object) in your applications. However, BF has more tool support for typed entity object, and programming with them is easier and less error-prone.

To use typed entity object, you should:

  1. Run McCodeGen to create typed entity object C# class
  2. Register a new typed object as primary type for meta class.

McCodeGen.exe

McCodeGen application reads the mcgen file, extracts metamodel and output template and generates output text file.

McCodeGen.exe -mcgen:mcgenFile -out:outputFile

 

Parameter

Description

mcgenFile

The metamodel file

outputFile

The output file

Using mcgen file to create typed entity object

McCodeGen application can generate C# class from mcgen file. Typed entity object class is very similar to the untyped class EntityObject, but includes properties mapped to column values and column name constant string.

Mcgen file should include XML:

<?xml version="1.0" encoding="utf-8" ?>
<mcgen xmlns="mediachase.codegen.config" extension="cs" template="Templates\BusinessFoundationEntityObject.aspx">
<EntityObject>
<ConnectionString> Data Source=(local);Initial Catalog=TestDB;User ID=sa;Password=; </ConnectionString>
<MetaClass>Book</MetaClass>
<Params>
<add key="Namespace" value="Test.MetaClass"/>
</Params>
</EntityObject>
</mcgen>

Parameter

Description

ConnectionString

The connection string

MetaClass

The name of meta class

Namespace

The typed row C# class namespace

You should paste your connection string, meta class name and declare output class namespace, then execute McCodeGen from command line.

McCodeGen.exe -mcgen:BookEntity.mcgen -out:BookEntity.cs

You can add typed entity object class to your .NET project.

Typed entity object registration

After you have created a typed entity object, you must register it in the Application. You should create a new handler based on EntityObjectDefaultRequestHandler and override CreateEntityObject method. The CreateEntityObject method should create and return typed entity object.

After you have created a handler, you should register it.

Visual Studio Integration

McCodeGen should be installed.

The McCodeGen application can be integrated to Visual Studio 2008. You can add mcgen file to Visual Studio Project.

View the properties for your mcgen file (in our case, a CategoryRow.mcgen). The 'Custom Tool' field should be blank. Enter the name ”McCodeGenerator”.

The tool should run automatically. Check to make sure the output was created by opening the Solution Explorer.

Execute Methods Through Web Service

BF allows executing entity object methods through Web Service.

MetaObject class

MetaObject class allows low-level access to entity object persistent storage. Default handler uses MetaObject to load, save entity object to persistent storage. You can use MetaObject to call low-level get, update or delete methods.

MetaObject extensions

MetaObject extension allows capturing meta object events. MetaObject extenstion is registered in the meta class.

To create a custom MetaObject extension, you create a class that implements the IMetaObjectExtension interface. You should implement Init, PreSave, Save, PreDelete, Delete and Clone methods.

You can use ready to use BaseMetaObjectExtension class as base class for your extension.

After you have created a custom extension class, you must register it in the MetaClass. You should add MetaObjectExtensionInfo object to MetaClass.Extensions collection, passing extension name, extension type and activation type. This enables extension to receive metaobject events.

// Add MetaObject Extension
metaClass.Extensions.Add(new MetaObjectExtensionInfo(HistoryManager.ModuleName, AssemblyUtil.GetTypeString(typeof(HistoryExtension)), MetaObjectExtensionActivationType.OnSave));

 

A metamodel can be modified in only Design mode. You should open edit scope.

Extension supports several activation types:

Activation type allows optimizing performance.

Triggers

A trigger is procedural code that is automatically executed in response to certain events on a particular meta object in a persistent storage. The trigger is mostly used for keeping the integrity of the information on the persistent storage. For example, when a new meta object is added to the employees meta class, new meta object should be created also in the meta class of the taxes, vacations, and salaries.

Call AddTrigger of TriggerManager class to add custom trigger.

Call RemoveTrigger of TriggerManager class to remove custom trigger.

Trigger can be registered on meta object create, update and delete event.

 


Last updated: 2011-05-17 | Copyright © EPiServer AB | Send feedback to us