Taoffi's blog

prisonniers du temps

Meta-models: towards a universal dependency injection framework


I joined an interesting presentation today about unit tests. Part of the presentation was related to dependency injection usage for unit testing. That brought to my mind again the benefits of meta-models.

The problem

Unit testing often faces the problem of having to instantiate objects that may impact the test itself or simply make the test impossible.

A sound example of this is when the method to be tested requires the instantiation of an object requiring, for instance, a database connection.

In this schema, we have 3 actors

  • The function
  • The caller
  • The object (SomeObject) which cannot be instantiated.


Traditional recipe

One, now traditional, recipe is to use an Interface (instead of the specific object) as a function parameter. And, according to the context, instantiate and use an object that implements the defined interface. The figure below illustrates this.


Good solution… a little acrobatic, but OK… good.


A problem, though. We now have 6 actors (to code and maintain):

  • The Function
  • The caller
  • The original 'true' object (SomeObject)
  • The Interface
  • The interface implementations (=2)!


On the other hand, testing a function may also need to instantiate a 'true' object context. In which case, we would have to rewrite (and recompileJ) our test code to instantiate a 'true' implementation when required.

A third point: in this solution, we defined the Interface to represent an abstraction of the original object. What if the original object itself was, for instance, a database record? This would then introduce a new actor in our playgroundJ


As Bjarne Stroustrup puts it:

"Any verbose and tedious solution is error-prone because programmers get bored" J


Meta-models may be a better way

In the current case, meta-models (see my previous posts) can be used to more simply describe all actors (object structures / methods / properties…).

An illustration:



Reminder: meta-models are closely related and enforced by Reflection (assemblies' meta-data). Through meta-models AND Reflection (namespace System.Reflection) developers can gain more flexibility to create versatile and scalable software.


In our present case, meta-models not only expose less actors to code and maintain, but also lower the complexity level of involved actors (for instance: maintaining database records instead of hard coding implementation).


The main goal for this approach is to ultimately write fewer universal methods to invoke and instantiate any object!

Will try to deliver a code sample in a future post. In the meantime, you may download meta-model sample code here!

Silverlight database to DataGrid, yet another approach- Part IV

Filtering database data

As we have seen in Part III, the SQL Select statement is composed of the following parts:

SELECT                 [field1], [field2],… [fieldn]

FROM                   [database table or ‘table-like’ store]

WHERE                [conditions]

ORDER BY           [field name] <sort direction>,

                               [field name] <sort direction>


It is the ‘WHERE’ clause of the SQL statement that is used to filter the data.

‘WHERE’ is followed by ‘conditions’. Several conditions are concatenated using AND or OR operator.

What is a filter condition?

A ‘condition item’ can be presented as:

[Field name] [Comparison operator] [Filter value]


A collection of ‘condition items’ can be presented as something like:

<Condition item> <Concatenation operator> <Other condition item>



Name = ‘John’

Amount >= 100

(Last_name LIKE ‘%bama’) AND (Age >= 20)


That seems easy to be represented by an object:

public class SilverFiltertItem


       string              m_field_name,


       CompareOperator     m_compare_operator  = CompareOperator.EQUAL;

       ConcatOperator      m_concat_operator   = ConcatOperator.AND;



The concatenation and comparison operators are members of the following enum types:

public enum filter_concat_operator







public enum filter_compare_operator














Two properties can give us the Compare and Concatenate strings when required:

protected string ConcatString




             if( m_concat_opertaor == filter_concat_operator.none)

                    return "";


             // return ‘AND’ or ‘OR’

             return Enum.GetName( typeof( filter_concat_operator), m_concat_opertaor).ToUpper();




protected string CompareString




             switch (m_compare_operator)


                    case filter_compare_operator.Equal:

                           return "=";


                    case filter_compare_operator.Like:

                           return " Like ";


                    case filter_compare_operator.Not_equal:

                           return "!=";


                    case filter_compare_operator.GreatertThan:

                           return ">";


                    case filter_compare_operator.GreatertThanOrEqual:

                           return ">=";


                    case filter_compare_operator.LessThan:

                           return "<";


                    case filter_compare_operator.LessThanOrEqual:

                           return "<=";



                           throw new Exception("Unknown Compare opertor encoutered!");





The FilterItem object can now provide us with its SQL string through a property like the following:

public string SqlFilterString




             if( string.IsNullOrEmpty(m_filter_value)

                           || string.IsNullOrEmpty( m_target_column_name))

                    return "";


             string       field_name   = "[" + m_target_column_name + "]",

                          str_ret      = ConcatString + "(";


             string str_value    = m_filter_value;


             str_ret      += field_name + " " + CompareString + " " + str_value + ") ";

             return str_ret;



A filter collection class may look like this:

public class SilverFilter : List<SilverFilterItem>





The filter collection can return the entire SQL filter string through successive calls to its member items:

public string SqlFilterString




             if( Count <= 0)

                    return "";


             int    ndx          = 0;

             string str_ret      = "";


             foreach (SilverFilterItem f in this)


                    if (ndx <= 0)

                           f.Concat_operator = filter_concat_operator.none;



                           if( f.Concat_operator == filter_concat_operator.none)

                                  f.Concat_operator   = filter_concat_operator.and;



                    str_ret      += f.SqlFilterString;




             return str_ret;




Our DataTable object (see previous posts) can now include a Filter collection object and construct the SQL Where clause:


protected SilverFilter    m_filter     = new SilverFilter();




public string SqlCommand






             string       str_cmd      = "SELECT * FROM " + m_table_name;

             string       str_sort     = m_sort.StrSql;

             string       str_filter   = m_filter.SqlFilterString;


             if( ! string.IsNullOrEmpty( str_filter))

                    str_cmd      += " WHERE(" + str_filter + ")";


             if( ! string.IsNullOrEmpty( str_sort))

                    str_cmd      += " ORDER BY " + str_sort;


             return str_cmd;



Note: a better approach would, of course, be to map the filter field names to the table’s meta-data table fields… or directly use MetaDataTable’s columns as filter members (instead of using field names as strings). In this last case, we would be able to check columns’ data types and also act more closely to database’s business logic.


In other words: what is proposed here is a simple approach that can evolve according to your needs.



You can download the sample code: SilverDbDataGrid-2-sorting&filtering.zip (1.87 mb)

Silverlight, Back to basics: the User Interface!


I wanted to post a new article in the series about Silverlight (client) and server’s databases. The subject of the article was ‘data forms in Silverlight’. But, because a ‘Data Form’ is the ultimate place where the user directly interacts with the data, and where the concrete sense of a ‘rich user interface’ comes to life… I finally preferred to begin by discussing one of the basic questions: the User Interface (GUI, UI… as it got so many titles and names through the time!)

The UI frontiers

Where does the UI sit inside the entire image of a software project?

Are there any definitive… (kind of ‘waterproof’) frontiers between the UI tasks and the rest of the software project’s tasks?

There is, occasionally, some confusion about this subject. Software industry literature teaches us how to separate ‘objects’ from their ‘presentation’ (‘data’ from ‘views’). But does this mean that building a User Interface should be done in a separate bureau (or on the beach)?...

Although no literature ever discussed the question, such a simplistic approach is applied in some projects in the real world. The concept of separating objects from their presentation is sometimes applied in the form of separating the development processes: Object tasks vs. UI tasks, Object modules vs. UI modules, Object workers vs. UI workers!

Although each task, in any project, has particular skills and knowledge requirements, the success (or failure) of the entire project obviously depends on the global understanding, at all levels, of what the final product is and how its parts articulate.

What is the ‘User Interface’?

To avoid taking the risk of giving a formal definition of what a user interface is, let’s try to define what the user interface’s role is.

In most cases, software solutions propose automated (accelerated) tools for accomplishing well-known human tasks. Most of these tools run using some new ‘media’ (screens, keyboards, mice… etc.). This context implies new ways for representing tasks’ items and new ways for manipulating (processing) theses items. The initial presentation approach was, naturally, to mimic the ‘real world’ way of presenting and manipulating the task items (remember the too large accountancy book displayed on the too small screen… that was probably when the scroll bars have been invented!). Many of today’s iconic presentations still use this approach (just have a look at a ‘button’ and its press/release interaction!)

Presentation (and human-machine interaction process) is largely related to the social and cultural context in a given period or era (objects we use, fashion and elegance trends…). The advent of software and its related objects (virtual and/or material) also affects and participates in the evolution of this cultural and social context. That is why, I think, that a successful user interface is achieved when we mimic the ‘real world’ objects and processes to some extent and, in the same time, instigate new (futuristic) objects and processes (obviously, what may seem ‘futuristic’ today will sooner or later become outdated!).


Anyway, if we may admit that user interface is, briefly, about presenting data through visual graphical objects (controls), then, many new things have to (will) be done at this level!

For example, take the ComboBox: which is basically a selection list of items. With the time going, a selection list can now have several thousands of items… may be we now need a ‘paged combo-box’?... or may be a brand new control to make the selection process easier, faster, less cumbersome…

Many interesting work have been done to solve this kind of concrete problems (you may have a look at some ‘virtualization’ approaches here, here and/or here) fewer have been done for inventing new UI objects (since how many years do we still use: the button, the text-box, the list/combo-box…?)

UI role

From a functional point of view, data presentation (User Interface) role may be summarized as:

§  Give access to different data areas (through menu commands, for example);

§  Show the data;

§  Let the user interact with the data (modify, add, delete…);

§  In some cases, validate the data;

§  Send the updated data back to the data store (server).


In these tasks, the user interface makes use of:

§  Controls to present the data;

§  And transitions (animations or animation-like, between presentation and processing stages).


The success of user interface (in a given era!) is mainly related to the best (harmonious) choice of controls and transitions according to each context of data presentation and/or processing stage.

Silverlight (and WPF) added value

One of the most interesting aspects of Silverlight (and WPF) is that it doesn’t imprison you in a special form of any of its proposed controls. You can, for example, reformat, entirely or partially, the proposed ‘traditional’ ComboBox to make it present the data and behave the way you want. You can, of course, invent something new.

UI controls… the server choice

A UI control presents data. The data is stored and ultimately validated and processed at the server side. So, at the client side, the presented data has a semantic aspect and a presentation (visual) aspect. Although we cannot pretend of any strict rule (valid for all contexts), the data semantic aspect should better be defined at the server side. i.e. questions like: is this a read-only, read/write data?, can the value be omitted (nullable)?, should the value be one of specified choice list items?... etc. should better be defined at the server-side.

The presentation visual aspect (and transitions) should logically be defined at the client side (the UI module).


How can we setup and manage the relationship between the data semantic/visual aspects?

Again, there no ‘all purpose’ rule!

I will present some work on this subject in a following post.

Silverlight database to DataGrid, yet another approach- Part III

Sorting and filtering database records

After having succeeded to display our server data into Silverlight DataGrid (see previous post), we will now continue the adventure to complete our solution with some useful and necessary features that Silverlight DataGrid originally proposes (for example, sorting records) and add some new features for filtering records.


Silverlight DataGrid allows the user to sort displayed rows by clicking into column headers.

That is nice and helpful. But, in the context of data provided by a server through a database, that doesn’t seem to be quite a correct approach.

In fact, in such context, if you click to sort a column in the ascending order, the displayed data records may not contain the entire values stored in the database. The data should be ‘refreshed’ to represent the effective sorted values according to currently stored database data in its entirety.


Sorting database data

How database data can be sorted?

The answer: this can be done using the SQL ‘ORDER BY’ clause.

We use SQL to query the data according to the following (simplified) statement template:

SELECT                [field1], [field2],… [fieldn]

FROM                  [database table or ‘table-like’ store]

WHERE                [conditions]

ORDER BY           [field name] <sort direction>,

                            [field name] <sort direction>


The ORDER BY part, contains a list of field names (each of which should be one of the listed SELECT fields, or, at least, one of the queried table or ‘table-like’ fields)

Each field in the ORDER BY clause can have a specified sort direction (ASC for ascending, or DESC for descending). The default being the ascending direction (if the direction is omitted)


If we have to represent an ‘order by’ item as an object, the object may then be something like this:

public class SortItem


       string       m_field_name;

       SortDirection m_direction  = SortDirection.ASC;




So, in our case, we can simply sort our DataGrid by building a list (List<SortItem>) of clicked column names (met-data column names) and passing them to the server to compose the ORDER BY part of the query accordingly and return too us the desired sorted data.


Implementing the solution

Let’s begin, at the server side, by enriching our service’s SilverDataTable (see Part II) object by a new SortList object, which will simply be a List<> of SortItem.


public enum sort_direction







A SortItem object can be defined as follows:



public class SilverSortItem


       protected string           m_target_column_name       = "";

       protected sort_direction   m_sort_direction    = sort_direction.asc;




We can now define a sort-list object which is mainly a List<SilverSortItem > that takes care for some constraints like, for example, not adding duplicate fields:


public class SilverSort : List<SilverSortItem>



The class exposes an indexer that returns the field by its name:

public SilverSortItem this[string field_name]




             if( string.IsNullOrEmpty( field_name) || Count <= 0)

                    return null;


             foreach (SilverSortItem e in this)


                    if( string.Compare( e.Target_column_name, field_name, true) == 0)

                           return e;


             return null;



An Add method, to add or modify settings of an existing sort field:

public new void Add(SilverSortItem element)


       if( element == null || string.IsNullOrEmpty( element.Target_column_name))



       SilverSortItem      e      = this[element.Target_column_name];


       if( e == null)

             base.Add( element);


             e.CopyOther( element);



And a property that returns the SQL sort string of the contained fields:

public string StrSql




             if (Count <= 0)

                    return "";


             string str_ret = "";


             foreach (SilverSortItem s in this)


                    if( str_ret.Length > 0)

                           str_ret      += ", ";


                    str_ret += s.StrSql;


             return str_ret;




Let’s now include a Sort list into our SilverDataTable class:


public class SilverDataTable


       protected SilverSort       m_sort = new SilverSort();



We can now extend our SqlCommand property to include the sort string:

string str_sort     = m_sort.StrSql;


if( string.IsNullOrEmpty( str_sort))

       return "SELECT * FROM " + m_table_name;

return "SELECT * FROM " + m_table_name + " ORDER BY " + str_sort;


We will also change our WCF service method to include an optional list of sort field names:



public SilverDataTable GetData(string str_connet_string,

                           string str_sql_command,

                           SilverSort sort_items,

                           int n_records)



Sorting… the Client-side job

At the client-side, our DataGrid should send us a message each time a column should be added to the SilverDataTable sort list. And, unfortunately, that is not as ‘intuitive’ as we may like!

Manish Dalal published a very interesting paper about custom sorting and paging inside a DataGrid. His work presents a good (and extensible) start point.

The usable part of his work in our project is the CollectionView class which can give us more control on sorting in response to DataGrid Column Click events.

As you may see at Bea Stollnitz interesting blog, Silverlight DataGrid internally uses a CollectionViewSource (an object that implements ICollectionView interface).

That is: When we set DataGrid’s ItemsSource to an observable collection, it integrates it into its own ICollectionView object.

Fortunately, the DataGrid is smart enough to let us implement this object ourselves, i.e. if we set its ItemsSource to an object that implements the ICollectionView, the DataGrid will use this instead of its own one.

So, let’s create a class that implements the ICollectionView:

public class SilverCollectionView<T> : ObservableCollection<T>, ICollectionView



The ICollectionView exposes a collection of ‘SortDescriptions’ that we will use, for the requirements of our project, as a list of field names to be sorted. i.e. each time a column will be clicked, we will add the column name to the SortDescriptions list and generate a Refresh event to request the server’s data sorted as desired.

Here is the SilverDatasetView helper class that will integrate our SilverDataTable as an ICollectionView:

public class SilverDatasetView : SilverCollectionView<SilverDataRow>


       public SilverDatasetView() : base()




       public SilverDatasetView(SilverDataTable service_data_table) : base()


             CopyDataset( service_data_table);



       public bool CopyDataset(SilverDataTable data_table)


             if( data_table == null || data_table.Rows == null)

                    return false;


             base.SourceCollection      = data_table.Rows;

             return true;



Once we receive the data from our database server, we can now set the DataGrid’s ItemsSource to a SilverDatasetView object:

SilverDatasetView   dataset_view = new SilverDatasetView(m_table.Rows);

data_grid.ItemsSource                   = dataset_view;


To tell the DataGridColumn how to send us desired sort items, we will set its SortMemberPath to the data column name:

Grid_col.CanUserSort              = true;

Grid_col.SortMemberPath    = data_col.Name;


The last part is to respond to the Refresh event of our SilverDatasetView in order to collect the desired sort field names and request the data accordingly:

dataset_view.OnRefresh     += new EventHandler<RefreshEventArgs>(m_dataset_view_OnRefresh);


void m_dataset_view_OnRefresh(object sender, RefreshEventArgs e)


       if( m_sort_fields == null)

             m_sort_fields = new ObservableCollection<SilverSortItem>();




       SilverSortItem      sort_element;


       foreach (SortDescription s in e.SortDescriptions)


             sort_element = new SilverSortItem();

             sort_element.Target_column_name   = s.PropertyName;

             sort_element.Sort_direction             =

                           (s.Direction == ListSortDirection.Ascending)




             m_sort_fields.Add( sort_element);






RequestSilverDataset() method will, mainly, do the following:

DataServiceClient   cli    = service_helpers.DataServiceProxy(5);


cli.GetDataCompleted += new EventHandler<GetDataCompletedEventArgs>(cli_GetDataCompleted);

cli.GetDataAsync( str_connet_string, str_sql_command, m_sort_fields, n_records);


That is it… your DataGrid can now be sorted according to the real data on the server.

Don’t forget: Click the column to sort/ shift + click to add the column to the sorted list…


Download the sample code:

SilverDbDataGrid-2-sorting.zip (1.36 mb)

Silverlight database to DataGrid, yet another approach- Part II

This is the second part on how to format/adapt data to be displayed in a Silverlight DataGrid in a way that allows the preservation of business logic.


Server side objects

As we have seen, in part I, the server will prepare our data into the designed classes before transmitting it to the Silverlight client application.

On the server side, we have the following classes:


Data level classes


Represents the table (or view, or function…) data.


A meta-data table

A list of data rows


Represents one record of data.


List of data cells

Linked to:

A parent table


Represents one record’s data cell.

Linked to:

A parent row

A parent meta-data column

Meta-data level classes


Represents the table’s meta-data (schema)


A list of meta-data columns

Linked to:

A parent table


Represents one column’s schema information.

Note: This is the ‘Key Class’ where you can insert all your required business logic.

Linked to:

A parent meta-data table


The server uses these classes’ methods to expose a data service that returns a set of requested data:


[AspNetCompatibilityRequirements(RequirementsMode =


public class DataService



       public SilverDataTable GetData(string str_connect_string,

                                  string str_sql_command)


             SilverDataTable sl_table = new SilverDataTable();


             sl_table.UserDefinedSqlCommand = str_sql_command;



             return sl_table;




The GetData method of the SilverDataTable logic is as follows:

§  Open the database connection.

§  Read the meta-data structure of the SQL command.

§  Read the data rows of the SQL command.


Reading table’s meta-data (table schema)

For reading the table schema, SilverDataTable asks an OleDbDataAdapter to fill a DataTable (System.Data) schema and passes this DataTable it to its SilverMetaTable for reading its information:


OleDbDataAdapter    adapter      = new OleDbDataAdapter(str_sql_cmd, connection);

DataTable           table  = new DataTable();


table  = adapter.FillSchema(table, SchemaType.Mapped);

MetaDataTable.ReadDbTableColumns( table);


The Meta-data table (SilverMetaTable) offers a method to read a DataTable (System.Data) schema and create its own meta-data columns accordingly:


public bool ReadDbTableColumns(DataTable db_table)


       /// start with a ‘traditional’ checking!

       if( db_table == null || db_table.Columns == null)

                    return false;




       foreach (DataColumn col in db_table.Columns)


             Add( col);



       return true;



The Add method of this same class proceeds as in the following code:


public void Add(DataColumn data_column)


       /// start with a ‘traditional’ checking!

       if( data_column == null

                    || string.IsNullOrEmpty( data_column.ColumnName)

                    || data_column.DataType == null)



       /// does this column already exist?: if so, only update its information

       /// otherwise add a new column

       SilverMetaColumn    col    = this[data_column.ColumnName];


       if( col == null)

             Columns.Add(new SilverMetaColumn(data_column));


             col.ReadColumnInfo( data_column);



As you may have already guessed through the above code, our meta-data table offers an indexer which returns the meta-data column by name:


public SilverMetaColumn this[string column_name]




             if( string.IsNullOrEmpty( column_name) || Count <= 0)

                    return null;


             foreach (SilverMetaColumn col in m_columns)


                    if( string.Compare( col.Name, column_name, true) == 0)

                           return col;


             return null;




And the meta-data column offers a constructor using a DataColumn (System.Data) object:


public SilverMetaColumn(DataColumn data_column)


       ReadColumnInfo( data_column);



public bool ReadColumnInfo(DataColumn data_column)


       if( data_column == null)

             return false;


       m_name       = data_column.ColumnName;

       m_caption    = data_column.Caption;

       m_data_type  = data_column.DataType;


       return true;



Reading data records

Inside the SilverDataTable, reading the data rows (records) is straightforward:


OleDbCommand        cmd    = new OleDbCommand( str_cmd, conn);

OleDbDataReader     dr     = null;

SilverDataRow       row;


dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

while (dr.Read())


       row          = new SilverDataRow(this);

       row.ReadDataReader( dr);

       m_rows.Add( row);



The ReadDataReader method of the SilverDataRow class looks like the following pseudo-code:


int                 n_fields     = data_reader.FieldCount;

string              field_name,


SilverMetaColumn    meta_column;


for( int ndx = 0; ndx < n_fields; ndx++)


       field_name   = data_reader.GetName( ndx);

       meta_column  = meta_table[field_name];

       field_value  = data_reader.GetValue(ndx).ToString();


       m_cells.Add(new SilverDataCell(this, meta_column, field_value));



The Silverlight client side

At the client side, our Silverlight application will uses (references) the server’s web service in order to obtain the data.

As we have seen above, the data will be received as a SilverDataTable object (containing the data rows + the meta-data table)


Binding the Silverlight DataGrid to the data

To bind the received data to the DataGrid, we will, basically, proceed according to the following steps:

§  Set the DataGrid to NOT auto generate its columns (we will do this ourselves)

§  Bind the DataGrid to our received SilverDataTable’s Rows (List<> of rows, often presented in Silverlight as an ObservableCollection<SilverDataRow> when referencing the wcf service)

§  For each SilverMetaColumn in our received meta-data table’s meta-columns:

§  Create a DataGridColumn according to the meta-column data type (and business logic constraints)

§  Bind the created data grid column using a converter that will be in charge of interpreting the related data cell’s data for all column’s rows

§  Add this DataGridColumn to the DataGrid


Here is a sample code (where some artifacts have been removed for better readability):


foreach (SilverMetaColumn met_col in meta_table.Columns)


       DataGridBoundColumn col    = CreateDataGridColumn( meta_col);

       Binding                    binding      = new Binding();


       col.Header                 = cell.Caption;

       binding.Path               = new PropertyPath("Cells");

       binding.Mode               = BindingMode.OneWay;

       binding.Converter          = (SilverRowConverter) this.Resources["row_converter"];

       binding.ConverterParameter = col_index;


       col.Binding         = binding;





Note: The converter is defined inside the Xaml code, like the following:



       <local:SilverRowConverter x:Key="row_converter" />





As you may have guessed, each DataGrid row will receive the corresponding data row’s Cells as its DataContext. And to present any row cells, it will call our designated converter.

To interpret one cell’s data, our converter takes one parameter: the cell index.

Using he cell index, the converter will be able to identify the related cell, its data and its meta-data column information (data type, or any other business logic constraints)


Here is a sample code for the converter:


public object Convert(object            value,

                    Type         targetType,

                    object              parameter,

                    CultureInfo culture)


       ObservableCollection<SilverDataCell>    row    =

                    (ObservableCollection<SilverDataCell>) value;

       int    col_index    = (int) parameter;


       SilverDataCell      cell         = row[col_index];


       return cell.ValueAsString;



Sample user interface to test the solution

In the joined sample code, to test our solution, the user interface proposes:

§  A TextBox control where you can enter the desired connection string to your database;

§  Another TextBox where you can type your SQL command;

§  A data grid where the received data will be displayed.


Any comments are welcome: you can write me at tnassar[at]isosoft.org


Download the sample application (1.32 mb).


Silverlight database to DataGrid, yet another approach- Part I


As I exposed in an earlier post, Database structure can be declined into the following hierarchy

§ A table

§ Containing rows

§ Containing data //(arranged into columns)


This schema cannot live without the following meta-data structure

§ Table definition

§ Column definition:

§ Data type / data size (storage space reservation maximum size)


One important thing to observe is the relation between the meta-data definitions and the data storage or presentation:





All these structures and concepts have been used for years through several database access technologies (ado.net for example) using some well known objects like Dataset, DataTable… etc. and everybody was easily able to read and display data into grid controls in Windows and Web forms.


Now this question is once again exposed with Silverlight: How to read and display data into a DataGrid!

The reason for this is, mainly, that Silverlight is a “multiplatform browser plug-in”, and, as such, don’t know about database facility objects like Datasets, DataTables…

Also, Silverlight being a “client”, it cannot directly have access to what is stored or otherwise going-on on the server-side end. Accessing such information is done by calling Xml web services hosted at the server.


Interesting solutions

Some interesting work has been done to try to solve this dilemma. Some of the solutions proposed a (very interesting) workaround which requests the server’s xml dataset, and entirely creates database objects at runtime (MSIL!) on the Silverlight client side.

Although this seems quite fascinating, it is still a sort of ‘black magic’ solution, and lets me uncomfortable to use it as a sustainable solution. It also misses some of the interesting features of Silverlight, like Binding Converters.


Starting at the bottom line

One may think: A Dataset already has all what we need: Meta data definitions, Data rows… etc.

Let’s create a Dataset on the server-side and then write it down to the client through a web service. The client can then consume the received dataset by incorporating it into the required classes.


I tried this solution, but ended up by finding myself in front of a great deal of ‘raw’ data that should be reformatted on the client… And, worse, this data reformatting altered some important business logic that should be decided on the server-side.

For example, in a sales representative client application, if a ‘customer’ field value inside an ‘order’ should be only one of the current user’s authorized customers; this would obviously be better decided on the server not the client.

Even the fact of presenting the ‘customer’ field as selection option (combo box) or as a plain text field is better to be decided at the server end.


The ‘Dataset’ is a great and useful object, but it only provides ‘raw’ relational data. It needs to be complemented by other features in order for the business logic (at the server-side) to take control over data presentation and manipulation process (at the client-side).



The diagram below illustrates the basic schema used by the proposed solution to represent the data stored in a database.


The diagram’s classes represent the 2 levels of a database table:

§  At the meta-data level : SilverMetatTable, composed of one or more SilverMetaColumn(s);

§  The data storage level is represented by SilverDataTable, which has a meta-data table definition (SilverMetaTable). The data table contains zero or more rows (SilverDataRow), each of which containing data cells (SilverDataCell). Each data cell is linked to the corresponding meta-data column.


The meta-data column represents the basic properties of a database column (data type, default value, is/is not nullable… etc.), but can now expose all the desired presentation features and functionalities as required by the business logic.

It may, for example, expose the desired presentation type (plain text / option list… etc.), for an option list: the choice-elements (or where to request them), the data access options (read-only / read-write…) according to session context or application context… etc.


Surprisingly coding the required classes for this part of the solution was a matter of a few hundreds of lines of code (approx 4 hours + 2 for repairing some of my ‘chronic’ errors… I do many!)


In the next post, I will talk about ‘The client side’ job… and deliver a fully-functional sample application.

See part II


Revisiting the Database design foundations

Software is about defining objects structures, relationships and behavioral contour. This is probably a too short sentence to define what software is. But it can be a good commencement for what I would like to expose here.

Years passed for the software industry to mature and be able to express the complexity of this task. And, it seems that there still will be some more years to come for this maturity to gain some sort of stability and normalization.

Remember the lessons about the ‘Date object’ which would never display a ‘February 30’ day. Although that seems so far away, we still encounter things of the same kind (remember, for example, the ‘page 1 of 0’ syndrome!). Those are simple indications about how complex it can be to mimic the ‘real world’ system, its large span of objects, relationships and behaviors.


One of the early, and interesting, questions that the Software had to solve was: data storage.

Historically speaking, we can summarize the maturity of the provided solution into three stages:

§ The folder/file structure

§ The data table

§ The ‘relational’ database


The ‘data table’ solution seems particularly interesting:

If you have a look at a data table (even within any of the most elaborate of today’s database engines) you can easily state how the simplicity of the structure looks embarrassing:

§ A meta-data space which describes the table’s columns.

§ And, a storage space where the columns’ data is stored into rows.





Basically, the column definition describes its data type and storage size. This allows the storage system to organize the data rows according to theses definitions.


Of course, with the time going, so many other attributes and artifacts had been added to the data table solution. Column definitions, for example, got more elaborate (ex: default value, auto-increment, indexes, data validation constraints… etc.), Columns’ relationships (foreign keys…), Operations like row insertions, row deletions or row updates can be triggered by procedures that execute particular ‘business’ logic… etc. But the foundations of the solution remain strictly the same as the early reflection and design…

One of the reasons of this design success seems to be the readability of the solution.


Anyway, the fact is, today, nearly no one single software solution can live without a database! And that itself is a profound demonstration of the efficiency of the initial design.


The Software ‘Code / Database’ schism!

Strangely, databases still live almost apart from the software development cycle. When you talk software, you seem to be supposed talking about classes, inheritance, behaviors, user interface… etc. and databases almost seem so simplistic compared to this ‘alive’ jungle!

The reasons for this schism seem to be cultural and social (within the development community) more than being a verdict against the database solution efficiency.


Industrially speaking, this schism seems often to be one of the most common explanations of software projects failures. It is also, probably, one of the profound reasons for some of the software industry’s inefficiencies.


What I think is that databases efficiency can be beneficially used for leveraging software objects properties and behaviors. And that database organization and readability bring interesting applications and solutions for controlling objects behaviors in order to create more versatile and scalable software solutions.

At a very simple level, think about application configuration files (which are great solutions but can sometimes hardly be altered without producing inconsistencies).

Think about a truly structured configuration file, one that guaranties no typing errors, no inconsistencies according to application’s specific logic.

This can be, relatively easily, achieved using a Database!


Database-stored menus… extending and redirecting actions

Let’s go a step forward and use the database to store, for instance, application menus.

A menu is basically a displayed text that, when clicked, invokes an application’s functionality.

By storing menus in the database, we may be wishing to expose only some of our application’s functionalities (according to specific application version for example). We may also be wishing to let our customer’s IT team to expose different functionalities to user groups according to a predefined business role hierarchy.

We can also use this structure to localize our application menus without having to recompile specific localized versions.

Another advantage: to be able to add a new menu after a new functionality is added to the software, or remove one that no more exist etc.


Menus are good examples for the ‘action’ concept. In fact, clicking a menu, a button or other button-like item in the user interface, results in invoking an action in the software. The action to be invoked has an entry point (a function) which is, normally, part of the handled object’s code.


Thanks to .NET System.Reflection (or any Reflection-like library) we can retrieve a method by its name. This can allow us to store object’s method names in the database, and, in the action properties, tell the software which method to be called. The software can then search the defined method, and, if found, invokes it when the action is activated.


Of course there are some other considerations to be taken into account: invoked function parameters, return value... etc. But the main concept remains correct and feasible.


Database-based solutions advantages?

Well, just to name a few:

§  Runtime object properties modification: Imagine a (dynamic) ‘web page section’ object which is initially created as 600/800 pixels dimensions. A database-based solution can allow the user to easily change these properties to obtain, say, a 1027/800 pixels object on runtime… without having to recompile the application’s code;

§  Runtime object properties extension: Software (compiled) objects’ structures NEVER satisfy at 100% real world structures or requirements (at least during a reasonable period of time). With a database-based solution, using, for example, an EAV (Entity Attribute Value) implementation, you can envisage extending compiled software objects… without having to recompile the application’s code;

§  Action processing redirection: Imagine a software functionality that may require authentication only in some contexts and none in other contexts, depending on the customer’s environment. Thanks to database readability and simplicity, the customer can easily choose which entry point to assign to the action according to his or her environment (without having to recompile the software code)