Saturday, February 09, 2008
update 2: I also posted this on the forums and the team finally found what was causing this. They explain:

There have been several reports where intellisense has completely stopped working for all projects after installing a version of the Windows SDK or MSDN. We have been able to track down the source of this problem. This seems to only affect installs of the SDK/MSDN post the installation of Visual Studio. One registry value has been incorrectly reset after these installs causing this failure. This issue has been handed off to setup team for a future fix.

In the meantime, if you encounter this issue, it can be fixed using regedit. First, determine if you are seeing this same issue by opening regedit and looking at the key:

HKEY_CLASSES_ROOT\CLSID\{73B7DC00-F498-4ABD-AB79-D07AFD52F395}\InProcServer32

If (Default) is empty you are hitting this issue. To correct the problem, change the value of (Default) to point to the location of TextMgrP.dll on your system (C:\Program Files\Common Files\Microsoft Shared\MSEnv\TextMgrP.dll in my case with a C: OS drive and accepting all the defaults). Restart Visual Studio and intellisense should be working again. Thanks to everyone who submitted reports of this issue and gave us the additional details needed to track it down quickly.

Update: If you are running a 64-bit version of Windows, you will need to make sure you are running the correct regedit version (%systemroot%\syswow64\regedit - see http://support.microsoft.com/kb/305097) and you will need to locate the correct path to TextMgrP.dll (such as C:\Program Files (x86)\Common Files\Microsoft Shared\MSEnv\TextMgrP.dll)

 

Update: a repair of visual studio eventually fixed this. Lesson learned: a repair does not damage already installed hotfixes and addins, so you do not have to fear losing anything.

I lost my xaml intellisense and I really miss it. I installed SDK 6.1, but I do not know if that was the cause. I was using Resharper, so I didn't notice. However, when I uninstalled resharper, intellisense did not appear again! It could have been the sdk. It could have been resharper. Or something else all together. I just don't know.

Lot's of googling did not really help (2008 is different than 2005), but did point to the importance of two files in your xml/schemas folder:

- XamlPresentation2006.xsd
- xaml2006.xsd

However, VS 2008 does not work with xsd anymore to supply intellisense. I was under the impression that a Xaml-parser service was build. I do not have those files and on another computer (where intellisense works fine), I did not find them either.

I copied them from a vs2005 install, and opened a xaml file in the xml editor. No schemas were defined (nor are they on the healthy computer), but when I pointed to the just copied files, intellisense does work partially again. It does not see usercontrols and stuff. This is not the way it is supposed to work in 2008!

Funny thing though: I now have this intellisense in the xmleditor, but not in sourcecode editor or the designer. In the healthy install, it's the other way around.

Let me know if you have a solution!

Saturday, February 09, 2008 11:06:22 PM (Romance Standard Time, UTC+01:00)  #    Comments [0]  |  Trackback

Dax Pandhi, of Reuxables is offering a lite version of their commercial theme: paper. You only get the compiled dll, but still, it's a bargain ;-)

I have not used any commercial themes yet, and as I am not working for a client at this point, I probably won't at this moment ;-) I also do not know yet whether I like the theme. I am going to use it and just see!

Are there other commercial theme packs around? I would like a pack that makes my applications look like this application ;-)

Saturday, February 09, 2008 9:05:07 PM (Romance Standard Time, UTC+01:00)  #    Comments [2]  |  Trackback

If you are working with clients that do not see the use of automated testing (be it in unit tests of code blocks, or specific UI testing), you are in for a hard time. Maybe you should walk away, but let's face it: you will probably give in and try to do your best.
I have even had heated discussions with developers that do not see the use of it, certainly when there are monkey-testers to do it.

Testing the userinterface is incredibly hard to do. When you're testers are brave, they might use a testtool (robot) that will simulate clicks and read out information. However, these scripts have to be updated when the software changes and that is costly.

WPF has great support for UI Automation, which allows other programs to interact with your application's UI from the outside. It does this by naming the elements of your UI and offers 'strategies' to interact with them (Press this button).
It's not an easy framework, but workable.

Project White seems to be an abstract layer on top of the UI Automation stack, released to the public domain by ThoughtWorks today. It's aimed at simplifying your scripts and presenting a uniform API for both Winform and WPF technologies.

I'm looking forward to discovering it's api. This looks nice:

 

Application application = Application.Launch("foo.exe");
   Window window = application.GetWindow("bar", InitializeOption.NoCache);
Button button = window.Get<Button>("save");
button.Click();

Do you use UI automation to test your application?

Saturday, February 09, 2008 8:54:33 PM (Romance Standard Time, UTC+01:00)  #    Comments [0]  |  Trackback

Maybe old new, but Microsoft put up new site here which looks like a very nice collection of all the tools that you can get for visual studio.

Resource Refactoring Tool

Saturday, February 09, 2008 6:05:29 PM (Romance Standard Time, UTC+01:00)  #    Comments [0]  |  Trackback
 Monday, February 04, 2008

I'm a strange man: I seem to be equally interested in EntityFramework and in WPF. They are such different beasts, and still I take great pleasure in using them both! That's possibly because I view them as enablers of the kind of projects I like to do. Weird.

Anywho, it's been a long time since I blogged about WPF. And even longer since I blogged about unittesting WPF. The simple trick in this post is probably widely used already in the community: I haven't paid any attention ;-)

In this post, I explained how to setup a tracelistener to listen for binding errors. In the months that followed, this proved to be less than convenient! In WPF views, even when everything is setup great, there might be binding errors that you wish to accept. For instance: a view binds to an instance of type Foo, and is later subsituted by an instance of type Bar. Bar has the same properties as Foo, except 1. The binding engine just clears the bound label, and you are fine with it (yes, sure.. it smells a bit, but you get the example).
Using the tracelistener, you have less control over what the process.

It is much better to have total control over the binding objects in a view. With some exceedingly simple methods, you can get to them to query their status:

First, let's start with an enumeration over all the visuals in your view:

public
IEnumerable<Visual> EnumVisual(Visual visual)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(visual); i++)
 {
   Visual childVisual = (Visual) VisualTreeHelper.GetChild(visual, i);
   yield return childVisual;
 }
}

Then, we use some cleverness by dr. WPF that enumerates all the bindings found on a visual:

private IEnumerable<BindingExpression> EnumerateBindings(DependencyObject target)
{
   if(target is ContentControl && ((ContentControl)target).Content is DependencyObject)
   {
      EnumerateBindings( (DependencyObject) ((ContentControl)target).Content);
   }

LocalValueEnumerator lve = target.GetLocalValueEnumerator();

while (lve.MoveNext())
   {
      LocalValueEntry entry = lve.Current;

      if (BindingOperations.IsDataBound(target, entry.Property))
      {
         Binding binding = (entry.Value as BindingExpression).ParentBinding;

         yield return entry.Value as BindingExpression;
      }
   }
}

It uses the GetLocalValueEnumerator, which is a largely unknown method that gets all the properties on a dependencyobject.
I first check to see if the target is a content control, if it is, I go for its content as well.

Now, let's see all the bindings:

private IEnumerable<BindingExpression> GetFlattenedBindings(Visual root)
{
   foreach (Visual child in EnumVisual(root))
   {
      foreach (BindingExpression childBinding in GetFlattenedBindings(child))
      {
         yield return childBinding;
      }

      foreach (BindingExpression binding in EnumerateBindings(child))
      {
         yield return binding;
      }
   }
}

Use it in your unittest to get all the bindings that are available in the visualtree. Test specific bindings or just fail if one breaks.

foreach(BindingExpression b in GetFlattenedBindings(this))
{
   Debug.WriteLine(b.ParentBinding.Path + "=" + b.Status + " on item:" + b.DataItem.ToString() );
}

Ofcourse, it's cool to change the helper methods to extension methods.

Beware that I have not really tested the code. Copy pasting it, I see a few errors, but you get the drift.

 

Monday, February 04, 2008 11:31:58 PM (Romance Standard Time, UTC+01:00)  #    Comments [0]  |  Trackback
 Tuesday, January 29, 2008

In my previous project, we used the Composite Application Block with WPF to decouple our application. Lately I have been thinking alot about this, and found some good material on the subject that I wanted to share. But first, let me give a high-level overview of my previous approach. If you are in need to first learn about MVP, check out this dnrTV video where Jean Paul Boodhoo talks about Model View Presenter.

First off, keep in mind that CAB was not written for WPF and has to be hacked to actually be usable.
Secondly, Acropolis is dead and is being turned into guidance material in the future (think end of 2008!).

Cab exposes workitems, controllers and views. We approached the workitem as a simple configurator, which meant it just grabbed the view it wanted and showed it. That was all the responsibility a workitem got, even in wizard style screens.
The controller was our main class, implementing all the screen logic. It was responsible for retrieving and saving data through services and did not communicate directly with the view. The only communication was through the model, that we dubbed as state.
The view was bound to this state class, which could indeed be seen as a viewmodel-model (see Dan Creviers posts on this subject here). We kept the view as dumb as possible and only let it decide on view specific things, never implementing logic. This means, that the controller could decide when a particular state was prudent (for instance, 'this item is on sale'), but the view gets to decide how to present that item to the world ('wow, I'm going to turn the background to yellow').
The codebehind of the view was only a translation layer between the WPF specific calls (events defined in Xaml) and calls to the controller.

This worked great for us, although in hindsight, we did find that the whole solution was a bit over-the-top. We stuck with it though, and I think it worked out well enough. I feel we could have done without the workitems (in our approach atleast).

Since I'm on sabbatical now, I've been reflecting somewhat more on this issue and found a series of incredible posts by Jeremy Miller on how to build your own CAB. Basically, he points out that it's not that hard to implement MVP in your application by building the pieces you need yourself. The upside would be that CAB is a big monster (I completely agree here),not worthy to be used in your kick-ass application (my own interpretation ;-) ) and building the components you need yourself would buy you a much more lightweight system custom fitted to your problem domain.

While reading all of his posts, I kept feeling that most of what is needed for building a more loosely coupled system is already provided by WPF. The resources system is a possible way to inject dependencies and retrieve them. The routed events and usage of commands is also great. Then just now I've found a post which proves that I am right (and the rest of the world is wrong ;-) ) written by Josh Smith himself, a notable wpf blogger. He shows how he actually uses the resources system to inject classes and even mocks.

My main interest at this moment is to decide how to build big systems with big teams and offer tangible guidance on that subject. One of the most important aspects of that is to Keep It Simple, Stupid! I saw that my team was strugling a bit with bending their minds around the whole MVC concept. This might be attributed to lacking explanations by myself, but at the very least, it was also caused by the feeling it brought-in more complexity then it took away. Certainly the less experienced of the team did not feel the de-coupling was worth it. That is why Jeremy's stand on this felt so 'right' for me. I do think that a simpler solution then CAB would be great.

However, Joshes solution does feel a bit contrived to me. A view would indeed be able to find it's presenter(s), but how does the presenter find it's services? Will they also be defined within the resources? Could be. I find some piece of inversion of control is a more straight forward way to configure your components than 'misusing' the resources functionality. Because that's basically what is being done here.
Keep in mind though, that it is mighty handy to be able to use the injected components within the userinterface without having to do weird things. Say you have an 'edit' button and a controller that was created to manage these things. Your view will want to bind the 'enabled' property to that controller. If it was injected somehow behind the scenes, you will have to find a way to bring it into scope for the button.
We solved this, but it's not pretty!

Another solution being worked on is a WPF specific MVC platform by Rob Eisenberg: Caliburn. His solution does tackle one important issue I have with current systems, which is the communication between the view and the controller. He introduces 'ActionMessages' which can be used in xaml like so:

  1.       <Button Content="="    
  2.               Margin="3">    
  3.          <Engine:Views.AddMessageSource>    
  4.             <Engine:ActionMessage Trigger="Click"    
  5.                                   Action="Divide"    
  6.                                   Return="{Binding ElementName=result, Path=Text}">    
  7.                <Engine:Parameter Value="{Binding ElementName=leftSide, Path=Text}" />    
  8.                <Engine:Parameter Value="{Binding ElementName=rightSide, Path=Text}" />    
  9.             </Engine:ActionMessage>    
  10.          </Engine:Views.AddMessageSource>    
  11.       </Button> 

When the button is clicked, the method 'Divide' will be called on your controller, with two parameters. It's return value will be bound to the result textbox.

Talk about a great idea!! He has used this framework for great succes and I can see why. Incredibly powerful.

However, it does bring in yet another mechanism unfamiliar to your teammembers. Probably worth it though, I'm looking forward to delving into the project and using it myself.
I don't like the introduction of yet another class of things that can go wrong at runtime though: the Action method (here: Divide) should exist on your presenter. If it's not, I'm sure you will only get an error at runtime. As if the binding syntax wasn't enough ;-)

All in all, it seems there is lots of movement in the Microsoft community. People have been thinking about how to build userinterfaces for a long time, and I'm happy to see that this is also the case in the .Net world and very happy to see movement in the WPF camp on this front.

More on this soon!

Tuesday, January 29, 2008 12:19:38 AM (Romance Standard Time, UTC+01:00)  #    Comments [0]  |  Trackback
 Wednesday, January 23, 2008

David Chapell is writing tons of whitepapers lately, and his last one seems like a whitepaper I could've used on more than one occasion ;-)

Go print it and give it to your manager.

Wednesday, January 23, 2008 7:54:27 PM (Romance Standard Time, UTC+01:00)  #    Comments [0]  |  Trackback
 Saturday, January 05, 2008

Let's mix things up!
One of the strengths of the Entity Framework is it's mapping mechanism, which uses views to represent the data needed for an entity. As they call it 'some clever magic' allows the EF to fold and unfold data into views, solving the problem that most database systems (including oracle) do not solve for you: updating and inserting into a view that consists of more than 2 tables.
This allows us to map more information when needed.

In our previous examples, an employee table was defined in the database and our conceptual model used the Table Per Hierarchy mapping strategy to map developers, testers and business analists to that table. We now find that we have quite a bit of information that we need to store about the developers (such as their skill-set) that is of no use to the other types of employees. We could very well add a bunch of nullable columns to the employee table. However, one can only sustain that much filth for a certain time period ;-) Going down that path will soon get out of hand. It's better to create a new table that will hold the information we seek. (Or would you rather create a universal table???)

Thus a new table 'DevelopmentSkills' is added and a primary key DeveloperID is created, along with a few boolean columns. A foreign key relation is created between the Employee table and the new table. Nothing fancy:

EF_Combining_DBDiagram.jpg

I've learned by now that it's best to create the SSDL by hand. So I add the new table to the SSDL:

        <EntityType Name="DevelopmentSkills">
          <Key>
            <PropertyRef Name="DeveloperID" />
          </Key>
          <Property Name="DeveloperID" Type="int" Nullable="false" />
          <Property Name="WPF" Type="bit" Nullable="false" Default="false" />
          <Property Name="WCF" Type="bit" Nullable="false" Default="false" />
          <Property Name="WF" Type="bit" Nullable="false" Default="false" />
          <Property Name="EF" Type="bit" Nullable="false" Default="false" />
        </EntityType>
And the more important association:
        <Association Name="FK_DevelopmentSkills_Employee">
          <End Role="Employee" Type="EntityFrameworkTestModel1.Store.Employee" Multiplicity="1" />
          <End Role="DevelopmentSkills" Type="EntityFrameworkTestModel1.Store.DevelopmentSkills" Multiplicity="0..1" />
          <ReferentialConstraint>
            <Principal Role="Employee">
              <PropertyRef Name="EmployeeID" />
            </Principal>
            <Dependent Role="DevelopmentSkills">
              <PropertyRef Name="DeveloperID" />
            </Dependent>
          </ReferentialConstraint>
        </Association>

This association represents the foreignkey in the database and should be pretty clear by now.
Don't forget to define the sets in the entitycontainer.

Then I was able to use the designer to first create extra properties in the 'einstein' class, our junior developer ;-)
In the mapping designer, choose to map to DevelopmentSkills. Set the DeveloperID column to the PersonID property and map the remaining properties.

Pretty neat, we did not have to map another class, but instead, just extended our current class.

That means that this code is now possible:

Einstein smartNerd = new Einstein()
{
Firstname = "Albert",
Lastname = "Einstein",
Language = "C# 3.5",
WCF = true, WPF = true, WF = true, EF = true,
TeamLeader = e,
};
context.AddToPerson(smartNerd);

Elvis elvis = new Elvis()
{
Firstname = "Elvis",
Lastname = "Presley",
Language = "C# 2.0",
WPF = true, EF = true,
TeamLeader = e,
};
context.AddToPerson(elvis);

One thing to note though: the current designer makes a mistake when mapping the extra table to the Einstein class. It keeps adding new entitytypemappings in the CSDL, with the new mapping fragment (to developmentskills table) instead of combining the fragments in the already defined entitytypemapping. This leads to an error keeping the designer from showing any info. I had to hand edit a few times ;-(

 

 

Saturday, January 05, 2008 11:15:36 PM (Romance Standard Time, UTC+01:00)  #    Comments [2]  |  Trackback

We have seen two types of inheritance modeling, at this point I'm interested in modeling an association. This actually turned out to be harder then I had expected, even though the documentation on this subject is good and plentyfull ;-)

However, since you are still reading, I will create a very simple example in the employee class, such that an employee needs to report to another employee.
Remember that employee inherits from person. I was happy to see that I was indeed able to create the relationship!

I've added a new column in the employee table, named: ReportsToID and a foreignkey relation that specifies the primary key base to be Employee/EmployeeID and the foreign key base to be Employee/ReportsToID. In database lingo this simple means that ReportsToID can be filled with an exact EmployeeID and that this relationship is verified (for instance, when deleting an employee, but still having other employees which report to the deleted employee).

 Let's look at the SSDL that I created to match this new foreignkey relationship:

In the EntityContainer section:
          <AssociationSet Name="FK_Employee_Manager"
                          Association="EntityFrameworkTestModel1.Store.FK_Employee_Manager">
            <End Role="Manager" EntitySet="Employee" />
            <End Role="Members" EntitySet="Employee" />
          </AssociationSet>
And the mentioned AssociationSet:
        <Association Name="FK_Employee_Manager">
          <End Role="Manager" Type="EntityFrameworkTestModel1.Store.Employee" Multiplicity="0..1" />
          <End Role="Members" Type="EntityFrameworkTestModel1.Store.Employee" Multiplicity="*" />
          <ReferentialConstraint>
            <Principal Role="Manager">
              <PropertyRef Name="EmployeeID" />
            </Principal>
            <Dependent Role="Members">
              <PropertyRef Name="ReportsToID" />
            </Dependent>
          </ReferentialConstraint>
        </Association>

As you can see, I named the roles: Manager and Members.
The association can be interpreted as follows: An employee (a Member) can have zero or one Manager. A Manager can have zero to infinite Members.

Let's take a look at the C-side of life.
In the EntityContainerSection:
          <AssociationSet Name="TeamMemberToTeamLeader"
                          Association="EntityFrameworkTestModel1.TeamMemberToTeamLeader">
            <End Role="TeamMembers" EntitySet="Person" />
            <End Role="TeamLeader" EntitySet="Person" />
          </AssociationSet>
And the Association is defined as:
        <Association Name="TeamMemberToTeamLeader">
          <End Type="EntityFrameworkTestModel1.Employee" Role="TeamLeader" Multiplicity="0..1" />
          <End Type="EntityFrameworkTestModel1.Employee" Role="TeamMembers" Multiplicity="*" />
        </Association>

I like to use real desciptive names, but this should be easy enough to follow.

Also, I added navigationProperties to my model, so I can easily follow an association:
        <EntityType Name="Employee" BaseType="EntityFrameworkTestModel1.Person">
          <NavigationProperty Name="TeamLeader" Relationship="EntityFrameworkTestModel1.TeamMemberToTeamLeader" FromRole="TeamMembers" ToRole="TeamLeader" />
          <NavigationProperty Name="TeamMembers" Relationship="EntityFrameworkTestModel1.TeamMemberToTeamLeader" FromRole="TeamLeader" ToRole="TeamMembers" />
        </EntityType>

Remember that an association is an independent entity, it only defines a relation that can be traversed. We need Navigationproperties to actually use the association. This way it can be shared between models.

The actual mapping between the store and the conceptual model is interesting:
          <AssociationSetMapping Name="TeamMemberToTeamLeader"
                                 TypeName="EntityFrameworkTestModel1.TeamMemberToTeamLeader"
                                 StoreEntitySet="Employee" >
            <EndProperty Name="TeamMembers">
              <ScalarProperty Name="PersonID" ColumnName="EmployeeID" />
            </EndProperty>
            <EndProperty Name="TeamLeader">
              <ScalarProperty Name="PersonID" ColumnName="ReportsToID" />
            </EndProperty>
            <Condition ColumnName="ReportsToID" IsNull="false" />
          </AssociationSetMapping>

Here you can see that I am mapping the ScalarProperty PersonID instead of EmployeeID; remember we are using inheritance here.

The condition is needed to solve some errors I was having. I think it can be read as: the association only works if there is a reportsID value set.

Some test code:

Employee e = new Employee();
e.Firstname = "Ian";
e.Lastname = "Mort";
context.AddToPerson(e);

Einstein smartNerd = new Einstein();
smartNerd.Firstname = "Albert";
smartNerd.Lastname = "Einstein";
smartNerd.Language = "C# 3.5";
smartNerd.TeamLeader = e;
context.AddToPerson(smartNerd);

Elvis elvis = new Elvis();
elvis.Firstname = "Elvis";
elvis.Lastname = "Presley";
elvis.Language = "C# 2.0";
elvis.TeamLeader = e;
context.AddToPerson(elvis);

At this point I can check that e.TeamMembers has a count of 2 and both employees have a teammember property! So, everything working as expected.

Reading back this post, I can see it was actually pretty simple. However, the syntax seems to be overly complex and a small mistake leads to weird errors!

 

Saturday, January 05, 2008 3:09:31 PM (Romance Standard Time, UTC+01:00)  #    Comments [0]  |  Trackback