Click here to Skip to main content
Click here to Skip to main content

ObjectLounge - An Object-Oriented Database Framework

By , 30 Jul 2009
 
ObjectLounge Logo

Introduction

The TechNewLogic ObjectLounge framework is an open source framework that helps you developing business applications. It is a host for object oriented domain models that manages concurrency, transactions, validation and persistence.

You can get an impression on how to work with the framework and what it does if you have a look at the small-step tutorial below.

You want to know more? Go to http://objectlounge.technewlogic.de.

Prerequisites

You will need the Microsoft SQL Server CE 3.5 SP1 Runtime

Background

Today, people automatically use a relational database if they want to build a business application. But:

Databases come from a long time ago in a galaxy far, far away...

In this time,

  • RAM was very small and very expensive,
  • Computers were pretty slow,
  • Programming was something very technnical and abstractions like OO had not been invented yet.

Thus, the database vendors optimized their products on scaling, memory sufficiency, etc. But is that really needed in a middle sized "as usual" business application? We think: No, Sir. Reasons:

  • 8 GB of RAM cost only some bucks.
  • Even desktop computers run at several GHz and have multiple cores.
  • Software is everywhere and has to change very fast and be very flexible.
  • The amount of data in a middle sized business application is usually less then the amount of memory on a well equipped machine.

Object Orientation is awesome and cool and smooth. But as soon as you hit the database, it becomes not so cool and smooth anymore. We define relational tables, but we want to have hierarchical classes. We write stored procedures, functions and triggers, but we want to encapsulate our logic in objects with methods, properties and events. The point is: Even with modern ORMs we have to go through a lot of hassle to connect our application to a database. What we get for that is a lot of features we don't need. So the question is:

Why should we use a data base at all?

The only thing we need is a store where we can persist our entities and a framework that makes this aspect as transparent as possible. But what about the "useful" features of a database which are defined by the ACID criteria, which are basically focused on concurrency? In a database, we can run transactions, we can roll them back and we have isolation between transactions. If we want to get rid of our database, we need a framework that handles transactions with rollback and isolation on our domain model - fine! With ObjectLounge, you can do all these things, too - without a database!

Tutorial

The Example is focused on developing a standalone (client-only) WPF application that manages a blog system with Authors, Blogs and Posts (inspired by the "Getting Started" of Castle's ActiveRecord). Of course it can also be used in services, where the transaction / concurrency handling of ObjectLounge come into play.

The goal of the Sample is to give you an idea of

  • How should domain classes look like.
  • How we can use abstractions like Aggregation and Composition.
  • How to work with the domain model (querying data, manipulating data, transactions and persistence).

What this Sample does not show:

  • Validation
  • Complex Business Logic
  • Concurency

Setup your project

For this sample you start developing with ObjectLounge by doing the following:

  • Create a new "WPF Application" project in Visual Studio 2008 and name it "GettingStartedDemo".
  • Add a reference to the assembly Technewlogic.ObjectLounge.dll.

Creating the Domain Model

Now, create a folder in the project called "DomainModel" and add the following new classes:

  • Author
  • Blog
  • PostCategory
  • Post
  • DomainModelContext

The first 4 classes are called "entity classes" and contain the business logic of our application. Together, they form the domain model of the sample application. The DomainModelContext class holds lists of the 4 entity classes (either read-only or read/write).

The final domain model will look like this:

Domain Model

Now, we will look at the classes in detail and describe how they interact with the ObjectLounge framework. You may copy the code regions into your classes.

Author class

using System;
using System.ComponentModel;
using Technewlogic.ObjectLounge;

namespace GettingStartedDemo.DomainModel
{
    [Identity("_id")]
    public class Author : INotifyPropertyChanged
    {
        protected Guid _id = Guid.NewGuid();

        private string _name = default(string);
        public virtual string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                OnPropertyChanged("Name");
            }
        }

        private string _password = default(string);
        public virtual string Password
        {
            get { return _password; }
            set
            {
                _password = value;
                OnPropertyChanged("Password");
            }
        }

        private Blog _blog;
        [Composition]
        public virtual Blog Blog
        {
            get { return _blog; }
            set
            {
                _blog = value;
                OnPropertyChanged("Blog");
            }
        }

        #region INotifyPropertyChanged Members

        ...

        #endregion
    }
}
Simple POCO
As you can see, the Author class is a simple POCO (plain old CLR object). This means you don't have to implement ObjectLounge-specific interfaces or inherit a base class if you want to use ObjectLounge. The implementation of INotifyPropertyChanged is just for databinding reasons in WPF.
IdentityAttribute - The Entity's Identity
Each ObjectLounge entity class needs the IdentityAttribute that specifies the name of the field that should be used to maintain the object's identity. Identity is also important for the ObjectLounge reference management system which relies on identity fields inside the entity (this is one point where the persistence aspect of the framework is not transparent to the framework user).
Virtual Properties
Have a look at the Name or the Password properties: They are marked as virtual! This is mandatory because internally, the ObjectLounge framework generates proxies of your domain classes by inheriting them at runtime (this is important for almost all the subsystems like transaction management, change tracking and validation).
CompositionAttribute - Manage a Child Reference
There's another property: The Blog property, which is a pointer to a blog entity. It is marked with the CompositionAttribute. In ObjectLounge, references (either single or list references) are modeled by using compositions and aggregations. Compositions are the "owner" of their children. That means, if the parent entity is deleted, all children are also deleted from the store. There can only be ONE class having a composition to another class. In this case: If the Author class defines a composition to the Blog class, no other class could have a composition to the Blog class, too.

Blog class

using System;
using System.Collections.Generic;
using System.ComponentModel;
using Technewlogic.ObjectLounge;

namespace GettingStartedDemo.DomainModel
{
    [Identity("_id")]
    public class Blog : INotifyPropertyChanged
    {
        protected Guid _id = Guid.NewGuid();

        private string _name = default(string);
        public virtual string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                OnPropertyChanged("Name");
            }
        }

        [MasterRef]
        public virtual Author Author { get; protected set; }

        [Composition]
        public virtual IList<Post> Posts { get; protected set; }

        #region INotifyPropertyChanged Members

        ...

        #endregion
    }
}
MasterRefAttribute - Backpointer to the Parent
In object oriented domain models, you can navigate through your object graph with a lot of comfort. In our case, we could pick ourself an author and navigate to it's blog using the Blog property. What if we want to navigate backwards - from the Blog to it's parent Author? For this reason, you can specify a backpointer property which is decorated by the MasterRefAttribute. The framework will automatically set the property when you change the parent's composition.
CompositionAttribute - Manage Child Collections
Additionally, we have - analog to the Author class - a composition to the Post class. But here, we don't have a simple link, but a whole list of posts. When we use this class later, the framework will assign the appropriate collection to the IList property.

PostCategory class

using System;
using System.ComponentModel;
using Technewlogic.ObjectLounge;

namespace GettingStartedDemo.DomainModel
{
    [Identity("_id")]
    public class PostCategory : INotifyPropertyChanged
    {
        protected Guid _id = Guid.NewGuid();

        private string _name = default(string);
        public virtual string Name
        ...
    }
}

Pretty simple class :)

Post class

using System;
using System.ComponentModel;
using Technewlogic.ObjectLounge;

namespace GettingStartedDemo.DomainModel
{
    [Identity("_id")]
    public class Post : INotifyPropertyChanged
    {
        public Post()
        {
            CreationDate = DateTime.Now;
        }

        protected Guid _id = Guid.NewGuid();

        private string _heading = default(string);
        public virtual string Heading
        ...

        private string _content = default(string);
        public virtual string Content
        ...

        private DateTime _creationDate = default(DateTime);
        public virtual DateTime CreationDate
        ...

        private bool _isPublished = default(bool);
        public virtual bool IsPublished
        ...

        [MasterRef]
        public virtual Blog Blog { get; protected set; }

        [Aggregation]
        public virtual PostCategory PostCategory { get; set; }

        ...
    }
}
AggregationAttribute - Weak References to Entities
As we have seen before, Posts are composed ("owned") by the Blog class. But there is another interesting fact here, which is: The Post needs a PostCategory. But not in the way that it is really the "owner" of it. We just want to point to an existing PostCategory - not more. So the character of the PostCategory is more like that of a master data. This is achieved by using an AggregationAttribute over the PostCategory property.

DomainModelContext class

using System.Collections.Generic;
using Technewlogic.ObjectLounge;

namespace GettingStartedDemo.DomainModel
{
    public class DomainModelContext
    {
        [EntityCollection]
        public IList<Author> Authors
        {
            get; private set;
        }

        [EntityCollection]
        public IEnumerable<Blog> Blogs
        {
            get; private set;
        }

        [EntityCollection]
        public IEnumerable<Post> Posts
        {
            get; private set;
        }

        [EntityCollection]
        public IList<PostCategory> PostCategorys
        {
            get; private set;
        }
    }
}

Last, but not least: We need a class that gives us access to all the entities in the system, which we call "Context".

EntityCollectionAttribute
The EntityCollectionAttribute tells the ObjectLounge framework which entity classes our domain model contains.
Top-Level Classes
Top-Level classes have no "owner", means: No other class holds has composition to it. Thus we need something where we can insert new entities or delete old ones, by using the IList<T> properties in the context.
Non Top-Level Classes
Non Top-Level classes can only be read through IEnumerable<T> properties in the context. Write access is provided via the compositions in the entity's parent classes.

Working with the Domain Model

In the following section, we will have a look on how to work with our domain model, i.e. modifying and querying data. Most of the interesting are done in the sample application's MainWindow class.

Startup

using System;
using System.ComponentModel;
using Technewlogic.ObjectLounge;

public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeObjectLounge();
        
        ...
    }

    private Engine<DomainModelContext> _engine;
    public DomainModelContext Context { get; private set; }

    private void InitializeObjectLounge()
    {
        // Create a new Context.
        Context = new DomainModelContext();

        // Start the framework (the database will be created
        // automatically if it doesn't exist).
        _engine = EngineFactory.CreateEngine("store.sdf", Context);

        // Check and create the demo user if not present.
        if (!Context.Authors.Any(it => it.Name == "Demo"))
        {
            // Execute an atomic transaction and store the "demo" user.
            _engine.ExecuteTransaction(() =>
            {
                // We must use the factory method of the engine
                // to create new entities.
                var demoAuthor = _engine.CreateInstance<Author>();
                demoAuthor.Name = "Demo";
                demoAuthor.Password = "Demo123";
                Context.Authors.Add(demoAuthor);
            });
        }
    }

    ...
    
}
Context Creation
We have to supply the framework with an instance of our DomainModelContext. When we start the engine, all the entity collections will be injected automatically.
Gentlemen, Start Your Engines!
The framework is started using the EngineFactory. You can either supply a path to the database file. In that case, ObjectLounge uses it's out-of-the-box SQL-Server CE backend. Alternatively, you can provide your own backend implementation. In that case, the data access is completely in your hands.
When the framework starts, a lot of things happen. The framework checks that your domain model (the entity classes and the context) meet the constraints described above. After this check was successful, the framework loads the entities from the store and builds up the provided context. Now, we can start working!
Execute an Atomic Transaction
If the database is created the first time, no data is present at all. Thus, we create a "demo" user we can use for the Login form to login to the application.
You can use LINQ to query data from the context at any time. If you want to modify properties or add / remove entities, you have to do this inside of a transaction. Transactions in ObjectLounge are thread-bound, which means there can be only one running transaction per thread. Thus our sample application is a single-threaded client application, this is not so important here.
There are two ways you can execute a transaction:
  • Use the ExecuteTransaction method of the engine. The provided delegate is executed and committed, or rolled back if an exception occured.
  • Use the BeginTransaction method of the engine to control the transaction flow (which is not used in this sample).
Transaction Behavior
All changes that are made while a transaction is running are immediately visible in your entities if you access them from the transaction which modified the entities (as you would expect from normal objects). If you decide in any point of time that you don't want the changes, you can just rollback the changes and it is as if nothing ever happened (you don't have to reload or rebuild your entities in any way). Only if a transaction is committed, the changes are actually persisted to the data store.
Creating new Entity Instances
To enable the ObjectLounge framework managing entities for you, you have to let it create new entities for you. So, instead of using the new operator, you have to use the CreateInstance<T> factory method of the engine. This requires a parameterless (default) constructor in the entity classes.

DataBinding

We have simple POCOs, so we can bind the entities in our context to UI elements. Note that all collections in ObjectLounge implement INotifyCollectionChanged, which is good for databinding to ItemsControl, ListBox, etc.

<Window x:Class="GettingStartedDemo.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:domainModel="clr-namespace:GettingStartedDemo.DomainModel"
    x:Name="mainWindow">

    <ListBox ItemsSource="{Binding ElementName=mainWindow, Path=Context.PostCategorys}">
            
        ...

Summary

We have learned some important things when we work with ObjectLounge:

  • There is a domain model that consists of entity classes and a context class.
  • The context class has list properties of the entity classes which are marked with the EntityCollectionAttribute.
  • Entity classes are POCOs.
  • The relationships between entities are modeled using the CompositionAttribute, the AggregationAttribute, and the MasterRefAttribute.
  • The management of the ObjectLounge framework during runtime is done using the Engine.
  • An engine can be created using the EngineFactory method.
  • Instances are created using the CreateInstance method of the engine.
  • Reading and querying data is always possible.
  • Data can only be modified within a transaction.

History

2009-07-20: Article Posted.
2009-07-30: The list property of the Blog class marked as virtual / MasterRef setters marked as protected.

License

This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)

About the Author

Ronald Schlenker
Software Developer (Senior) www.technewlogic.de
Germany Germany
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralArkeos Factory [modified]memberMember 75483730-Jul-09 4:22 
Hi, Code Project Team.
 

please view "Arkeos Factory" in www.multiclicksistemas.net (Spanish only for now).
 
"Arkeos Factory" generate code for "Arkeos Framework". Arkeos factory is based in Sample paradigm:
 
<big>blg.Post:</big>
{  $Post$Id! 12345
   Blog_: MeBlog
   Content_: This is y blog bla bla ............
           .............      
   CreationDate: July 27/2009
   Heading: My title.
   isPublished_: Yes       isActivate: Yes  
 
   <big>blg.Categories:</big> 
   {[NameCategories!]
    [Technologies] 
    
   }
             
} 
 
-----------------------------------------
--- DDL : Please don't handly modifying 
--- Create Table blg_Post
-----------------------------------------
if Not exists (select * from sysusers where name = 'blg' ) then
   grant connect, group, dba to blg
end if 
go
if exists (select * from sys.syscolumns where tname = 'Post' and creator = 'blg') then
   drop table "blg"."Post"
end if
go
Create Table "blg"."Post"
(
      compania Integer Not null,
      PostId Integer not Null , 
      BlogPost Varchar(6) not Null , 
      ContentPost Text not Null , 
      CreationDate Date not Null , 
      Heading Varchar(14) not Null , 
      isPublishedPost byte not Null  default 0, 
      isActivate byte not Null  default 0, 
      
      fecha_impresion datetime null default timestamp,
      fecha_reimpresion datetime null default timestamp,
     fuente varchar(32) null default 'CP1865', 
      fecha_computador datetime null default timestamp,
      usuario varchar(32) null default last user,
      secuencia Integer default autoincrement,
  Primary Key (Compania, PostId)
)
go
CREATE TRIGGER log_blg_Post  AFTER INSERT, DELETE, UPDATE 
 ORDER 100 ON  "blg"."Post" 
  REFERENCING OLD AS deleted NEW AS inserted  
BEGIN 
	insert into DBA.auditorias ( 
	tabla , 
	appinfo , 
	nuevoPKey , 
	ViejoPkey , 
	nuevoXml , 
	ViejoXml ) 
     values ( 
    '"blg"."post"',  
    CONNECTION_PROPERTY ( 'AppInfo' ),  
    (select  compania, postid  from inserted as "key" for xml auto), 
    (select  compania, postid from deleted as "key" for xml auto), 
    (select inserted.* from inserted for xml auto, elements), 
    (select deleted.* from deleted for xml auto, elements) 
    ) 
END 
go
 
-----------------------------------------
--- DDL : Please don't handly modifying 
--- Create Table blg_Categories
-----------------------------------------
if Not exists (select * from sysusers where name = 'blg' ) then
   grant connect, group, dba to blg
end if 
go
if exists (select * from sys.syscolumns where tname = 'Categories' and creator = 'blg') then
   drop table "blg"."Categories"
end if
go
Create Table "blg"."Categories"
(
      compania Integer Not null,
      PostId Integer not Null , 
      NameCategories Varchar(12) not Null , 
     fuente varchar(32) null default 'CP1865', 
      fecha_computador datetime null default timestamp,
      usuario varchar(32) null default last user,
      secuencia Integer default autoincrement,
  Primary Key (Compania, PostId, NameCategories)
)
go
alter table "blg"."Categories"
       ADD FOREIGN KEY fkey_blg_Categories_blg_Post(Compania, PostId)
        REFERENCES blg.Post( Compania, PostId)
        CHECK ON COMMIT 
go
CREATE TRIGGER log_blg_Categories  AFTER INSERT, DELETE, UPDATE 
 ORDER 100 ON  "blg"."Categories" 
  REFERENCING OLD AS deleted NEW AS inserted  
BEGIN 
	insert into DBA.auditorias ( 
	tabla , 
	appinfo , 
	nuevoPKey , 
	ViejoPkey , 
	nuevoXml , 
	ViejoXml ) 
     values ( 
    '"blg"."categories"',  
    CONNECTION_PROPERTY ( 'AppInfo' ),  
    (select  compania, postid, namecategories  from inserted as "key" for xml auto), 
    (select  compania, postid, namecategories from deleted as "key" for xml auto), 
    (select inserted.* from inserted for xml auto, elements), 
    (select deleted.* from deleted for xml auto, elements) 
    ) 
END 
go
 

with in code "Arkeos Factory" generate SQL Script for create tables, Referential Integrity, Visual Interface. Audit page, Inital Help Page, Auto Test,. Other simple language make easy your life for implement Bussines rules,
 
Please contactme for more information adrua@multiclicksistemas.net
 
Adalberto Raul Rua Aguirre
adrua@multiclicksistemas.net Blush | :O
 
modified on Thursday, July 30, 2009 10:29 AM

GeneralMy vote of 1memberGraham Downs29-Jul-09 1:09 
I don't agree with your reasons. Just because RAM is plentiful and processors are fast does not mean we should forget what we've learnt about efficient coding and efficient design. 4 bytes or storage memory has exactly the same effect, whether your total available RAM is 2GB or 640k.
 
Besides, I don't like code generation tools. I like to know that (as far as humanly possible) that I wrote every line of code in my application - or at least know exactly what it does and why it's needed.
GeneralRe: My vote of 1 [modified]memberbilo8129-Jul-09 12:46 
You do have some good points but in some cases code generation is necessary...I'm sure you came across to the old ADO.NET typed dataset...or you can think of the designer code created behind a form or a control.
 
Any ORMs out there usually benefit from the use of code generation, and partial class are there also I'm sure for this reason.
 
I do agree however, that the article and the "database" application discussed here are more useful from the point of view of an embedded "OO Database".

I haven't check the code to be honest, but I appreciate the effort of putting this article together and I don't think it deserve such a low score, IMHO of course. I actually think it is a good article.
Keep up the good work.
 
modified on Thursday, July 30, 2009 8:15 AM

GeneralRe: My vote of 1memberRonald Schlenker29-Jul-09 23:09 
Hey Bilo,
 
bilo81 wrote:
the article and the "database" application discussed here are more useful from the point of view of an embedded "OO Database".

 
Exactly. Actually, as it is now, ObjectLounge is not a database. It is a framework that handles the main features of a database (ACID). Only the "D" (durability) is not handled directly by the framework, and that's also the reason why it's not an ORM. It just triggers a layer that we call SyncProvider, which can do anything he wants, even using NHibernate or other ORMs. The SyncProvider simply gets the updated, inserted and deleted entities, and he has to the work then. By default, we use a very very simple SyncProvider that just dumps the serialized entities and their relations in a file.
 
Possible UseCases could be:
* You have a standalone client app and use ObjectLounge as an "embedded db".
* You want to have something like a modern DB: You can wrap your ObjectLounge domain model with a service layer to make data and functionalities available to others.
 
In future, we plan to implement a small hosting environment for domain models. This environment can be configured so that it automatically exposes Get and Set service methods for your model. Maybe this is then more like a DB (we are inspired a little bit of things like CouchDB, which just exposes a REST api).
 
Have a nice day!
 
P.S.: Thanks for the back-up Smile | :)
GeneralRe: My vote of 1memberbilo8130-Jul-09 2:18 
You are welcome, you did a very good job!
 
Regards
GeneralRe: My vote of 1memberRonald Schlenker29-Jul-09 22:52 
Graham Downs wrote:
4 bytes or storage memory has exactly the same effect, whether your total available RAM is 2GB or 640k.

I think this statement is not correct. I try to explain what we meant with the "Ram" thing: If you look back over 30 years, Smalltalk was invented, and it was revolutionary. It was dynamic, had a dynamic type system that could be reflected, you could do refactorings, it had relied on a virtual machine and it had a garbage collector. I was extremely productive for developing business apps due to setting the focus on abstract modeling and not on technical stuff. But it didn't establish in a wide range, because it was indeed a big problem having all these things running on the hardware those days. Graham, in a today's business application, if you care about having or not having 4 bytes, you waste the customer's money.
Graham Downs wrote:
Besides, I don't like code generation tools.

Code generation / code modification is necessary if you want to express a pattern which is expressed not on a concrete level, but on a meta level (e.g. a pattern that adresses the type system) and that is not built in your programming language. Code generation is one way to achieve that, there are a lot of other ways to do that like code modification in dynamic languages, post compilers etc.
Graham Downs wrote:
I like to know that (as far as humanly possible) that I wrote every line of code in my application

Why do you use frameworks at all? You use the .Net framework library and the CLR without having written the source code.
Graham Downs wrote:
or at least know exactly what it does and why it's needed.

Why it's needed in general, I explain below. Maybe I can tell you a little bit about what we do:
* When the framework starts, we generate a runtime proxy for each of your entity classes.
* The proxy overwrites your property getters and setters.
* This is necessary for many framework's concerns. For example, it handles isolation aspects, rollback behavior (backing up property values in a running transaction), track changes (which is needed for validation and persistence) and other things.
 
Instead of using dynamic approaches like code generation, there is another way: Conventions! These conventions have to be implemented by the user of a framework. For example, if you want to use a framework, you have to implement certain interfaces, inform the framework when something happens in your code and so on. This means:
* a lot of extra work for the framework user.
* it is less robust, because it's not always possible for the framework to check if you fulfilled all conventions.
* You have to repeat yourself because of missing abstractions.
QuestionCan you do two-way data binding?membermyker28-Jul-09 17:58 
Great article! Love it! I re-created your demo using the sample code, and as an experiment, tried to bind the IList Authors property in the DomainModelContext to a Data Grid in WPF (using the data grid in the WPF toolkit). This worked well once I defined the columns.
 
The trouble arises when I double-click an item in the datagrid to edit it. I get the "'EditItem' is not allowed for this view" exception, which essentially means that WPF views the collection as Read Only. I also attempted to use BeginTransaction in the BeginningEdit event of the grid, and Commit transaction on the CellEndEditing event so I could wrap the edit into a transaction. I still received the exception.
 
Is there support for two-way binding?
AnswerRe: Can you do two-way data binding?memberRonald Schlenker28-Jul-09 19:54 
Hey myker!
 
Can you send me the sample app via email so I can have a look?
GeneralRe: Can you do two-way data binding?memberRonald Schlenker28-Jul-09 22:26 
Hey,
 
I invesstigated a little bit about the WPF-Toolkit Datagrid. I found this link:
 
http://forum.invist.net/showthread.php?p=1854[^]
 
It seems that the Edit-In-Place functionslities are only available if you bind to a List. The ObjectLounge collections implement IList, which seems not to be enough (but should be enough). In addition, it seems strange that if you bind to a simple IEnumerable, the grid won't even allow you the Edit functionality (edit is not add). You could wrap the Context-Collections in a List property of your ViewModel / CodeBehind. That seemed to work.
 
What I can tell you about the ObjectLounge collections is: Writable collections implement INotifyCollectionChanged and IList, so binding is possible, and we do that with "normal" WPF components.
 
Right now, we are developing a CRUD tool that is highly configurable. When it's ready, we will post it.
 
Cheers!
GeneralDirty ModelmemberGonzalo Brusella28-Jul-09 6:57 
Nice Article!! (I sense some DB4O inspitation)
 
Just one philosophical issue: The problem with this kind of approach is that you always get a dirty model, because you always end with a decorated model. Is like using Castle's Active Record[^].
 
This [anti-?]pattern mixes 2 different layer of the application, the Domain Model and the Persistence. A mapping structure a la NHibernate (an XML file or any other form of defining the relation between the object and how is persisted) allows you to grab your model and use it in another development. It also keeps the separation of responsibilities.
 
Just that.
 
I'm on a Fuzzy State: Between 0 an 1

GeneralRe: Dirty Modelmemberkraemersoftware.com2-Aug-09 22:48 
Thanks for your remarks. My view on the subject is the following (I am one of the co-developers of ObjectLounge).
 
You are right when you say that by adding attributes to your domain classes you might end up with a lot of them for different purposes (persistence, validation, security etc.) but after all that's the idea behind metadata: If e.g. a property should be persisted and verified and security checked and... why not just say so at the point of definition of the property? If you rather split out this data in separate files, your domain model class stays smaller. On the other hand it becomes less evident which metadata belongs to it, because you have to find all metadata references to it in various files. This could be especially difficult if the metadata is expressed in XML (like Hibernate mappings) because there is no help via the .Net type system (think "Find all references" in Visual Studio).
 
A compromise might be to use attributes (for better correlation between metadata and code) but to include only a minimal set of data in them and refer to external configuration data if it grows to big sizes (to keep the domain class small).
 
In the end, the problem is rather nonexistent right now since the attributes are few and mostly without additional configuration data.
QuestionMultiUser?membergeorani20-Jul-09 7:19 
Can I use this in a multiuser environment?
If yes, How can I handle concurrency? How many users it will support?

How can I ensure that one property value is unique?
 
Can I use this with a big size File?
What you could say about its performance?
AnswerRe: MultiUser? [modified]memberRonald Schlenker20-Jul-09 7:48 
Hi Georani,
 
very good questions. On my homepage, there are maybe some short answers, too.
 
1) Can I use this in a multiuser environment?
Yes. It's possible to have multiple transactions running. Transactions are thread-bound, means: One transaction per accessing thread.
Reading: "Read-Committed" Stategy, means: Every transaction has it's own isolated state, so you read only the committed data OR the data you changes inside "your" transaction.
As soon as you try to write properties, the framework automatically queues the write requests.
 
2) How can I ensure that one property value is unique?
Constraints like these (or other constraints) are managed by validation rules. I did not yet explain validation, but I will post an article as soon as possible. Short example:
 
public class Author : INotifyPropertyChanged
{
	...
	
	[ApplicationContext]
	public virtual DomainModelContext Context { get; set; }
 
	[ValidationRule]
	protected ValidationResult ValidateNameUnique()
	{
		if (Context.Authors != null)
		{
			var notUnique = Context.Authors
				.Where(it => it != this)
				.Any(it => it.Name == this.Name);
 
			if (notUnique)
				return ValidationResult.Failure("The Name must be unique.");
			else
				return ValidationResult.Success();
		}
		else
			return ValidationResult.Success();
	}
	
	...
	
}
 
You see here that you can access your domain model context by creating a property and decorating it with the <code>ApplicationContext</code> attribute. The validation method is automatically invoked when a transaction is committed. If a rule fails, a <code>ValidationException</code> is thrown that you have to catch. In this way, you can model any constraint you want. In the future, we plan to have built-in constraints that you can just put above your properties for the most common things.
 
3) Can I use this with a big size File? / What you could say about its performance?
We have some applications already running in production environments, but an older version of ObjectLounge. There, performance is good, because we don't have to fetch data all the time from the database, and we do mostly in-memory querying. But we have to run stress tests with this version, thus we changed a lot. If you would like to try out something, please let me know your experiences.
 
Cheers!
 
Ronald
 
modified on Monday, July 20, 2009 1:56 PM

QuestionRe: MultiUser?membergeorani20-Jul-09 8:36 
Thank you.
 
More questions:
 
Can I use it in a shared folder like MS-Access, and many concurrent users?
 
Do you plan add server capability?
 
Is there any mechanism to ensure database integrity?
 
Is there any mechanism to repair a database?
AnswerRe: MultiUser?memberRonald Schlenker20-Jul-09 22:51 
  • You cannot share the storags file. There can only be ony process accessing it.
  • You can make your domain model accessible for other processes by wrapping it with a service layer (we use usually WCF).
  • We plan to add server capability. This will be some kind of process that hosts the domain model and exposes automatically generated Get / Set methods via WCF.
  • The Framework ensures referencial integrity of your domain model and ensures that all your validation constraints are fulfilled when you commit. In other words: If your domain model is in a consistent state before a transaction, it will be in a concistent state after a transaction.
  • In which way should it be broken?

QuestionRe: MultiUser?membergeorani21-Jul-09 2:02 
Thank you.
 
Ronald Schlenker wrote:
In which way should it be broken?

 
When I tell about "database integrity" and "repair database", I was telling about file corrupting.
 
This can happens when hardware fails.
 
Example: MS-Access has an option "compact and repair database"
AnswerRe: MultiUser?memberRonald Schlenker21-Jul-09 2:07 
Ah, ok. Not I understand what you mean. The storage file created is a simple SQL-CE database (with only one table in which we dump the entity's XML). We don't use anything of the database functionality, no schema, no indexing, no constraints or relations, because all this is managed by the framework. What we needed was just a file based store.
 
So: You can use all the functionalitites that are provided by SQL-CE (maybe also repair if the file is corrupted).
QuestionRe: MultiUser?membergeorani21-Jul-09 4:31 
Thank you.
Now I understand.
 
1- Do you have plans to use SQL Server Express instead of SQL-CE? If yes the database could be shared across many machines. If not, why?
2- Have you heard about http://persistor.net/[^]? It seems to be very similar to your project, but it is a very expensive product.
AnswerRe: MultiUser?memberRonald Schlenker21-Jul-09 6:01 
1) No plans richt now. If you would like to use ObjectLounge, we could write you one (it would be pretty similar to the SQL-CE provider we already have). But remember: There would just be one table (with one row per entity), in which we would dump the serialized XML. Technically, it would also be possible that the sync provider creates more complex schemata mapping the domain model to an ER model, but for us this would be too much work for now.
 
2) No, I didn't know that thing. But it's true, sounds pretty similar to what we have, also from the idea snd the philosophy behind it.
 
Cheers!
 
Ronald
QuestionSupported Databases?memberCreF20-Jul-09 4:19 
Hi Ronald,
first of all your article is very interesting. I think you'll have my vote of 4...
 
I have just only a question: which are the supported databases and how to build up the connection string?
 
Thanks in advance
the CreF Smile | :)
 
the CreF

AnswerRe: Supported Databases?memberRonald Schlenker20-Jul-09 4:33 
Hey, thanks CreF!
 
To give a short answer: There is no need for a database.
 
First of all, not to get me wrong: This framework is not an ORM. If you use the framework, you are actually developing a customized database, and there's usually no need to connect to a sql database or something. By default, you just have to provide a file name, and the framework creates a "store" for you in the filesystem (little bit like in db4o).
 
If that doesn't fit, you can implement what we call "SyncProvider". When the framework wants to persist entities, your implementation gets a changeset with inserted, deleted and updated entities. You can use and mapper or data access logic that is necessary to dump the entities in your prefered store (for example a relational database).
 
Hope I could help you!
 
Cheers Smile | :)
 
Ronald

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130617.1 | Last Updated 30 Jul 2009
Article Copyright 2009 by Ronald Schlenker
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid