Taoffi's blog

prisonniers du temps

Windows Vista / Windows 7: To pin or not to pin, that is…

Have you ever tried, in Windows Vista or 7, to pin to the start menu (or to the task bar), an item whose name contains ‘documentation’?

Well, that is simply impossible (and, above all, forbidden!)

(You may have a look at this discussion… hope the link will still be aliveJ)


Why?... and Who decided this?



In Windows Vista or 7, you cannot pin to the start menu (nor to the task bar), any item whose name contains one of the following words (quite long list... long list J):

·         Documentation

·         Help

·         Install

·         More Info

·         Read me

·         Read First

·         Readme

·         Remove

·         Setup

·         Support

·         What's New


Note that this doesn’t still tell us any useful information about WHY are these words excluded from ‘pinnable’ items. And what logic is behind this choice?!

Nobody and no literature want to explain something plausible about this mysterious choice.


Still you can do It!

Curiously enough, you can still pin an item whose name contains one of these blasphemed words. Without even going to the famous ‘Registry’, just try the following:

·         Rename your item to be pinned (example: remove just one character of ‘documentation’ to obtain something like ‘documentatio’);

·         You can now pin your item to whatever you want;

·         Rename again the item to its original name;

·         Rename the pinned item to the name you like.



As for ‘Who’ decided and designed this genius (customs-office-attitude-like) feature?... It seems that those are the same Microsoft’s young people playing with Windows Interface, under the name of “Application User Model ID” to deliver us some awesome features (like sub folders hysterically bouncing down when you expand them: see this post).

They, apparently, continue to care about us in Windows 7

God bless them all… hope they will still be there in Windows 8.


Is it a shame?

As you may have noticed, the link to http://support.microsoft.com/kb/282066... The page where this design is confirmed doesn’t exist anymore!


Sorting dates: Ascending, Descending OR…

This is a small story, yet with something special:

Once upon a time, there was a list of events stored into a database table. Each event had (evidenceJ) a date.

A friend of mine asked me to sort these event items.

I asked, as you may imagine: Ascending or Descending?


But this, apparently, seemed too simplistic for him…

- I want the most recent to appear first. He said.

- Well, that means you want to sort in descending order.

I gave him a demo of data sorted in descending order…

- No, he said, that is not what I want!


After a short discussion, I understood that what he wanted was:

·         To first have the incoming events (i.e. those located after “today’s” date… sorted in an ascending order)

·         Followed by older dates (sorted in ascending order)


I first thought: can ORDER BY do something else than sorting in ascending / descending?...

As the answer was, evidently, No… I said: Sorry, but that is not possible!

The question remained in my mind however. And I started looking for a solution (for myself!)

The experimentations didn’t in fact last long, the solution was quickly found:


All what we need is to:

§  Categorize dates according to their location relative to Today (or any other logic);

§  Give each category a ‘sortable’ value (integer for example)

§  Sort by the category’s value, followed by the date value.






      CASE WHEN event_date >= getutcdate() THEN 1

            ELSE 2

      END               AS date_category  -- categorize date

FROM         dbo.sight_conferences

ORDER BY date_category, event_date



Screenshot of the output data sample




The key part of this code is the logic of categorizing dates. In this sample, categorization was quite simple (set a category according to date location relative to Today). But, of course, we can use another logic scheme to obtain data sorted accordingly.

Organize your MSDN Help Favorites

If you regularly use MSDN help (Visual Studio Documentation or MSSQL Server Books OnLine (BOL)) you may have noticed that it is not possible to sort or search the list of help favorites.

Migrating these favorites to another machine is almost more painful!

I suffered from these problems for a long time, until I decided to write a tool to help resolving these lacks.

What does the tool do?

HelpFavoriteOrganizer can locate and read your Favorites (xml) file (for Visual Studio or MSSQL documentation) and allow you to sort and search favorite topics. It also locates duplicated topics (i.e. topic having the same help addresses)

You can then save you favorite file, to either a new xml file or overwriting the original XML favorite file.

Another useful feature is to import (merge) an existing xml favorite file into your favorite topics. This can allow an easier roaming life, and can also be used to share your help favorites with someone else.


ATTENTION: be careful when deleting items or overwriting files because this tool DOES NOT ask any confirmation. (i.e. use it at your own risk!)

That said (!), you can download it Here: HelpFavoritesOrganizer.zip (34.82 kb)

Some screen captures

Try to locate and load either VStudio help or SQL help favorites






Sort / Search your topics… items highlighted

Save the list either to a new file or to the original help favorites file.



Locate / delete duplicated topics (As you can see, I have no more duplicatesJ)



Import (merge) another favorites xml file


Managing databases periodic membership (or: unique time span indexing) Part II

Ho to view periodic relationship data

In the previous post, I exposed a method for uniquely indexing time spans of periodic-memberships.


Here, we will discuss the next task: How to view historical data in such structures?

To illustrate this, we will talk about a portfolio sample data, simply because this is a more elaborate case (than the hotel/room reservation case).


Suppose we have:

§  A portfolio named ‘Sample portfolio’

§  A set of companies: company 1, company 2 and company 3

§  A set of daily historical data for each company for the period from 2010/01/01 to 2010/01/10


Now suppose that:

§  Company 1 and company 3 are ‘permanent members’ of the portfolio starting at 2010/01/01

§  Company 2 is a member of the portfolio for the following periods:

o   2010/01/01 to 2010/01/05

o   2010/01/08 to à endless


To query the daily historical data for company 2 related to its parent portfolio, we should thus obtain the data for the periods where it is effectively a member of the portfolio:

§  2010/01/01, 2010/01/02, 2010/01/03, 2010/01/04, 2010/01/05

§  2010/01/08, 2010/01/09 and 2010/01/10


(Note that data for 2010/01/06 and 2010/01/07 should be ignored)


This can be done using a view similar to the following (TSQL followed by the view design diagram)


SELECT     p.name AS portfolio,

                c.name    AS company,




FROM dbo.portfolio_companies AS pc INNER JOIN

                      dbo.portfolios AS p ON pc.portfolio_id = p.id INNER JOIN

                      dbo.company_data AS history

                ON pc.date_start <= history.date

                               AND ISNULL(pc.date_end, CONVERT(datetime, '9999/01/01')) >= history.date INNER JOIN

                      dbo.companies AS c ON history.company_id = c.id AND pc.company_id = c.id


As said above, company 2 is a portfolio member during the following periods:

§  2010/01/01 to 2010/01/05

§  2010/01/08 to à endless




With our sample history data, this view produces the following data for company 2 (8 entries):



Note: the history data table contains the following data for company 2 (10 entries):



Managing databases periodic membership (or: unique time span indexing)


The relations between some ‘real world’ objects can sometimes be in the form of ‘periodic membership’. By ‘periodic membership’, I mean the context when one object can be member of another during one or more periods of time.


·         A person who occupies a hotel room during a period of time;

·         A company which is member of a portfolio during a period of time;

·         … etc.


The context also assumes that we want to keep the membership history and be able to build data aggregations that take into account these periodic memberships. (For example: be able to calculate portfolio performance during a period of time that spans several ‘periodic memberships’).


A concrete example may better explain the case:

§  We have a portfolio for which we want to maintain historical performance during time;

§  At 2009/01/01, the portfolio contained : company1, company2 and company3;

§  At 2009/03/01, we changed the portfolio components and excluded company2. (Now the portfolio contains only company1 and company3);

§  At 2009/06/01, to calculate the portfolio performance for the period 2009/01/01 to 2009/06/01, we should take company2 into account for the period 2009/01/01 to 2009/03/01 (although it is no more part of the portfolio).


Knowing that database engines do not offer a ‘time-overlap’ unique indexing features, resolving this situation needs a structure that allows us to assign and manage periodic membership indexes.

Note: I am surely not the first to confront this context, but I wanted to share my experience to resolve this problem and will be glad to receive any thoughts about it.


Periodic membership multiplicity models

In my experience, I encountered two possible types of multiplicities related to periodic relationship:

§  One-to-one periodic membership: a good example for this would be a hotel room that can be occupied only by one person during the same period (i.e. period is unique per room);

§  One-to-many periodic membership: a good example for this would be a portfolio which can have more than one member for the same period (i.e. period is unique per portfolio-member).

In this article, I will explain how to handle both of these types.


Hotel room reservation, the basic structure

To demonstrate a hotel reservation periodic membership (uniqueness of room/reservation period), we can create the following table and relationships:


§  Hotel clients: contains client list items

§  Hotel rooms: contains room list

§  Hotel room reservations: contains client/room reservation periods


Note: the date_end field of the reservations table can be null, to allow ‘permanent’ (or endless) reservations.


To ensure uniqueness of reservation periods, we will create a scalar function (returning a Boolean value) that can be used as Check Constraint on the hotel_room_reservations.


CREATE FUNCTION [dbo].[is_valid_hotel_reservation_period]


       @item_id     int,

       @room_id     int,

       @date_start  datetime,

       @date_end    datetime





       -- validate the provided parameters    

       if @date_start is null or @room_id is null

             return 0


       -- be sure start date < end date 

       if not @date_end is null


             if @date_start >= @date_end

                    return 0



       -- is this the first reservation period for this room?

       if ( select count(*)

                    from dbo.hotel_room_reservations

                    where( room_id = @room_id) ) <= 0

             return 1


       -- check overlapped periods

       if @date_end is null              -- is this a permanent (endless) reservattion?


             if ( select  count(*)

                    from dbo.hotel_room_reservations

                    where( ( room_id = @room_id)

                                  and( id != @item_id)

                                  and(( date_end is null) or (date_end >= @date_start))

                           )) > 0

                    return 0




             if ( select  count(*)

                    from dbo.hotel_room_reservations

                    where(       (room_id = @room_id)

                                  and( id != @item_id)

                                  and( date_start <= @date_end)


                           )) > 0

                    return 0




       -- return OK

       return 1



We can now use this function as check constraint on the reservation table:



Overlapping entries in the reservation table would now display an error message like:

The Portfolio/company periodic membership case

In portfolio/company case, membership should allow multiple membership instances for different periods. That is: the same company can be member of the same portfolio several times as long as the membership periods do NOT overlap.


Our tables and relationships may look like the following:


All what we need is to create a new version of the above function, and use it as a check constraint condition for the portfolio companies table:


CREATE FUNCTION [dbo].[is_valid_portfolio_company_period]


       @item_id     int,

       @portfolio_id int,

       @company_id  int,

       @date_start  datetime,

       @date_end    datetime





       -- validate the provided parameters    

       if @company_id is null or @date_start is null or @portfolio_id is null

             return 0


       -- be sure start date < end date 

       if not @date_end is null


             if @date_start >= @date_end

                    return 0



       -- is this the first membership period for the portfolio/company?

       if ( select count(*)

                    from dbo.portfolio_companies

                    where( portfolio_id = @portfolio_id)

                           and( company_id = @company_id) ) <= 0

             return 1


       -- check overlapped periods

       if @date_end is null              -- is this a permanent (endless) membership?


             if ( select  count(*)

                    from dbo.portfolio_companies

                    where( company_id = @company_id

                           and( portfolio_id = @portfolio_id)

                           and( id != @item_id)


                           )) > 0

                    return 0




             if ( select  count(*)

                    from dbo.portfolio_companies

                    where( company_id = @company_id

                           and( portfolio_id = @portfolio_id)

                           and( id != @item_id)

                           and( date_start <= @date_end)


                           )) > 0

                    return 0



       return 1



We can, now, use the function as a check constraint condition for the membership table:



Possible extensions

It seems that, with some more efforts, this can evolve to a generic Time-Span unique indexer.

Waiting to hear some thoughts about thisJ!

Silverlight database to DataGrid, yet another approach- Part V

The data record (the ‘form’)

As I mentioned in Part II, my proposed solution (aimed to transfer and communicate data between a Silverlight Client and the database server) is composed of the following schematic 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 SilverMetaColumn class is the key class which will transport many of business logic information from the database server to the client (and back to the server).

A meta-data column object of this class can transport information like:

§  The column’s data type;

§  Can the column contain null value?

§  The semantic type of the field (ex: control type… i.e. is this an option list? a value entry field?…)

§  Valid value ranges;


§  etc.


What I want to expose here is: how to use this meta-data column object to ‘automatically’ (or semi-automatically) compose a data record (form) on the client side.


From the field semantic àto the control àto the form

After having examined many of the data entry forms in various contexts, I think that a data entry (from the user interface point of view) is either:

§  A value entry control (i.e. a TextBox or TextBox-like: Numeric Up-down control for example)

§  Or a choice control (i.e. a ListBox, ComboBox, CheckBox, Radio-buttons-collection or other type of collection container controls)


Of course, the visual aspect of the control and its interactivity scenario may vary… but its presentation-semantic remains the same: a value entry or a choice.

From the business logic point of view (at the server side), what is important is not the visual aspect or visual transitions for presenting and collecting the data. What is important is the conformance of the collected data to specific business logic constraints:

§  Does the entry conform to the required data type?

§  Does the entry conform to the required valid range?



According to this approach, we can imagine a solution where the server tells the client:

§  Here is the requested data record composed of:

§  Column 1 : this is the record key column, It is Read-only (i.e. it will be handled at the server)

§  Column 2: this is an entry of data type Text, Required (cannot be null), cannot exceed 50 characters, Current value is “sample entry”;

§  Column 3: this is an entry of data type integer, Can be null, Valid range is 0 through 40, Default is 25, Current value is 32;

§  Column 4: this a single choice of the following option list (x1, x2, x3), Cannot be null, Current value is x2;

§  Column 5: this a boolean value, default is True, Current value is False;



Receiving this information, the client can then undertake the presentation process, for example:

§  Start record presentation transition (animation);

§  For each column, create the corresponding control (ex: according to the user interface graphical chart);

§  Set each control’s properties to conform to business constraints (read-only, max chars, valid values check… etc.)


Here is an example of a solution using this approach:


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:


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)

'Strategic' Pause!


NOTE: I found that Dick Brass's article is an interesting insider view. That is why I decided to publish it here in its entirety.



Microsoft’s Creative Destruction




Published: February 4, 2010

International Herald Tribune

















