Sunday, September 21, 2014

Constructor Parameters

It's funny, in all my years of writing software I have never given much thought to when I should use parameters in a constructor verses setter properties (or getXXX / setXXX methods for you Java people). I always just picked it based upon what I saw as convenience. Usually convenience to me meant less lines of code. For example:

MyClass myClass = new MyClass("hello world");

Is shorter than saying:

MyClass myClass = new MyClass();
myClass.Text = "hello world";

But the other day I was once again overriding the GetHashCode method for a .NET class because I had overridden the Equals method and you should override both at the same time.  Usually I just don't care much about this method and write some probably incredible poor hashing method (aka, GetHashCode of some properties)

Well, I decided to do a bit of a Google for a proper hash method. I actually found some very interesting proposals and looked to implement some of them.  All of the methods of overriding GetHashCode look at using the fields in the class to develop a unique hash.

Now, the important thing about the GetHashCode method is that the result from it must be immutable for the class.  Since we are basing our hash off of some class fields, those fields must now also be immutable.

Let's say you have a class called Person. It would seem reasonable that the hash code be based upon the person's name. Every class with a name of John Doe should generate the same hash code.

But here in comes the problem, what if the name changes? We want the GetHashCode to always return the same thing for the class and we need the name to be immutable now. This is especially important if that class is added to a list or becomes a key to a dictionary.

And so here I was lead to my "AH HA!" moment. Parameters passed in with the constructor should be considered immutable and define the class for its life time. Any constructor parameter should not be allowed to be changed after the instantiation of the class. This way the GetHashCode always returns the same value regardless. So, my person class gets a constructor of Person(string firstName, string lastName). Now forever going forward those two properties are fixed to the class and the GetHashCode always works.

Class fields that are accessed via set properties (or setXXX methods) are mutable and therefore cannot be used for hashing. So, for my Person I may have mutable properties, but the name is now considered fixed.

Person myPerson = new Person("Jane", "Doe");
myPerson.Slogan = "Hello World!!!";

In this case, the name is immutable, whereas the slogan is not.  The slogan cannot participate in hashing.

In Conclusion

I am proposing that class constructor parameters be immutable and used to define the class when implementing of the Equals and GetHashCode methods. Alternatively, getter/setter properties or methods for immutable properties should throw an exception if a calling method attempts to change the value.

A word of caution

All constructor parameters that participate in the hash code themselves must also be immutable.  Following this principle though out your classes will ensure that, but if parameter's object can change its hash code, then your classes hash code is no longer fixed.

 


Wednesday, May 14, 2014

Simplied reading of code

So I recently was working on refactoring a piece of code I found online. It was this:
if (this.itemUnderDragCursor == newItem)
    return;

// The first pass handles the previous item under the cursor.
// The second pass handles the new one.
for( int i = 0; i < 2; ++i )
{
    if( i == 1 )
        this.itemUnderDragCursor = newItem;

    if( this.itemUnderDragCursor != null )
    {
        UIElement item = this.GetSelectorItem(this.itemUnderDragCursor);
        if( item != null )
            SelectorItemDragState.SetIsUnderDragCursor( item, i == 1 );
    }
}
Now looking at this code, it's tough to tell what exactly it does. Refactoring it, same functionality, but much easier to read:
void UpdateItemUnderDragCursor(object newItem)
{
    if (this.itemUnderDragCursor != newItem)
    {
        SetItemSelectedState(itemUnderDragCursor, false);
        itemUnderDragCursor = newItem;
        SetItemSelectedState(itemUnderDragCursor, true);
    }
}

private void SetItemSelectedState(object itemToSetState, bool state)
{
    if (itemToSetState != null)
    {
        UIElement item = this.GetSelectorItem(itemToSetState);
        if (item != null)
            SelectorItemDragState.SetIsUnderDragCursor(item, state);
    }
}
Lesson here is that code can be made complex to read and maintain or can be made easy.

Tuesday, April 3, 2012

Favoring Inheritance

I started refactoring a core library used in software we've been developing for the past few years. One of the common tasks in the library is converting an object to a database primary key value, which is always an int.

The code was littered with the following checks at the top of every method. Of course it changes based upon the type, but the logic was the same. And worse, since I wrote the same check over and over again, I inconsistently implemented my logic checks. The general idea is to check that object is a provided type, check that the provider is a specific instance type, then get the ID:
if (patient is PathProvidedPatient == false)
    throw new ArgumentException("Patient argument must be of type PathProvidedPatient");

if (((PathProvidedPatient)patient).IPatientProvider is WCF_PatientProvider == false)
    throw new ArgumentException("Patient argument property IPatientProvider must be a WCF_PatientProvider class.");

WCF_PatientProvider patientProvider = ((PathProvidedPatient)patient).IPatientProvider as WCF_PatientProvider;

int PatientID = patientProvider.GetPermanentObjectKey(patientProvider.GetObjectKey((PathProvidedPatient)patient));
My first step at refactoring this code was to pull this repeated code out into methods:
public int GetPatientId(PathPatient patient)
public int GetCaseId(PathCase Case)
public int GetSampleId(PathSample Sample)
Etc...

This cleaned up the code quite a bit! But suddenly I was hit with another problem. While these individual functions knew the type, I had refactored earlier and created some generic functions to take a IPathWithObjectID, from which all the "provided" versions of the objects derive. Now I was in trouble!

A little background. Using a classic Bridge Pattern, a provided implementation stores a reference to an ObjectID and a provider class. When a request comes into the provided object, it turns it around and calls the provider class with the objectID to fulfill the request.

And now back to the story at hand... my first go around looked something like this:
if (myObject is PathSample)
   return GetSampleId((PathSample)myObject);
if (myObject is PathPatient)
   return GetPatientId((PathPatient)myObject);
if (myObject is PathCase)
   return GetCaseId((PathCase)myObject);
Uh oh! This isn't looking very good. Multiple if statements or a switch statement usually is a sign of a poor design.

What is needed here is abstraction. What really should happen is the provider should know how to get the database ID value. But how do we get the provider?

The first thing I looked at was provider hierarchy.

All WCF_XXXProvider classes implement their corresponding IXXXProvider interface that implements a common interface IPathProvider.

So far so good, every provider is deriving from a common type of IPathProvider.

I next looked at the Provided Objects inheritance hierarchy.

PathProvidedXXX classes all implement the IPathProvidedObject interface that implements the IPathWithObjectID interface.

Again, looks good!

I decided to add a property to the IPathProvidedObject interface:
IPathProvider Provider { get; }
Now, I had to go implement that property in each of the derived classes. A pain, but no challenges because every provided class already has a property that is deriving from IPathProvider.

OK, so now regardless of the provided object, I can retrieve the provider via my new property and the ObjectID (via a property required by the IPathWithObjectID interface). So far, so good.

Next I turned to looking at my specific provider implementations. All of my providers implement the WCF_IProvider interface as well as the IXXXProvider interface. This is good as well.

I added another method to the WCF_IProvider:
int GetObjectPermanentIdentifier(IPathProvidedObject obj);
And then implemented this method in each of the classes that implement the WCF_IProvider.

So my large if statement mess cleans up nicely into a very simple method:
public int GetPermanentObjectKey(IPathProvidedObject obj)
{
    if (obj.Provider is WCF_IProvider)
    {
        return ((WCF_IProvider)obj.Provider).GetObjectPermanentIdentifier(obj);
    }

    return 0;
}
So, what is the advantage??

First off, the code is simple. It is easy to read and understand.
Second, it is extendable. When I add a new class (which I am sure I will), I will not forget to update some massive if statement. In fact the compiler will force me to implement the correct functionality by requiring me to implement the members of the interface.

Learning to program is not the same thing as learning to be a software engineer. It takes finesse and there is an art to making good code. But once you learn it, your code will be flexible, maintainable, and easy to test.

And having a good suite of unit tests enables you to refactor and validate your changes.

Thursday, March 22, 2012

Abstraction by methods..

I recently wanted to refactor a database connectivity framework to support another type of key in the system.

At first glance, this seemed easy.  Every object implements an interface called IPathWithObjectID, that specifies the object must have a property:
object  ObjectID { get; }

Since ObjectID can be any object, it should be trivial to switch things to a string or something else.

The problem, however, lies in the details.

Most methods did this:

int ID = (int) MyObject.ObjectID;

At the time it seemed simple enough, but in hindsight, this is very limited.

A better approach would be to encapsulate the type cast into a method, which is what I refactored the code to do:

public int GetObjectKeyAsInt(IComparable ObjectKey)
{
    if (ObjectKey != null)
    {
        if (ObjectKey is int)
            return (int)ObjectKey;

        throw new ArgumentException("The ObjectKey property is expected to be of type 'int'.");
    }

    throw new ArgumentException("The ObjectKey is null!");
}

Now, in reality all this method does is do a type cast, with some checks. But the power in it is later on I can refactor what is stored in the ObjectID.

So, my code goes from:

int ID = (int) MyObject.ObjectID;

To

int ID = GetObjectKeyAsInt(MyObject.ObjectID);

Maybe I want an ObjectID to be a new class called MyDataKey. Rather than changing hundreds of different places across the code base, I just change one. The GetObjectKeyAsInt method.

Methods provide a powerful mechanism of abstraction. Use them as often as possible, even if the action seems as trivial as a typecast.

Monday, February 21, 2011

My take on MVVM, I like to add a "C" so we get MVVMC

There is a lot on the web about the Model-View-ViewModel (MVVM) pattern. To me, overall, it seems like a great way to go for developing testable, extensible user interfaces. However, I have run across a few areas where I'm not in total agreement, and other areas where I just think MVVM blogs just gloss over details of things that I think are really important. In my next few blog posts, I hope to outline how I see MVVM and how I have chosen to implement it. I may not be correct in everything, but I hope to present a direction to go for development.

My ultimate goals are to develop code that is consistent, easy to read and follow, and hopefully automatically testable via unit testing or other automation.

The first thing I propose doing is removing control logic from the ViewModel. In most MVVM implementations, you see the VM containing the control logic, for example, if a "Save" button is clicked, we see the VM responding to the command and writing the data to the database. I don't like this. It's not that having it in the VM is a bad thing, it is encapsulated and away from the view. But to me the VM should be light weight, responsible only for transforming model data into a data format easily digestible by the view and for gathering user input back from the view.

By moving control logic, validation, etc. into a controller class, this allows the view model to focus on it's job, makes it easier to read, and I think makes it easier to test the controller.

Here is a diagram of my structure.  Unlike most MVVM models, I take into account using MVVM on custom controls as well as Main UI windows.   Designing a custom control (that derives from User Control) and using the MVVM pattern requires departure from the traditional MVVM pattern.


In looking at the model, we see a departure from the classic MVVM model where the view only accesses only the ViewModel.  If the setup is for a top-level window, and not a control, then things become just like the classic MVVM model.

But when making a user control, their are things that belong to the view in the WPF world and we really need them to notify the controller.  Dependency properties are a prime example of this.  They are attached to the code-behind of an XAML file, which really belongs to the view.  In this case, the view needs to inform the controller module that a dependency property has been updated and let the controller respond appropriately.  And the controller needs to inform the view when a dependency properties value should change.  If we are not working on a user control, then everything goes back to normal MVVM where the view has no knowledge of the controller or view model.

However, if we look at a dependency diagram, I think the view have knowledge of the controller is OK.   After all, dependencies still only go one way and this is fine.  It still allows us to replace the view with a unit test and not have anything break.




It is this important that dependencies flow one way.  This is critical for being able to test and for a clean architecture.  The View has knowledge of the ViewModel and possible the Controller.  The Controller and possible the ViewModel has knowledge of the Model.  In this model, the View can be replaced without the knowledge of any of the underlying layers.

Messaging up the chain takes place via events.  If the ViewModel needs to notify the View of changes, this is accomplished by raising an event and allowing the View to listen for it.  The WPF way of doing this is to use the INotifyPropertyChanged interface. 


 It is critical to use interfaces whenever possible.  An interface allows us to swap out components with testable components.  An interface between the ViewModel / Controller and Model allows us to unit test the ViewModel / Controller by creating a mock model. 


In developing the ViewModel and Controller, it is critical that these classes be separated from any UI components, including opening new windows.  Every action within the view model and the controller should be completely contained.  Opening a new window would be instantiating another view, which violates the requirement that the ViewModel and Controller have no knowledge of the View.  Additionally moving things on and off the UI thread is something that belongs in the domain of the View.  However, often it is the Controller that makes this move.

In order to accomplish application tasks, such as opening new windows and putting things onto the UI thread, interfaces should be created to concrete classes responsible for operating in the View space.  This configuration allows these objects to be mocked out during unit testing.  This will be the subject of a future blog post.

I hope to put some example code up soon as well. 

Monday, January 3, 2011

Using Nested classes to encapsulate View Models in User Controls

I have been working on developing some more complex user controls that will serve as the base of a lot of applications we develop. These controls will exist in a separate library of common controls. Although I am not using Prism, this is following in line with the composite concept the present, having an application being composed of many different reusable user controls.

I like the MVVM pattern and have made extensive use of View Models within the control.  However, I do not want to really show all those "internal" view models to the users of the control.  Unfortunately, traditional hiding techniques, such as internal classes are not allowed by WPF.  To solve this problem, I employed a few tricks.

1.  Declare the constructor as internal on the public class.  This prevents the applications from initializing their own instances of View Model and protects against others using your classes.  This means you can more freely upgrade and modify your class as the internal needs of your control change without worrying about breaking someone else's code.

2.  "Hide", or at least partially hide all the "guts" of the control by putting them inside the user control class as embedded classes. When doing this, I like to have each View Model in its own file.  I learned long ago that one class per file is a good rule to follow.  To do this, I use the handy partial class feature.

Now, these two methods don't always work.  If you directly reference the View Model from the XAML, you have to make the class public. You can see the requirements for classes used within XAML here.   However, in my case many of my view models are only instantiated in code and returned via properties (like lists of items, etc).  In fact, only one of my View Models needed to be made public.

Here is an example of a control's View Model. It can't be instantiated outside the control's assembly (aka, the app using it) and the class is at least somewhat hidden from view. For example, Intellisense won't show all the class names unless someone actually types out "MyUserControl.".


public partial class MyUserControl
{
  public class MyViewModel
  {
     internal MyViewModel() { }
  }
}

Friday, December 10, 2010

WPF Tips and Tricks - DockPanel Doesn't Behave Right

Consider the following:

  1.   <DockPanel>
  2.       <ListBox Width="2000">
  3.         <!-- Lots of items -->
  4.       </ListBox>
  5.       <StackPanel DockPanel.Dock="Bottom" Height="35" Orientation="Horizontal" VerticalAlignment="Bottom" HorizontalAlignment="Right">
  6.           <Button VerticalAlignment="Center" HorizontalAlignment="Right">OK</Button>
  7.           <Button VerticalAlignment="Center" HorizontalAlignment="Right">Cancel</Button>
  8.       </StackPanel>    
  9.     </DockPanel>

You would think that the buttons at the bottom will always be there. But if that ListBox gets too many items, the DockPanel will happily cover up the StackPanel. That doesn't seem right since the StackPanel has an explicit height and it is explicitly docked to the bottom. The reason for this is the DockPanel renders items in the order they are entered. In this case, the ListBox gets rendered first and fills the space. The fix is simple, although does not reflect the real layout of the page. That is to flip the StackPanel and ListBox.

  1.   <DockPanel>
  2.       <StackPanel DockPanel.Dock="Bottom" Height="35" Orientation="Horizontal" VerticalAlignment="Bottom" HorizontalAlignment="Right">
  3.           <Button VerticalAlignment="Center" HorizontalAlignment="Right">OK</Button>
  4.           <Button VerticalAlignment="Center" HorizontalAlignment="Right">Cancel</Button>
  5.       </StackPanel>
  6.       <ListBox Width="2000">
  7.         <!-- Lots of items -->
  8.       </ListBox>
  9.     </DockPanel>

Thursday, September 2, 2010

Making Test SQL Data

Today I had the need to make a lot of dummy rows to test performance of a system. Often the case is when you design a query it performs great with a few thousand rows, but over the years as your data grows, things slow down. So, today I wanted to test my schema with a larger dataset. The first question was how to do that. SQL performs much better with sets, not iterations. The thought of running an INSERT statement millions of times did not appeal to me. Here's some tricks to make a lot of data "relatively" fast.  I say relatively because this will still take many minutes, but not many hours.  Remember, SQL is SET based!  Use sets whenever possible!


-- Don't want 25M "1 Row inserted" messages!
SET nocount ON

-- Some timing stuff, see how fast it is.
DECLARE @a DATETIME,
        @b DATETIME

SET @a = current_timestamp

-- Create a temporary table to create a multiplier factor.
DECLARE @myTable TABLE (id INT)

-- Add 5000 rows to our dummy table.
DECLARE @counter INT

SET @counter = 0
WHILE @counter < 5000
  BEGIN
      SET @counter = @counter + 1
      INSERT INTO @myTable VALUES (@counter)
  END

-- This is the big multiplier.. a cartesian product is 5000*5000=25M rows!  We 
-- don't even need to select from the tables, but if we want we could use the
-- numbers for something..
INSERT INTO uw_containers (type_id)
SELECT 1 FROM   @myTable a, @myTable b

-- Now create a history event for each of the new containers.
INSERT INTO uw_container_history
            (containerid,label,effectivestart,effectiveend,eventstartid)
SELECT  

    id,'C' + CAST(id AS varchar(50)),Getdate(),'12/31/9999',139059
FROM 

    uw_containers


SET @b = current_timestamp
SELECT Datediff(ms, @a, @b)

Thursday, August 19, 2010

Known Values and NULL - Communication channels and when to cache

"There are known knowns. These are things we know that we know. There are known unknowns. That is to say, there are things that we now know we don’t know. But there are also unknown unknowns. These are things we do not know we don’t know."  - United States Secretary of Defense Donald Rumsfeld

Rumsfeld really summed up the problem with his statement.  One of the most commonly used constructs in programming in the concept of NULL, to indicate an unknown or unset value.  This is all fine, until you start to design a communication channel and start caching information on the client.  


The problem really comes down to half filled data structures being returned to the client or sent to the server.  This occurs usually because of a trade off between completeness of data and performance or queries.  Now, we can argue whether or not this is the best approach, but for now let's just assume this is the case.  A more valid place for this is an "Update" message to the server, where we want to use a common UpdateRequest structure, but only want to update some portions of the data.


The problem is, when the client sees a NULL in a field, does it mean the value was actually NULL in the database, and therefor a "known unknown" or does it mean the value was never set and therefore the client should request that value from the server if needed?  The same problem can go for updating data:

Say we have the simple UpdateRequest as:
int id;
string name;
string description;


If we send an update request with {id=1, name="Kevin", Description=null}, does that mean that the description is unknown, and should be written as such to the database, or does it mean we don't want to update the description and keep whatever the previous description was?


In order to solve this problem, I introduced a simple wrapper class called KnownValue:


  [DebuggerDisplay("Known: {Value}")]
    public class KnownValue <T> 
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="KnownValue&lt;T&gt;"/> class.
        /// </summary>
        /// <param name="value">The value.</param>
        public KnownValue(T value)
        {
            Value = value;
        }

        /// <summary>
        /// Gets or sets the value.
        /// </summary>
        /// <value>The value.</value>
        [DataMember(IsRequired=true)]
        public T Value
        {
            get; set; 
        }
    }

The beauty of this simple class is we can now introduce three-state logic:

Description = null: The value is unknown, so don't change it on the server or if the user requests it, we don't have it cached so go get it.
Description = KnownValue<string>(null): The value is known, and should be set to NULL. If the user requests the value, don't go to the server since we already know it is NULL.
Description = KnownValue<string>("My Description"): The value is known, and should be set to "My Description".

Friday, July 2, 2010

What's at a location at a given time?

Today I was challenged with a problem that seemed deceptively simple and the answer is. But coming up with it took a while. The question was for a location log, what were all the objects at a given location at a given time?

The table is simple:
LocationID int
ObjectID int
Date datetime

So, {1,1,6/30/10 10am} would indicate that object 1 was at location 1 at 10am on 6/30/10.

Given a set of log entries:

{1,1,6/30/10 10am}
{2,1,6/30/10 12pm}
{4,1,6/30/10 6pm}
{2,1,6/30/10 8pm}
{1,2,6/30/10 11am}
{3,2,6/30/10 1pm}
{4,2,6/30/10 5pm}

We can see from this list that at 11am for location 1, both object 1 & 2 are there. But at 12:01pm, only object 2 is left. So, how do we get this list for any given time?

Here you go..

declare @myDate datetime
set @myDate='2010-06-30 11:00'
declare @MyLocation int
set @MyLocation =2

select * from
LocationLog t1
left join LocationLog t2 on t1.ObjectID=t2.ObjectID and t2.Date > t1.Date and t2.Date <= @myDate
WHERE
t1.Date<=@MyDate
and t1.LocationID=@MyLocation
and t2.ObjectID is null

Wednesday, October 28, 2009

MySQL vs MS SQL Server

I know MySQL's query engine isn't as powerful as MSSQL, but there are things in the MySQL syntax that just run circles around MSSQL. For example, MySQL has a great option to the INSERT command called IGNORE.

It is very common to construct a many to many table using just two columns for the relationship and making those two columns the primary key. This implies each row is unique. A common problem is how to update this relationship.

Say you have a web site where a user can choose from a list of options. When the user wants to update their settings, they check or uncheck some new settings. On the backend, we need to update the relationship.

A common approach is to delete all the old relationships, then reinsert them. This to me is an expensive and brute force approach. A less "heavy handed" approach would be to select all the current mappings, then figure out what is new and what should be removed. However, we've now made a rather complex difference engine on the client and it's not concurrent, unless we lock the database while doing the work on the client.

So, welcome MySQL's INSERT IGNORE command.

Here's how it works:

INSERT IGNORE INTO table (field1,field2) VALUES (val1, val2)

Simple, if the row already exists (a unique constraint is violated), MySQL simply skips the insert.


However, what if we want to do the same thing in MS SQL? Not nearly as easy, and a lot more resource intensive..

T-SQL:
insert into table (field1,field2)
select val1, val2
where
not exists(select 1 from table where field1=val1 and field2=val2)

Another command I love in MySQL, but absent from MSSQL is the INSERT .. ON DUPLICATE syntax.. It solves a common problem, do you need to add a new record or update an existing one.

Most people have some code that looks like this:

SELECT COUNT(*) FROM table WHERE id=val1

IF COUNT(*) = 0 THEN
INSERT ....
ELSE
UPDATE ....

Straight from the MySQL manual:

INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;

is equivalent to

UPDATE table SET c=c+1 WHERE a=1;

but if no value exists for a=1, then

INSERT table (a,b,c) VALUES (1,2,3)

Sometimes, it's those little extra I just love.

Wednesday, June 24, 2009

Service principal name when using WCF, net.tcp binding, and a domain service account

Service Principal Names (SPN) allow you to assign a name to a service and it will be used as a simple authentication mechanism. Basically, when the client connects to the service, the service sends the client it's SPN. The client also knows what SPN it expects. If they match, things are good.

In order to use the WCF NetTcpBinding with a Windows Service, it is necessary to create a SPN.

Here's the scenario:

We have a Windows Service that exposes a WCF NetTcpBinding service. The Windows service runs as a domain user account instead of LOCAL SYSTEM, NETWORK SERVICE, etc. Let's say the service is running under the account MyDomain\MyServiceAccount.

We have a client on the domain that will access the WCF service.

The problem arises when the client tries to talk to the server. Without an SPN, there is no way for the client to verify it has reached the appropriate service.

So, how do you use an SPN...

  1. We need to create an SPN and associate it with the service account. This is done using a utility called setspn.exe that is located in the Windows 2003 Support Tools.
  2. We need to create the SPN. An SPN consists of two parts, service and host. The format is \. In our case, the host really doesn't matter because we will attach the SPN to a username, not a computer. Here's the command:
    setspn -A MyServiceClass\MyHostName MyDomain\MyServiceAccount
  3. Next, on the client, we need to specify the SPN when we create an endpoint mapping. This can be done using the app.config file or programmatically. In the app.config file, in the section, add

    <identity>
       <serviceprincipalname value="MyServiceClass\MyHostName"/>
    </identity>

    Or we create the endpoint with the SPN..

    EndpointIdentity id = EndpointIdentity.CreateSpnIdentity("MyServiceClass\MyHostName");
    EndpointAddress addr = new EndpointAddress(new Uri(URI), id);




That's it. Now your client will be able to verify the service it is connecting to.

Wednesday, November 19, 2008

Visual Studio 2008's bug in it's XAML editor bugged me all morning

All I got to say is "AAAAHHH!"...

I spent the morning trying to figure out why Intellisense fails to work in my XAML files. Life was great, then one day it stopped working. I couldn't figure out why. Googling for solutions came up with nothing.

So, I decided to create a blank XAML file in my project. Guess what? Intellisense worked there. So, I went through starting to recreate my "bad" XAML file. As soon as I added a namespace reference to my own assembly, it broke. In the code snippet below, you'll see the offending line. It's the xmlns:local. Remove that line, Intellisense works, add it and Intellisense breaks. Great!



<Window x:Class="MyProject.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MyProject">



Now that I knew it was related to that line, a much more targeted google brought up this one Microsoft forum where the issue was discussed, recognized as a bug by MS, and supposed will be fixed in the next Service Pack. Problem was, at the time of writing, the next SP was to be SP1. I've got SP1, but the bug still persists.

So, in light of the stupid bug, this is the workaround I'm using. It's not perfect, but if you use a reference to your local assembly only for a model-view, you can push your model-view off into a resource file then link via a shared dictionary to your actual UI.

SharedResources.xaml:



<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:MyProject"
>
<!-- Your local resources go here.. oh, and Intellisense is broken when editing this file -->
</ResourceDictionary>


And now the actual window...



<Window x:Class="MyProjects.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="SharedResources.xaml"/>
<ResourceDictionary>
<!-- Any local resources -->
</ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>

<!-- Your contents -->
</Window>


Sometimes you make coding decisions just because you like your IDE too much to give up it's tools...

Monday, November 3, 2008

WPF & Multithread - Part 2 and creating multiple windows on different messaging threads

In my previous post I talked about getting input from a user while running on a business thread. You maybe wondering what happens if I choose to just always create a new STA thread rather than check to see if the calling thread is already on an STA thread. After all, that's less code.

Well, that's what I originally did, until I ran into a problem. You see, it all comes down to calling the Thread.Join call. This call blocks the calling thread. So, if the calling thread is the UI thread, you've just blocked it! Oops.. there goes the message pumping for that thread. So, say you have a timer on your main window. Well, suddenly it comes to a stop. In my case, I had a custom NativeWindow class that listens for keystrokes across the application to detect incoming barcode values from a barcode scanner. For my application it is essential the WndProc override of my NativeWindow always gets called. This is because I use the Raw Input API to filter keyboard input searching for barcode values. However, the Raw Input API stops all WM_KEYxx calls from being generated. The only way any of my WPF windows will get a message (and hence keystrokes) is if I manually send the WM_KEYxx messages. So, as you can see, it is essential to the application that the NativeWindow.WndProc method is always called.

But as soon as I pop up my new WPF window to ask the user a question, they can no longer type. That's because the new window is running on the newly created STA thread and the original UI thread (and the one running the NativeWindow.WndProc) is now blocked! Users don't need to type, do they?

So, in my original post I showed a simple way to deal with this. Just check the calling thread and see if it is a UI thread. If so, show the Dialog box on that thread and you're good to go.

However, another option that also works is to create my NativeWindow on a different thread. The key is to call at the end System.Windows.Forms.Application.Run(). This method basically runs the old fashion message loop.. remember that one?



while(GetMessage(&Msg, NULL, 0, 0) > 0)
{
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}


Of course, the reason I choose not to do this method was it was just too much work! First of all, now I need to worry about multiple message loops, and more cross thread issues. Secondly, an Application.Current.Shutdown() call from my WPF window doesn't shutdown the application. That's because you need to somehow communicate to the newly created window to shutdown it's thread. So, more work...

Anyway, here's a simple example of creating a new window on a different thread, so the message loop is on a different thread. I am not saying this is the way to do things, but I wrote about it because it was a good find and maybe used later..




public void Startup ()
{
Thread NewThread = new Thread(new ThreadStart(CreateWindow));
NewThread.SetApartmentState(ApartmentState.STA);
NewThread.Start();
}

private void CreateWindow()
{
// Create a new native window that will be hidden.
CreateParams cp = new CreateParams();
cp.Caption = "MyWindow";
cp.ClassName = null;
cp.Style = 0x08000000 | 0x20000000;
cp.Height = 500;
cp.Width = 500;

this.CreateHandle(cp);
CreateRegistration();

// Here is the key! Application.Run encapsulates the old standard message loop.
Application.Run();
}

Multithreading and WPF Windows

I recently had an interesting problem come up with UI threads in .NET applications and how input is processed. Here's the basic rundown...

A user initiates an event in the UI on Thread 1

The UI makes a call to some business layer to process the request. Note, this MAY or MAY NOT continue to execute on the UI thread.

The business logic needs more information before it can proceed. Nicely separated, the business thread raises an event called GetAdditionalInfo. Now, the application can either provide the information directly back to to the business logic or it may need to ask the user.

Now, here's where things get "interesting". If the business logic is running on a different thread, you've got a problem. You can't simply create a new WPF window to ask the user for the information. If you try, you'll get the following error message:

System.InvalidOperationException: The calling thread must be STA, because many UI components require this.

Well, what are you to do? A few options come up.

One option is to put a message onto the dispatch thread for the current window. While this method will definitely get your message across, you have a bit of a problem. That is, the business logic thread will continue to execute Problem is, you need to hold up the business logic thread until the user has responded to the question.

The trick lies in spawning off a new thread, creating the WPF window in that new thread, and block the business logic thread until the UI finishes. Of course, if the business logic thread is already a UI thread, this isn't needed and you can just do a ShowDialog directly. Code below...



private static void ShowWPFDialog(object arg)
{
GetAdditionalInformationWPFWindow myWindow = new GetAdditionalInformationWPFWindow();

// ShowDialog will block the calling thread..
myWindow.ShowDialog();

// Presumably at this point you have the data required from the UI... So you could set it in the arguments..
((BusinessRequestEventArgs)args).MyResult = myWindow.BusinessLogicResult;
}

private static void GetAdditionalInformation(object sender, BusinessRequestEventArgs e)
{
// If the current thread is already an STA thread we can just run on this thread.
if (Thread.CurrentThread.ApartmentState == ApartmentState.STA)
RetrieveSecondaryLogon(arg);
else
{
Thread _UIThread;
_UIThread = new Thread(new ParameterizedThreadStart(RetrieveSecondaryLogon));
_UIThread.SetApartmentState(ApartmentState.STA);
_UIThread.Start(arg);
// Block the caller until the UI thread ends..
_UIThread.Join();
}
}

Thursday, October 30, 2008

RoutedEvents to Commands

Microsoft started down a great road by introducing Commanding with WPF. However, in my opinion they didn't go far enough. While it's great that some UI elements like Buttons, Menus, etc. support sending a Command when activated, there are many other places in UI design that an action taken implies a command. The most common example I can think of is when the SelectedItem value changes in a Listbox or Combobox. Perhaps you want to either display details about a selected listbox item. Maybe you want to take action if the user double-clicks the list item. Maybe you want to immediately do some action, like a user chooses a value from a ComboBox and your ready to move forward. (I won't go into whether this is really good UI design).

Regardless, my point is, there are lots of things exposed via RoutedEvents that have no command interface, but it sure would be nice to have a command instead of a routed command.

One great thing about WPF is the extensibility. Using the Attached Behavior pattern (by John Gossman) we can create a class that will allow us to add command patterns onto UIElement for any routed command. The code is at the end of this post.

Some interesting things I learned while making this class and then trying to use it. One, XAML is good, but it's got a long way to go to catch up to the more mature .NET languages, like C#. A difficulty in XAML is the lack of generic support, so you need to do little things like my creation of the RoutedEventCommandBindingCollection class, even though it is an empty class, it creates a concrete class of the generic ObservableCollection<>.

The fact that attached property instances are not separately initialized also was a problem. For example, it would be great to initialize each attached property to be an empty list. However, we can't do this. So instead, we need to do the initialization in the XAML, as seen in the code example below. If you exclude the RoutedEventCommandBindingCollection wrapping, you get a NULL exception because the attached property EventCommandBinding (which is a list) hasn't been initialized to an empty list.


Using the class in XAML:



<UWPath:RoutedEventCommandProxy.EventCommandBinding>
<UWPath:RoutedEventCommandBindingCollection>
<UWPath:RoutedEventCommandBinding Event="UIElement.MouseUp" Command="{StaticResource MouseWasClicked}"/>
</UWPath:RoutedEventCommandBindingCollection>
</UWPath:RoutedEventCommandProxy.EventCommandBinding>



The source code in C#:



public class RoutedEventCommandProxy
{
// Fun, this will keep track of all the bindings!
private static Dictionary<UIElement, RoutedEventCommandBindingCollection> handlerTable =
new Dictionary<UIElement, RoutedEventCommandBindingCollection>();

public static readonly DependencyProperty EventCommandBindingProperty =
DependencyProperty.RegisterAttached("EventCommandBinding",
typeof(RoutedEventCommandBindingCollection),
typeof(RoutedEventCommandProxy),
new FrameworkPropertyMetadata(null, new PropertyChangedCallback(PropertyChanged)));

public static void SetEventCommandBinding(UIElement element, RoutedEventCommandBindingCollection value)
{
element.SetValue(EventCommandBindingProperty, value);
}
public static RoutedEventCommandBindingCollection GetEventCommandBinding(UIElement element)
{
return (RoutedEventCommandBindingCollection)element.GetValue(EventCommandBindingProperty);
}

private static void PropertyChanged (DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
UIElement element = sender as UIElement;

// Remove any old stuff..
if (handlerTable.ContainsKey(element))
handlerTable.Remove(element);

RoutedEventCommandBindingCollection OldMappings = (RoutedEventCommandBindingCollection)args.OldValue;
if (OldMappings != null)
{
foreach (RoutedEventCommandBinding mapping in OldMappings)
{
if (mapping.Event != null)
element.RemoveHandler(mapping.Event,new RoutedEventHandler(Handler));
}
}

// Add the new stuff
RoutedEventCommandBindingCollection NewMappings = (RoutedEventCommandBindingCollection)args.NewValue;
if (NewMappings != null)
{
handlerTable.Add(element, NewMappings);
foreach (RoutedEventCommandBinding mapping in NewMappings)
{
if (mapping.Event != null && mapping.Command != null)
element.AddHandler(mapping.Event, new RoutedEventHandler(Handler));
}
}

}

private static void Handler (object sender, RoutedEventArgs e)
{
UIElement element = sender as UIElement;
if (handlerTable.ContainsKey(element))
{
RoutedEventCommandBindingCollection mappings = handlerTable[element];
foreach (RoutedEventCommandBinding mapping in mappings)
{
if (e.RoutedEvent == mapping.Event)
{
mapping.Command.Execute(e);
}
}
}
}
}

public class RoutedEventCommandBindingCollection : ObservableCollection<RoutedEventCommandBinding>
{
}

public class RoutedEventCommandBinding
{
public RoutedEvent Event { get; set; }
public ICommand Command { get; set; }
}

WPF and Focus

So, Control focus in WPF just frustrates me sometimes. It should be simple. Control.Focus(). But things are never as they seem. Take this code for example. It simply hides a panel asking for an ID and the presents a panel asking for a Pin. With the myPinPad variable is an instance of a custom control (inherited from UserControl) with nice buttons for a pin pad and a text field to type optionally type in a pin.



private void ShowPinPad ()
{
IDBadgePanel.Visibility = Visibility.Collapsed;
PinPanel.Visibility = Visibility.Visible;
myPinPad.Focus();
}


The PinPad custom control contains an override of the OnGotFocus method as shown below. The PWD variable is a PasswordBox control that will display the pin. Now, when the PinPad control gets focus, we want the PasswordBox to get focus so a person can just start typing.



protected override void OnGotFocus(RoutedEventArgs e)
{
base.OnGotFocus(e);
PWD.Focus();
}


Anyway, this doesn't work the first time around! Why not? Well, after some investigation it is revealed that while PWD.IsInitialized is true, PWD.IsVisible is false. Of course, call ShowPinPad again later on and it works. This time IsVisible is set to true.

So, what to do? Well, I think the reason it isn't visible is that despite the status of being Initialized, it really isn't yet. Since we just made the panel containing the control visible, perhaps the render engine hasn't had time to make the children (and hence the PWD control) visible yet.

One trick is to wait a bit before sending the focus. And by wait, I mean let all the other initialization stuff finish first on the thread. This could be done with a DispatchTimer, but an even easier trick is the following:



protected override void OnGotFocus(RoutedEventArgs e)
{
base.OnGotFocus(e);
this.Dispatcher.BeginInvoke((Action)delegate { PWD.Focus(); },
System.Windows.Threading.DispatcherPriority.Background);
}


With this trick, we create an anonymous delegate and schedule it for execution at the lowest possible priority. So, hopefully everything else will get initialized first. I've tried this with my app and it works.

Thursday, October 23, 2008

Fun with SQL transactions, ADO.NETand how ExecuteScalar can bite you.

Today I wanted to create a section of code that grouped a bunch of stored procedure (SP) calls into one transaction. If any of these stored procedures failed, I want to rollback the entire transaction. It basically went something like this:

Call SP:CreateCase
Call SP:LinkIdentifierToCase
Call SP:CreatePatient
Call SP:LinkPatientToCase

Ok, first thing I tried was the .NET 2.0 TransactionScope. I won't go into details here, there are plenty of sites online how to use it. Anyway, after some digging I found that TransactionScope only works with MSDTC service enabled on the SQL server when you are running SQL 2000! Ahhh.. That's a bit heavy since it's not distributed by any means.

So, I went back to look at the ASP.NET 1.x stuff, which is the SqlConnection.BeginTransaction method. OK, looks good on the surface.. but what's it really doing? Well, I took a look at SQL profiler to find out.. And the answer is... drum roll please... Simple sending T-SQL commands BEGIN TRANSACTION, COMMIT, and ROLLBACK.

Well, that's not too bad, at least I understand it. However, bigger issues came up when your SPs have transactions in them. See, while SQL Server claims to support nested transactions, it really doesn't. For example, what would you expect this to do:



begin transaction trans1
select @@trancount
begin transaction trans2
select @@trancount
rollback transaction trans2
select @@trancount
commit transaction trans1


I would expect it to roll back the entire transaction because trans2 failed. However, commit transaction trans1 shouldn't throw an error. Guess what, as soon as rollback is executed, all nested layers are rolled back. Instead, it should nicely fall out. OK, trans2 failed, one nested layer to go. When we see another commit or rollback, we know to rollback the entire thing. Anyway, this makes things "interesting"...

What ends up happening just isn't what you expect. So, you just need to be prepared for stuff. Luckily, it seems generally ADO.NET can handle this for you. I made a simple SP that either happily completes with a COMMIT or ends with a ROLLBACK. It is:



CREATE Procedure TestProc (@DoError int)
AS
BEGIN TRAN
insert into TestTable (Name) VALUES ('Test')
if (@DoError=0)
COMMIT
else
ROLLBACK
GO


Then I created my test code:



SqlConnection conn = new SqlConnection(ConnectionString);
conn.Open();
SqlTransaction tran = conn.BeginTransaction();
try
{
SqlCommand cmd = new SqlCommand("exec TestProc 0", conn);
cmd.Transaction = tran;
cmd.ExecuteNonQuery();

cmd = new SqlCommand("exec TestProc 1", conn);
cmd.Transaction = tran;
cmd.ExecuteNonQuery();

tran.Commit();
}
catch (Exception)
{
tran.Rollback();
}
conn.Close();


Here's the output of SQL profiler:



As I would expect, while the first call the SP succeeded, the second one failed, and all the "test" table should be empty. In fact, it was. Luckily for us, ADO.NET executes a IF @@TRANCOUNT > 0 after executing each statement. This allows it to know when to throw an exception if a ROLLBACK occurs in the T-SQL, which I'm catching in the try/catch block. However, I still call tran.RollBack just to ensure the exception wasn't caused by something else, even maybe an error message (but not rollback!) from the SP itself. And look, ADO.NET is smart enough to check if the @@TRANCOUNT is great than zero before calling ROLLBACK. I can't say it's that smart when you call trans.Commit, but you should never be calling Commit if you get an exception.

So, I thought my work was done, until I found another curious issue. It seems that ExecuteScalar does not throw an exception even if a rollback occurred within the SP or an error was generated by the SP. This obviously causes a problem in my book! There is a nice forum discussion about this on MSDN.

So, conclusion. Don't blindly use BeginTransaction, especially if you have stored procedures with transactions within them. Secondly, if you want to capture any sort of error from the SQL server, don't use ExecuteScalar.

Wednesday, October 22, 2008

Storing Information Per Thread

I recently ran across a situation where I wanted to store information per Thread. After doing some research I ran across the ThreadStaticAttribute class. You apply this attribute to a static field and the value for the variable is unique for each thread. Also note that a default value is useless since it will only be initialized once and the following threads will just have a null value. So, it is best to apply this attribute to a private field and have a public property that can initialize if needed.



[ThreadStatic]
private static string myThreadValue;

public static string MyThreadValue
{
get
{
if (myThreadValue == null)
myThreadValue = "New value";
return myThreadValue;
}
}


There are other methods to store data per thread. One is SetData / GetData methods on the class System.Runtime.Remoting.Messaging.CallContext. This method allows you to specify a named variable and a value. The reason I don't like this approach is that it doesn't allow you to strongly type the data since the SetData / GetDat use a Object parameter.

Finally, the Thread.AllocateDataSlot method allows you to create a "storage slot" and use the Thread.SetData and Thread.GetData to you to store information. The reason I don't like this approach is the same as mentioned above about the lack of strong typing. Secondly, this method is is slower than the ThreadStaticAttribute.