Friday, December 4, 2009

Eloquera at work

This post is the beginning of the series about development of applications using Eloquera database.  We are going to cover various topics: how to create databases, what is the best way to write applications with Eloquera, both for desktop and web applications.

We are not focussing only on the database part of the software, but would to demonstrate how Eloquera database makes it easy to design and develop applications, even if the code related to data access is encapsulated into separate logical modules.

There is a simple application that we are going to develop, called Messenger. I have done the basic things, but it is not complete yet.

You can download the source code for the Messenger application using this link. It is a simple console application allowing ‘users’ to send messages to each other.

The application is written in C# using Visual Studio 2008, and requires .NET Framework 3.5. Here you can download Eloquera database (version 2.5 beta) we have used to create the application. As the database is in the beta stage, the documentation is not completely ready, but I hope the examples in the Messenger app will be extremely easy to understand, and quite self-descriptive.

All right, let’s start now.

 

Messenger application – database installation script

 

First, let’s get the app running on your machine.

Let’s run a database script. That is a simple console application called DbInstall, and included into Messenger solution.

At the first place, why do we need any database script, if Eloquera database can easily create databases and add types in the main application? There are many reasons for that, e.g., you can run queries without prior checking if the type is present in the database (if you run the query against the type absent in the database, you will get an exception). The most important thing is that in the future versions of Eloquera only database administrators will be able to create databases and register types, while other authenticated users will be able to add, modify and query data only.

 

Registering types

What is the database script for Eloquera DB?

Just a few lines like this:

 
  // Now we can create the database.
  db.CreateDatabase(MessengerDbName);
  db.OpenDatabase(MessengerDbName);
 
  // And register all the types.
  db.RegisterType(typeof(Eloquera.Messenger.Objects.User));
  db.RegisterType(typeof(Eloquera.Messenger.Objects.Message));
  db.RegisterType(typeof(Eloquera.Messenger.Objects.Subscription));

Create a database, open it, register the types you want to use, and that’s it.

Registering types is a good thing, because you don’t have to worry about running queries against such types anymore.

Adding data

Our installation script does more than that, actually. We are adding some sample data into the newly created database as well.

 
  // Add sample users
  var userSam = new Eloquera.Messenger.Objects.User() { Name = "Sam"};
  var userWonka = new Eloquera.Messenger.Objects.User() { Name = "Willy Wonka" };
  var userMacquarie = new Eloquera.Messenger.Objects.User() { Name = "Lachlan Macquarie" };
  var userCervantes = new Eloquera.Messenger.Objects.User() { Name = "Miguel de Cervantes de Saavedra" };

 

Adding data may be helpful for testing, or just to initialise basic objects like an initial user account for a web application, e.g., an account for the administrator with the default password.

Changing definitions

Software development is about changing the code all the time. Adding new methods to the classes registered in the database, won’t break anything. But adding new fields and properties (with no [Ignore] attribute) to such classes will result in the EloqueraException exception with the message “Definition in database is different to one on the client”, thrown by Eloquera client. Eloquera database performs the integrity checks of your data, and prevents data loss or misinterpretations when class definition changes.

Because your database script registers all the types all over again, so, if you have got your classes changed during development, just delete the old database and recreate it using this script. And this task can be performed by the script:

 
    // -f flags denotes forcible re-creation of the database.
    if (args.Length > 0 && args[0] == "-f")
    {
        try
        {
            db.DeleteDatabase(MessengerDbName, true);
        }
        catch (Exception e)
        {
            Console.WriteLine("Cannot delete the database file. The error occured:\n{0}", e.Message);
            return;
        }
    }

The script checks the command-line parameter, and if the -f flag is specified, tries to remove the database.

This code uses DeleteDatabase() method introduced in Eloquera DB 2.5. The first parameter specifies the name of the database to be deleted. The second parameter forces the database drop all open connections, and then deletes the database.

That’s all about the database installation script.

Monday, June 8, 2009

Eloquera Database - the web-oriented client/server object database for .NET

Have you ever thought about having a database that you can write your objects directly, and use SQL for retrieving them back?

// Open connection to the server.
using (DB db = new DB("server=localhost;options=none;"))
{
// Open the database.
db.OpenDatabase("Cinemas");

// Create the object we would like to work with.
Cinema cinema = new Cinema() {
Location = "Sydney",
OpenDates = new DateTime[] { new DateTime(2003, 12, 10), new DateTime(2003, 10, 3) }
};

// And here is where the magic begins...
// Store the object - no conversion required.
db.Store(cinema);

// Magic is not finished yet.
// Get an object that matches the criteria.
var movies = db.ExecuteQuery("SELECT Cinema WHERE ALL Movies.Studios.Titles CONTAINS '20th Century Fox'");

// Magic still goes on...
// Creating parameters
Parameters param = db.CreateParameters();
param["dt1"] = new DateTime(2006, 10, 1);
param["dt2"] = new DateTime(2009, 09, 17);

// And here we search for the values IN THE ARRAY!
var result = db.ExecuteQuery("SELECT Cinema WHERE OpenDates BETWEEN @dt1 AND @dt2", param);

// And here we do something good with the objects retrieved from the database.
foreach (var cinema in result)
{
Console.WriteLine(cinema.ToString());
}
}


This is real code running on Eloquera Database 2.0 (codename Woomera) - the web-oriented client/server object database for .NET. It is already available as a pre-release version on the website http://woomera.eloquera.com


The upcoming version of Eloquera database has some mind-boggling features, and I would like to give a brief list of its main features.

  • Storing any .NET object without implementing any interface or inheriting from a specially designed class.
  • Queries based on SQL. Yep, good old SQL. And no SQL database is required.
  • Returns the objects in their native form, as a single object or as an enumeration.
  • Supports arrays in queries. Any arrays - simple, multidimensional, jagged, of simple or complex types. And there is more!
  • Supports JOINs in queries. And even for arrays.
  • Expressions and functions in queries. You can perform JOINs or sort your data on them.
  • Flexible sorting - there are some really useful ones.
  • Regular Expressions are your best friends! Regex support in queries.
  • Indexes. Yep, you can index data for faster access. Both fields and properties.
  • Bulk inserts and updates. You can insert tens of thousands objects in a second.
  • Generic object support. And also in queries.
  • Inheritance support in queries (SELECT ParentClass returns both ParentClass and ChildClass)
  • Queries only upon certain type. (SELECT ONLY ParentClass returns only ParentClass, but not ChildClass)
  • Restoring objects partially (you might need ForumTopic object, but don't need all TopicMessage, linked with it)
  • Depth for queries.
  • Client/server architecture.
  • Parallel and independent query execution for multiple users.
  • Windows authentication. Specify no user name and log on under your current account.
  • Both Server and client are implemented in 32- and 64-bit architectures.
  • Unique identifier for any object within a database - for stateless environments (hence ASP.NET)
  • Different cultures support in queries (e.g., "where dates BETWEEN['en-US'] @d1 and @d2" - formats will be treated as US English, even with the current UK settings on the machine)
  • Approximate matching with ALMOST keyword.



Have you seen an object database with SQL query support? With JOINs? And with arrays?

So, what do you need to get Eloquera Database 2.0 running on your machine and ready for your command?

First, download and install the Eloquera setup files from the website. You will be asked to fill up a short registration form, and you will receive an e-mail with the download links. You need to download the server for your platform (32- or 64-bit). The server includes also all client libraries.

Installation is straightforward, and takes just a few seconds. The setup will install the service called Eloquera Server 2.0.

Included with the Eloquera server is a folder containing examples in C#. These examples are quite concise but cover various topics on using Eloquera, like JOINs and queries on arrays.

Secondly, you need to connect to the database in your code. By default, only the members of the Administrators group can access the database server. As Eloquera uses integrated Windows authentication, you can add your own user or a group to the list of the permitted security entities.

To do that, open the Eloquera Server configuration file (it is usually located at "%ProgramFiles%\Eloquera\Eloquera Server" and it called Eloquera.config) with any suitable text editor (as Notepad).

Find the Server element, and change the value of the AllowUsers or AllowGroups attribute, adding your user or group to the list. The items in the list are separated by a semicolon. It is advised not to remove Administrators group from the list.

For development purposes it is good practice to add Users group to the list of allowed groups. After this your element in the configuration file will like this:





Restart the service for the changes to take effect. You can easily perform this task using the command line and running the following commands:

net stop "Eloquera Server 2.0"
net start "Eloquera Server 2.0"

And now Eloquera is ready to run your queries.

Below I am going to give some brief examples of Eloquera DB queries. We will discuss all the features in the next articles about Eloquera Database. These examples are intended to show how easily you can start working with Eloquera.

We are going to use these two classes as a base for our demonstration:


public class School
{
public Location Location { get; set; }

public string Name { get; set; }
}

public class WorkPlace
{
public Location Location { get; set; }

public string Company { get; set; }

public string Position { get; set; }
}

So, we have stored a bunch of objects of both types in the database, and now we want to run a JOIN query to get some of them back.

var queryResult = db.ExecuteQuery("SELECT sch, wp FROM School sch INNER JOIN WorkPlace wp ON ch.Location=wp.Location");

Consider we have stored multiple instances of the following class in our database:

public class User
{
public Location CurrentLocation { get; set; }

public string Name { get; set; }

public DateTime BirthDate { get; set; }

public User[] Friends { get; set; }

public WorkPlace UserWorkPlace { get; set; }

public string[] Emails { get; set; }
}

So, to find all users who has registered using the specific e-mail addresses, we can run a simple query with parameters:

Parameters param = db.CreateParameters();
param.AddList("emails", new string[]{"john@gmail.com", "david@hotmail.com"});

var res = db.ExecuteQuery("SELECT User WHERE Emails CONTAINS @emails", param);

As I said, you can find fully working examples of the Eloquera applications by installing the Eloquera server on your development machine.


Please follow the links below for downloading Eloquera DB v2.0 (codename Woomera).



Pre-release site for Eloquera 2.0 codename Woomera.

URL: http://woomera.eloquera.com

Forum: http://woomera.eloquera.com/TopicsList.aspx

Documentation: http://woomera.eloquera.com/NetHelp/default.htm

Thursday, November 20, 2008

Eloquera applications

Eloquera is being actively developed. Our team is working on adding new features and extending the current functionality. The current product is however, already quite suitable for use in some applications as the data storage backend. For example, the content management system of the 
www.eloquera.com website uses Eloquera to store all its data.

Eloquera has many unique features, but the main reason to use it, is the way it enhances and speeds database development. It radically reduces the complexity of designing, implementing and supporting the database and its engine. The developer is freed to focus on the primary task of developing the application using object-oriented programming techniques.

Below are a few examples of how Eloquera has been used in different web-oriented projects, and what impact it has had on the performance of the developers.


Web-based content management system

Modern CMSes are the core of web publishing. Almost any CMS nowadays stores its content and settings in a relational database. That seems a very natural choice as such systems store massive amounts of the text data. However, every web developer knows that CMS is not just about text. 

Content management system stores the links between documents, the different sections of the document, and each section has its own properties and ways to display data.

For the sake of simplicity here we will consider only a very simple example, looking at the functionality that covers the headings and the pre-formatted items (the base for things like quotes, examples, insets).

All programming starts with the class definitions, and here is a very basic code. You can draw a sketch for such a simple system in just a minute or so.


Basic definitions for the content management system.
public class DocoItem
{
    public string Text { get; set; }
    public string ParentId { get; set; }
    public int DocoOrder { get; set; }
}
 
public class DocoHeader : DocoItem
{
    public DocoHeaderType HeaderType { get; set; }
}
 
public enum DocoHeaderType : int
{
    PageTitle = 1,
    SectionHeader = 2,
    Navigation = 3
}
 
public class DocoPreformattedItem : DocoItem
{
    public string OriginalText { get; set; }
} 

And now the database part.

Eloquera design

Eh, what design? Can't a computer create a design that is most suitable for it? Sure, it can. These monotonic tasks are what the computers are good at!

Relational table design.

Here we have 3 tables (in fact, we need 4, one for the header type, but let's keep things simple), and 2 relationships between them.














Eloquera query

Getting data is the most used operation in the database world. And what is the most popular languange for getting data? Of course, good old SQL. Here it is.

Run query to get data.

var docos = 
  db.ExecuteQuery(
    "SELECT DocoItem WHERE ParentId = " + 
    Quote(docoName) + 
    " ORDER BY DocoOrder"
  );

Yes, it is just one line. We separated them for your convinience.

Now let's see what the relational databases have to offer.


Relational database query


First, we create a stored procedure that gets the data from the database.

CREATE PROCEDURE GetDoco(
@DocoName NVARCHAR(64)
)
AS
BEGIN
    -- These are text lines
    SELECT 
        d.DocoOrder, 
        d.Text
    FROM
        DocoItems d
    WHERE
        d.DocoName = @DocoName
        AND d.DocoType = 0
        
    -- Here comes the second recordset
    -- with the headers.
 
    SELECT 
        d.DocoOrder, 
        d.Text,
        dh.HeaderType,
        dh.HeaderLevel
    FROM
        DocoItems d 
          INNER JOIN 
        Headers dh
          ON 
        d.DocoItemID = dh.ID
    WHERE
        d.DocoName = @DocoName
        AND d.DocoType = 1
    
    -- And the third recordset
    -- with the pre-formatted items.
    SELECT 
        d.DocoOrder, 
        d.Text,
        dp.IsOriginal,
        dp.OriginalText
    FROM
        DocoItems d 
          INNER JOIN 
        DocoPreformattedItems dp
          ON 
        d.DocoItemID = dp.ID
    WHERE
        d.DocoName = @DocoName
        AND d.DocoType = 2
END      
After that there must be code to get this stored procedure running and to collect the results. It is no shorter than the example above, and it is not really interesting. Still want to see it? Contact us as www.eloquera.com/contact and we will send you that code.
It is really good for insomnia!