Thursday, June 18, 2009

Compounded filter predicates using Delegates

image






















The ListCollectionView of WPF replaces the DataView of Winforms as the primary object for filtering cached data. Unlike the DataView which encapsulates only DataTable, ListCollectionView encapsulates IList; making it a very flexible solution to your filtering needs. Another big change is the switch from string to delegate for the predicate. A predicate is a Boolean statement used to test if the record qualifies for the filter. In SQL, this is the condition you put in the WHERE section. At first you may think that this is an overkill for a simple task such as filtering but as you will see in this post, delegate improves the maintainability of the codes because it allows easy modularization.

In our simple application, we display the list of all Contacts from the AdventureWorks database using Entity Framework. The user should be able to filter the list using any combination of FirstName, LastName and MiddleName. Three delegates are needed to handle the predicate for each field. Everytime the user types in the text boxes of the search field, the filter is triggered. The predicate set to the ListCollectionView.Filter property is the compounded (AND’ed) result of the 3 delegates. You will see later on that this is not always the case. A result of true means the record is a match.

Before we filter, we fetch the data first:

image

We leverage on generics for a delegate that can handle any record.

image

To make the filter much more efficient, we only apply a predicate when it’s required. For example, if the user did not type anything for the last name, we will not include the last name predicate to the final filter. The filter is now modular and in order to achieve this, we use a list to contain only the needed predicates.

image

Each predicate is initialized with a lambda that is a straightforward comparison between the record field and the content of the control. Note the middle name logic is slightly different because the record property is nullable. Failure to check that would have resulted to an exception.

image

On every TextChanged event of the text boxes, we determine if the predicate mapped to the text box is needed or not. After this, we apply the filter.

image

The SetFilter method determines the logic on when to add or remove the predicate from the list.

image

The ApplyFilter sets the final filter. Filtering can be very taxing. For efficiency, we check if the predicate list is not empty prior to triggering the filter. If the list is empty, we should still check if there’s really a need to filter again.

image

I could have used lambda for the final predicate but having it as a named method makes the logic prominent. I like it this way because it shows how integral the logic really is for the application. Notice that we simply iterate thru all the predicates in the list and compound the result.

image

Here’s our predicates in action.

image

This usage of delegate may be a novelty to you. What’s not novel though is the decision on when to use it. It operates on cached data so it presupposes that you fetch everything from the database. Usually this is not an ideal approach if you have high volume of data for a less manipulative user.

Friday, June 12, 2009

Displaying Hierarchical Data using WPF DataGrid

The WPF DataGrid control of the WPF toolkit has a very interesting feature called row details which can be used to display related data of a selected row. It’s basically a template, much like those in the data controls of ASP.NET. If you create a template with a grid on it, basically you already have a control for displaying hierarchical data. So given the simplified object model below,

image

the markup required to display the items every time an order row is selected would be:

image

The key object here is Binding. It contains the path that tells WPF how to find the data to display. In the code illustration above, the Path property for the child grid is resolved to Items property of the Order bound to the selected row. The data is taken from the DataContext property of the data grid which are set up and assigned using the codes such as these:

image

Voila! The effect is a much friendlier data presentation.

image

Sunday, June 7, 2009

Delegate Contravariance. Say what?

.NET 2.0 started to apply a somewhat obscure programming concept called contravariance to delegates. Delegate contravariance, as what it’s being referred to, allows you to hook a method to a delegate which parameter is a descendant of the parameter in the method. If you’re confused, here’s what it means:

image

In the snippet above, you are able to hook OnAnyEvent even though the CancelEventHandler is defined with CancelEventArgs. This is because CancelEventArgs is a descendant of EventArgs. The EventArgs, under the virtue of polymorphism, can accept the CancelEventArgs passed by the TextBox control.

Where is it?

Delegate contravariance is not apparent in Visual Studio which, in my opinion, mainly contributed to its obscure nature and low adaption. If you hook an event to an existing handler at design time, you're shown only those which signature matches the event. In our example, you won’t see the OnAnyEvent contravariant delegate at all.

image

If you hook manually on the other hand, you’re provided hints which are not helpful either.

image

So the only way to apply delegate contravariance in your code is by brute force. Unless you have explicit knowledge about it, you would never know it’s there. And even to those who are already enlightened, the manual coding still puts them off.

Should you care?

If your codes perform the same routine in different events regardless of the event signature, the decision is no-brainer. I think this is contravariance raison d’ etre. But the thing is, this scenario is very rare. More often than not, you hook to an event because you wanted to execute specific routines and take advantage of the context properties. In our example, we hook to TextBox validating event to validate inputs and control the behavior of the focus using the CancelEventArgs.Cancel property. The question then becomes: Is it worth hooking more than one handler to a particular event to handle the generic and specific routines separately? My answer is NO. Additional handler is additional awareness layer. This practice compels you to always think that something else is hooking to an event, therefore complicating the debugging process. I rather convert the generic handler to a method which I can call within the other handler as shown here:

image

Should you adapt multi-handler approach thru contravariance, just remember that the order of calls follows the order of hooks. So if you wanted to fire the generic handler prior to the specific, you have no other choice but to hook both handlers by code because as you’ve seen a while ago, VS does not allow hooking of contravariant handler let alone 2 handlers, at design time. This necessitates slight modifications in the constructor as shown here:

image

The good thing is that the EventArgs hierarchy is still very shallow. My guess is it’s only two to three levels deep. So most probably you would only hook at most 2 or 3 handlers per event if you follow the event handler-decomposition path to cohesiveness. Still this is not a guard to bad practices because the very nature of .NET event does not prevent anyone from hooking handler to her heart’s content.

So what’s the next move?

My opinions on delegate contravariance are limited only to event-handling so I’m not going to conclude anything about its true merit. I’m still rummaging my old Windows application hoping to find sections I can refactor using this concept. Delegates are all over the place and viewing this concept only within the confine of UI programming is myopic. I’m sure I will find good uses of it nowadays that LINQ and lambda’s are starting to gain momentum.

Tuesday, June 2, 2009

Optional Params Anyone?

During my break today, I was able to skim on some articles about the upcoming C# 4.0. Pretty much everything is evolutionary but one feature stands out from the rest not because it’s revolutionary but because it’s needless and counterproductive. The C# team decided to add optional parameters support to C# ala VB. I’m not a fan of optional parameters and as a matter of fact, I abhor it like Dijkstra abhorred GOTO. It undermines the benefit of overloading. To stretch my point, let’s say you have a class Timer with alarm features and with the following overloads:

public void Start(DateTime startTime)
{
// more codes here
}

public void Start(DateTime startTime, TimeSpan elapsedTimeBeforeAlarm)
{
// If elapsed time is 0 or less, throw invalid argument exception
}

public void Start(DateTime startTime, DateTime alarmTime)
{
// If alarm time is prior to start time, throw invalid argument exception
}

As you can see, each method has distinctive purpose and logic based on their parameters. The first one does not set the alarm whereas the other two sets them but through different means based on the type of the second parameter.

A novice programmer can easily think of optional parameters to implement all of these. He could come up with something like this instead:

public void Start(DateTime startTime, TimeSpan elapsedTime=”0:00:00:00”
, DateTime alarmTime=DateTime.MinValue)
{
// Determine what combination and execute logic accordingly
// In addition, validation is also performed to the parameters

}

Wow! One method to serve them all! Nothing’s cool about this unfortunately. First of all, it’s fat because it’s no longer cohesive. The codes which check for the combination of the parameters supplied do not have anything to do with setting the alarm anymore. It’s difficult to maintain these convoluted codes. I’m not saying that this kind of coding is rampant but hey, it could happen.

Microsoft promised that the new incarnation of the .NET Framework will be a “real upgrade”. It will contain less new classes and more upgrades to existing ones. What I don’t expect are fixes for things which ain’t broke, let alone those that promote bad practices. Optional parameters is in that list. I just hope it’s the only one.

Saturday, May 30, 2009

Enum in Lieu of String Constants

Every now and then, we are faced with situations when using literals seems to be the only way to accomplishing things. Let’s take for example the case of untyped DataSet. One reason why I hated using untyped DataSet is the fact that Intellisense is unable to assist me when accessing the objects of the different collection within it. I'm talking about string indexers which is used to qualify the objects in collection as shown below.

DataTable tblPayers = aDataSet.Tables[“Pharmacy”];
// More codes here
selectedRow[“NCPDPNo”] = “123456”;
There might be typos in my codes already but most probably I’ll find out only during runtime. This situation is even aggravated when you have more than one parts of the codes accessing, let’s say, different columns of a DataTable. In order to be consistent with the indexer qualifier, a good practice is to declare those column names as constants. Ok, ok, some of you might think this is an overkill. Well, it is if you’re dealing with LastName, Birthdate, OrderNo but what if you’re in a totally unfamiliar territory where ClearinghouseSubmitterId, PayerLOB, NCPDPNo and other exotic creatures roam? Trust me, it will pay off sooner or later do it the “overkill” way. So to proceed, you will have something like this snippet:
const string ClearinghouseSubmitterIdColumnName = “ClearinghouseSubmitterId”;
const string PayerLOBColumnName = “PayerLOB”;
const string NcpdpNoColumnName = “NCPDPNo”;
I see nothing wrong with this approach and as a matter of fact, it’s a correct one. But there’s actually shorter and organized one albeit unconventional.

internal enum EnrollmentColumn { EnrollmentId, ClearinghouseSubmitterId, … };
internal enum PayerColumn { NationalPayerNo, PayerLOB, … }
internal enum PharmacyColumn {NCPDPNo, Name, ….}
internal enum Table {Enrollment, Payer, Pharmacy,...};

public class AForm : Form
{
void Foo()
{
DataTable tblPharmacy = aDataSet.Tables[Table.Pharmacy.ToString()];


// Codes to retrieve selected row
selectedPharmacyRow[PharmacyColumn.NCPDPNO.ToString()] = “12345”;
}
}
I know what you’re thinking right now. Enum is not built for this. I agree but as you can see, with the aid of Intellisense, enum becomes a convenient and safe way to code. First of all, it’s shorter to declare enum. You only need to type the name and the ToString() will take care of the rest. One thing to remember though is that the equivalent column or literal should not contain space. So enum is ruled out when you have columns like “Last Name” since space is an invalid token in .NET. Second, the code is a little more organized this time. The name of the enum can be the name of the table. Of course you can also employ other implementation like a static class with a bunch of read-only string get properties but again more coding is involved.

Sunday, April 19, 2009

Using Table Data Type for Variable-length Parameterized Search

The table data type is introduced in SQL Server 2008 to address the clamor of the community for an efficient means of inserting and updating multiple rows in the database. What used to be a task involving multiple calls to the database can now be achieved in one swoop. True to this objective, it’s no surprise that almost all discussion of table data type usage deals about this topic. Another one which is rarely discussed is on how table data type addresses one of the most volatile code construct in data-driven application – the variable-length parameterized search construct. This is the code construct for a search wherein you allow the user to specify 1 to n number of values for filtering a certain column. The user interface usually resembles the one below:

image

The interface above is obviously simplified. Most of the time, it involves a filter for almost every column in the result. The assumptions here are that the application does not cached any fetched data and the team has been living too long inside the cave that they haven’t heard about LINQ yet. Before SQL Server 2008 and LINQ, there are two approaches to achieving this, each has it’s own pros and cons.

The first approach is maintenance-free but opens your database to a possible SQL-injection attack. It involves a dynamic query which is composed of multiple strings. One of these strings is passed from the frontend application because it contains the values for the filter. The structure of the stored procedure may look like this:

CREATE PROCEDURE FilterDynaQuery @filterValues  VARCHAR(8000) AS
DECLARE @select VARCHAR(2000)
,@sort VARCHAR(500)
SET @select = ‘SELECT col1, col2, col3, … FROM Table1’
SET @sort = ‘ ORDER BY col1, col2, col3,…’
EXEC sp_executesql (@select + filterValues + @sort)

The @filterValues must contain all he hardcoded values from the frontend. The coder must make sure that regardless of the intention of the frontend, the concatenation of the all the components of the query should be valid. The argument passed should conform to the construct “ WHERE <column> IN (val1, val2,…valn)” like the one shown below
‘ WHERE col1 IN (1,5,8,4)’

The second approach ensures the safety of the database but couples the codes to the number of possible values in every filterable column. If the business adds or removes value allowable for that column, then the signature of the store procedure and the front-end codes should also change. For example, if there are 3 allowable values for that column, you need 3 parameters on for that column. Here’s how the procedure would then look like:

CREATE PROCEDURE FilterExplicitParams @value1 INT, @value2 INT, @value3 INT AS
SELECT col1, col2, col3 FROM Table1 WHERE col1 IN (@value1, @value2, @value3) ORDER BY col1, col2, col3

If you have many possible values for the column to be filtered, using this approach would surely bloat the codes. We all know that the more codes you write, the greater the chance for bugs and delays. Most coders - me included - would rather compromise security a bit, in exchange for easily maintainable codes. This is why the dynamic query is much preferred.

The New Approach

The table data type provides you the benefits of both approach without the compromises. However, be aware that RAD tools have no full support for queries with table-valued parameter, at least for now. In ASP.NET, you cannot use the SqlDataSource directly because you will not be able to fetch the schema of the result. ASP.NET requires the schema to configure the data control to which the data source is bound. This means executing the procedure using the dialog shown below. The problem is that it cannot accept the .NET types mapped to a SQL Server table type.

image

With ObjectDataSource this is not an issue because the tool doesn’t have to query the database for the schema. The quickest way to create an object for the result of our procedure is to make use of typed DataSet. Yes, this somewhat misunderstood and easily abused component is a boon for this kind of situation in a data-centric application. The stored procedure which will be discussed momentarily would become the source for the select command of the TableAdapter. If you’re new to typed DataSet, an excellent walkthrough can be found here.

For the sample application, we retrieve all the current employees from the AdventureWorks database. The tables involved are shown below.

image

Since the data is temporal, I decided to create a view which would contain only the current set of employees.

CREATE VIEW HumanResources.CurrentEmployee AS
SELECT e.NationalIDNumber, c.LastName, c.FirstName, c.MiddleName,
d.DepartmentID, d.Name AS Department, e.EmployeeID
FROM HumanResources.EmployeeDepartmentHistory h
JOIN HumanResources.Department d ON h.DepartmentID = d.DepartmentID
JOIN HumanResources.Employee e ON h.EmployeeID = e.EmployeeID
JOIN Person.Contact c ON e.ContactID = c.ContactID
WHERE (h.EndDate IS NULL)
The stored procedure accepts a table-valued parameter of type IntId. This is just a one-column table type that can be used to filter a integer column, just like the Employee.DepartmentId. Filtering a column is achieved by a join to the table or view to be filtered; in our case the CurrentEmployee
CREATE TYPE IntId AS TABLE
(
[Id] INT NOT NULL PRIMARY KEY
)
GO
CREATE PROC FilterEmployeeByDepartment
@DepartmentIds IntId READONLY
AS
SET NOCOUNT ON

SELECT e.EmployeeID, e.NationalIDNumber, e.LastName
, e.FirstName, e.MiddleName, e.Department
FROM HumanResources.CurrentEmployee e
JOIN @DepartmentIds ids ON e.DepartmentID = ids.Id
GO
Examining the parameter of the Select command in the TableDataAdapter would reveal that the mapped .NET object for the SQL table type is System.Object.

image

Don’t be dissuaded by what the editor seems to suggest. The only types you can use according to the documentation are DataTable, DbDataReader and IEnumerable. But even without having read the documentation, you would have probably used DataTable anyways; it’s just too obvious. Among the 3, IEnumerable still eludes me and I’m still struggling to get my first shot with it. I could care less; for now DataTable is perfectly fine for the job.

Setting up ObjectDataSource with typed DataSet is fairly easy. You can use the TableAdapter directly as shown below. In the next step, Visual Studio lets you specify which method is mapped to which CRUD method. With the sample application, the Get method of the adapter is used for the SELECT and the rest of the CRUD are just left blanks. The argument for the parameter is set to get its value from the Session.

image

The rows from the HumanResources.Department table should be fetched too. In the sample application, a SqlDataSource is used for this. A list box is bound to this source while a grid view is bound to the object data source discussed a while ago. There is no code necessary to populate the list box. As for the grid view, a dummy table is supplied during the loading because null is not yet supported by the ObjectDataSource with table-valued parameter. In the Find button click, the table is populated accordingly prior to passing it to the data source.

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable tbl = CreateDeptFilterTabl();
Session["DepartmentIds"] = tbl;
}
}

protected void btnFind_Click(object sender, EventArgs e)
{
DataTable tbl = CreateDeptFilterTable();
GridView1.Caption = "Employee(s) from ";
foreach (ListItem item in ListBox1.Items)
{
if (item.Selected)
{
tbl.Rows.Add(item.Value);
GridView1.Caption += (item.Text + " ");
}
}
Session["DepartmentIds"] = tbl;
DataBind();
}

DataTable CreateDeptFilterTable()
{
DataTable tbl = new DataTable();
tbl.Columns.Add("id", typeof(int));
return tbl;
}

Codes

You may download the codes here. If you don’t have AdventureWorks database, you can download it here. Be sure to change the connection string before you run the application.

Friday, April 10, 2009

SqlUserDefinedAggregate.IsNullIfEmpty: Does it work?

No. At least for me. I haven’t made this one work at all and I always have to resort to a dirty workaround. According to MSDN documentation, setting this property to true should direct your aggregate to return SQL-null when applied to an empty table which is exactly what you wanted. However, this is not the case. Let’s take a look at this naive example of a UAG which simply concatenates the string value of a column:

[Serializable]
[Microsoft.SqlServer.Server.SqlUserDefinedAggregate(
Format.UserDefined, MaxByteSize=8000, IsNullIfEmpty=true)]
public struct ConcatStr : IBinarySerialize
{
SqlString _concatenatedStrs;

public void Init()
{
_concatenatedStrs = null;
}

public void Accumulate(SqlString value)
{
if (value == SqlString.Null)
_concatenatedStrs += value;
}

public void Merge(ConcatStr group)
{
_concatenatedStrs += group.Terminate();
}

public SqlString Terminate()
{
return _concatenatedStrs;
}
#region IBinarySerialize Members

void IBinarySerialize.Read(System.IO.BinaryReader r)
{
_concatenatedStrs = new SqlString(r.ReadString());
}

void IBinarySerialize.Write(System.IO.BinaryWriter w)
{
if (_concatenatedStrs != SqlString.Null)
w.Write(_concatenatedStrs.Value);
}

#endregion
}

There’s nothing fancy about the codes and its implementation is pretty much straightforward. The quirk is, you don’t get a “NULL” if you apply this to an empty table as you see here

image

The workaround is simple. You need a flag that you can check if the Accumulate() method has been called or not. Accumulate() is called for every row in a table so no-call on this means the table is empty. Here’s the modified codes for our string aggregator

[Serializable]
[Microsoft.SqlServer.Server.SqlUserDefinedAggregate(Format.UserDefined
,MaxByteSize=8000, IsNullIfEmpty=true)]
public struct ConcatStr : IBinarySerialize
{
SqlString _concatenatedStrs;
bool _isEmpty;

public void Init()
{
_concatenatedStrs = null;
_isEmpty = true;
}

public void Accumulate(SqlString value)
{
if (value != SqlString.Null)
{
_concatenatedStrs += value;
if (_isEmpty==true)
_isEmpty = false;
}
}

public void Merge(ConcatStr group)
{
_concatenatedStrs += group.Terminate();
}

public SqlString Terminate()
{
if (!_isEmpty)
return _concatenatedStrs;
else
return SqlString.Null;
}
#region IBinarySerialize Members

void IBinarySerialize.Read(System.IO.BinaryReader r)
{
_isEmpty = r.ReadBoolean();
if (!_isEmpty)
_concatenatedStrs = new SqlString(r.ReadString());
}

void IBinarySerialize.Write(System.IO.BinaryWriter w)
{
w.Write(_isEmpty);
if (!_isEmpty)
{
if (_concatenatedStrs != SqlString.Null)
w.Write(_concatenatedStrs.Value);
}
}

#endregion
}

You shouldn’t forget to serialize the flag. Failure to do so wouldn’t preserve its value and it would always have the value in the initialization. If you put a breakpoint, in the terminate event, you could clearly say this one works.


image

And the result is what you expected:
image

The same workaround can be applied to any data type of your return value, be it a value-type or UDT. For example, if you don’t apply a workaround like the one below to an integer UAG, you get zero instead of null for an empty table!

[Serializable]
[Microsoft.SqlServer.Server.SqlUserDefinedAggregate(Format.Native
,IsNullIfEmpty=true)]
public struct SumInts
{
int _accumulator;
bool _isEmpty;
public void Init()
{
_isEmpty = true;
}

public void Accumulate(SqlInt32 value)
{
if (value != SqlInt32.Null)
{
_accumulator += value.Value;
if (_isEmpty)
_isEmpty = false;
}
}

public void Merge(SumInts group)
{
_accumulator += group.Terminate().Value;
}

public SqlInt32 Terminate()
{
if (!_isEmpty)
return new SqlInt32(_accumulator);
else
return SqlInt32.Null;
}
}

I still hope I would be proven wrong with my findings. But until then, I just have to content with this dirty codes. What’s important is that it works.