Pixata Custom Controls
For Lightswitch

Recent Posts

Popular tags (# posts in brackets)

Anonymous types (3) ASP.NET (5) C# (3) C# tricks and tips (2) Computers (6) Design patterns (3) DomainDataSource (3) Dynamic data (4) Entity framework (3) Entity model framework (5) F# (3) LightSwitch (12) Linq (6) Microsoft (2) MVP (2) MVVM (2) Project Euler (2) RIA services (5) Silverlight (2) SQL Server (4) Unit testing (4) Visual Studio (7) WCF (3) WPF (3)

Gratuitous link to StackExchange




The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

Actually, as I'm self-employed, I guess that means that any views I expressed here aren't my own. That's confusing!


Theme modified from one by Tom Watts
C#/F# code styling by Manoli (for posts pre-2016) and Google code prettify (for post from Jan 2016 and beyond)

My rambling thoughts on exploring the .NET framework and related technologies

I had the need today to add my own property to a WPF user control, and have that property available in the Properties panel of the Visual Studio designer, so the property could be set at design-time. The purpose of this was that my user control had a toolbar, and I had come across the need to use the control, but not show the toolbar. Simple eh? Well, not quite!

My first thought was to add a normal C# property, but this didn’t show up in the Properties panel, so was quickly rejected.

I then came across this forum thread that showed how to add a Dependency property, which seemed to be what I needed. The property showed up in the Properties panel as required, but changing it didn’t affect the display of the toolbar.

It turns out that the static Dependency property cannot change properties of the non-static controls on the user control. You seem to need to call a non-static method to do that. I ended up with rather more code than I would have expected for such a simple task, but it looked like this…

   1:  public static readonly DependencyProperty ShowToolbarProperty 
   2:        = DependencyProperty.Register("ShowToolbar", typeof(bool), typeof(Cameras),
   3:                  new FrameworkPropertyMetadata(new PropertyChangedCallback(AdjustControl)));
   5:  public bool ShowToolbar {
   6:    get {
   7:      return (bool)GetValue(ShowToolbarProperty);
   8:    }
   9:    set {
  10:      SetValue(ShowToolbarProperty, value);
  11:    }
  12:  }
  14:  private static void AdjustControl(DependencyObject source, DependencyPropertyChangedEventArgs e) {
  15:    (source as Cameras).UpdateControls((bool)e.NewValue);
  16:  }
  18:  private void UpdateControls(bool showToolbar) {
  19:    CamerasToolbar.Visibility = (showToolbar ? Visibility.Visible : Visibility.Collapsed);
  20:  }

Lines 1 to 3 declare the dependency property itself, passing the name of the actual property that we want to show up in VS (in this case ShowToolbar), the type of that property, the type of the containing control, and a rather nasty-looking callback to a method that would be called whenever the property was changed.

Lines 5-12 are the actual property we want, and are a fairly normal C# property declaration, except that they use GetValue() and SetValue() on the dependency property.

Lines 14-16 set up the static method that is called when the dependency property is changed. As explained above, as this is static, it can’t change the properties of controls, so we need to grab hold of the object that raised the event (in this case, the parent control), cast it to the correct type, call a non-static method and pass in the new property value.

Lines 18-20 simply set the Visibility property of the CamerasToolbar as required.

Quite a lot of code for such a simple task eh?

Thursday, 16 June 2011 15:59:00 (GMT Daylight Time, UTC+01:00)

I had been having some serious grief with Visual Studio’s unit testing tools. VS was complaining that some tests did not exist, and others called methods that didn’t exist. Both claims were total lies as all methods in question existed, and could be found by using the “Navigate to” feature in VS.

I had two basic errors when I tried to run tests. One was of the form "Method TestProject.SystemsRepositoryTest.CreateNewCamera does not exist" when the method did exist. I could right-click the test in the Test Results window and choose “Open test” and it would take me there. However, when trying to run the test, VS claimed it didn’t exist.

The other error I got was of the form "Test method TestProject.SystemsRepositoryTest.GetAllCameras threw exception: System.MissingMethodException: Method not found: 'System.Collections.ObjectModel.ObservableCollection`1<string> Repository.GetAllCameras()'" which was also a lie as the method being tested existed. Again, I could go to the test method, click on the name of the method being called, click f12 (Navigate to) and be taken to the code for the method.

Thanks to these problems, I have wasted loads of time debugging things that could have been fixed with unit testing. It has been frustrating to say the least!

Well, I finally found the answer…

I opened the bin/Debug folder in the test project in Windows Explorer and deleted everything in it. I then rebuilt the test project, and my tests ran fine.

For some odd reason, it looks like rebuilding the test project wasn't actually changing the DLLs in the folder, so it was using old versions, in which the methods didn't exist. Deleting them all forced VS to grab fresh copies of the referenced DLLs, and rebuild the test project's DLL.

I don’t know if this is a bug in Visual Studio 2010, but it doesn’t seem to be a feature that I would have added in by choice!

Tuesday, 31 May 2011 13:45:00 (GMT Daylight Time, UTC+01:00)

When you use Linq to create a query against an entity framework model, a common scenario is to use the .Include() extension method to make sure that any child objects are also loaded. This is mainly useful when the results of the query are to be sent over WCF, where the client is disconnected from the source of the query, and so cannot go back to the database to pick up any child objects as needed.

This works fine for simple queries, but falls apart when you want to do anything clever, like joins or shaping.

Without going into details, all you need to do is cast the query to an ObjectQuery<> and use .Include() on that. The syntax is not as obvious as it might be, so here’s an example…

ObjectQuery<Ferret> ferretQuery = ((from f in ctx.Ferrets select f) as ObjectQuery<Ferret>)

This particular example is too simple to require this trick, but I didn’t want to distract from the syntax of the cast.

I got this trick (after a long time of frustrated scratching of head at some of Microsoft’s more obscure and less helpful error messages) from this blog post.

Linq | WCF
Tuesday, 10 May 2011 15:21:00 (GMT Daylight Time, UTC+01:00)

A common scenario is to have a button on a view that is bound to a command on the viewmodel. You can also have an ABCCommandCanExecute() method on the VM that tells the view whether or not the button can be clicked.

This is all fine until you want to ask the user to confirm the action that will be performed when they click the button. For example "Are you sure you want to reformat your hard disk, dial up all the people in your contact list and reformat their hard disks, and then destroy the world?" It's kind of rude to do this without confirmation first.

The problem is that when you use WPF binding to bind the VM's command method to the button's Command property, you lose control over the execution process, and so can't inject a message box into the flow.

You could call the message box from the VM code, but this breaks the MVVM pattern, and is a really bad idea if you don't want people sneering at you in the street. It also stops you unit testing your code, which is inconvenient, but nowt by comparison to the derisive looks.

What you can do is not bind the command method, and handle it all in the button's click event. If the user confirms their desire to destroy the world, you just call the command method on the VM manually. However, doing this loses the benefits of the ABCCommandCanExecute() method. As this feature is pretty neat, we don't want to lose it if we don't have to.

Thankfully, we don't. After that long and drawn-out preamble, we are proud to present a surprisingly simple solution to the problem (drum roll please)...

This is based on the (apparently reliable) fact that a button's click event is called before the command is sent to the VM, giving us chance to get in the way.

We create a Boolean property (capital B in deference to the dear, departed George Boole, inventor of most of modern mathematical logic - the good bits anyway!) that will specify whether or not the command is to be executed. Here is some sample code for the VM...

public bool WasISure { get; set; }

Pretty complex stuff eh? Now, in the code-behind of the view, we have code like this...

private void button1_Click(object sender, RoutedEventArgs e) {
  bool wasISure = (MessageBox.Show("Are you sure?", "Confirm", MessageBoxButton.YesNo) == MessageBoxResult.Yes);
  ((MainViewModel)this.DataContext).WasISure = wasISure;

The code above assumes that your VM is called MainViewModel, and is bound to the DataContext of your view. If not, you just substitute your own code for getting hold of the VM.

When the user clicks the button, the click event is raised first, and this shows the message box. The result (ie confirmation or refusal to destroy the world) is shoved into the VM's Boolean property, where it can be used by the command method to determine whether or not it is to execute...

private void DestroyTheWorldCommand() {
  if (WasISure) {
    // destroy the world here

That's it really! A great long piece of waffle for a few lines of code (more for those modern types who insist on putting their opening braces on a new line, but still not many). Best of all, it doesn't break the fab MVVM pattern, allowing you to hold your head up high next time you go down the pub and brag about how clever you are.

Tuesday, 10 May 2011 15:09:00 (GMT Daylight Time, UTC+01:00)
# Tuesday, 22 February 2011

I was having some trouble with WPF data binding yesterday, where the binding looked correct, but the data wasn't being shown. It turned out that I had forgotten an .Include() on the original query (this data is being sent across the wire through a WCF service, so I can't use lazy loading), but along the way, I discovered a really useful blog post on how to debug WPF data binding.

Edit: After posting this entry, I noticed that one of the comments in the above blog post mentioned an older blog post that discussed the same subject. That adds a couple more ideas to the pot, so is worth reading as well.

Tuesday, 22 February 2011 14:06:13 (GMT Standard Time, UTC+00:00)
# Sunday, 20 February 2011

Just came across this rather useful post, that documents an obscure problem with what happens if you remove an element from a collection whilst enumerating it. Subtle and insidious, the problem has a simple answer.

Edit (21st July '11): Hmm, seems that post didn't last too long, as it's gone now. I wish I could remember exactly what the problem was! Serves me right for being lazy. (pause...) Ah, found it. Here is a new link that might work.

Sunday, 20 February 2011 16:21:40 (GMT Standard Time, UTC+00:00)

I came across an innocent-looking Linq problem the other day that really had me (and Yossi) baffled for some time.

It's easiest explained using the ubiquitous Northwind database (although just about any other relational database would probably do). Suppose you want a list of customers with their orders. Pretty easy eh? You do something like...

from c in context.Customers.Include("Orders") select c;

As you have included the Orders navigation property, this will include every order for the customer.

Now, what happens if you only want to include orders from this year? Sounds like a pretty simple request eh? Well, it isn't! If you were to do this in SQL, you could simply do something like...

select c.CustomerID, c.CompanyName, o.OrderDate from Customers as c
inner join Orders as o on o.CustomerID=c.CustomerID
where o.OrderDate > '1 Apr 1998'
order by CompanyName, OrderDate

Admittedly, this would return a flat dataset, with one row for each order, but you could fix this with some data shaping without too much problem.

Now the obvious thought would be to do something like this in Linq...

from c in context.Customers.Include("Orders") where c.Orders.OrderDate > new DateTime(2011, 1, 1) select c;

The problem is that this won't compile as the Orders collection doesn't have an OrderDate property. Orders is a collection of Order entities.

Well, this one had us going for ages. I posted a question up in two separate forums (fora?), and didn't get very far. Finally, a very helpful person posted an answer that worked.

What you have to do is create a query that creates an anonymous type that includes the Customer entity, and the Orders that you want. Then you create a second query that selects just the Customer entities from the first query...

using (NorthwindEntities context = new NorthwindEntities()) {
  context.ContextOptions.LazyLoadingEnabled = false;
  var customers = from c in context.Customers.Include("Orders")
                  where c.CompanyName.StartsWith("A")
                  select new { Customer = c, Orders = c.Orders.Where(o => o.OrderDate > new DateTime(1998, 1, 1)) };
  IEnumerable<Customer> customers2 = customers.AsEnumerable().Select(c => c.Customer);

What happens behind the scenes is that the Entity Framework uses relationship fixup to sort out which Order entities should be included in the query. I'm not 100% clear hat's going on here, but it works.

Two words of warning here. First, this won't work in the rather excellent LinqPad, as it doesn't support fixup. Second, you need to disable lazy loading.

If you want to read more about relationship fixup, see page 345 in Programming Entity Framework by Julia Lerman. I couldn't find a decent explanation of it on-line.

Sunday, 23 January 2011 15:15:41 (GMT Standard Time, UTC+00:00)
# Sunday, 19 December 2010

I found a neat trick the other day, and thought I would add it here in case it's of use to anyone.

I had a class, call it Ferret for the sake of argument, and I was handling a List<Ferret> collection. Although the order of the List<> was generally unimportant, I came across one instance where it would have been useful to sort them.

Now the obvious way to do this is to have the class implement IEnumerable, and add the appropriate method. However, I found that you can sort a List<> on the fly like this...

ferrets.Sort(delegate(Ferret f1, Ferret f2) { return f1.name.CompareTo(f2.name); });

This saves mucking around defining interface methods when you don't need them. Obviously, if you are going to sort the List<> regularly, then it's probably worth implementing IEnumerable, but for one-off usage like mine, this is a neat trick.

Edit (21st July '11): I found out later that you can do this even more simply with Linq...

ferrets.Sort((f1, f2) => f1.name.CompareTo(f2.name));
Sunday, 19 December 2010 21:05:28 (GMT Standard Time, UTC+00:00)
# Sunday, 19 December 2010

Although it's not actually a .NET issue, I decided to blog about it anyway!

I've been looking at design patterns quite a lot recently. I have always been a "bung it all in the code-behind" kind of programmer, which is an easy way to program, but messy. You end up with spaghetti code that's hard to maintain and impossible to test automatically (not that I ever tried mind you!).

I decided to learn some new skills, and discipline myself to programming the Big Boys' Way. I dutifully went to Amazon and spent far too much on books, and sat down to read them all. Most were fairly tough going and dull. I was beginning to think it wasn't worth the effort, until I came across Head First Design Patterns, which was a breath of fresh air. Apart from the slightly wacky style, the explanations were very good.

My only gripe with the book is that it's very Java-oriented. Given that design patterns are language-agnostic, this is totally unnecessary. Most of the time it didn't spoil the book, but in a couple of places it really annoyed me. However, it's still the best design patterns book I've read by a long way.

I hope to blog more about this subject. Watch this space (unless you've got anything better to do of course!)

Sunday, 19 December 2010 20:56:35 (GMT Standard Time, UTC+00:00)

Well, after realising (or even RIAlising if you like puns) that RIA services weren't cut out for non-Silverlight clients, I went searching for The Next Big Thing. Can't remember if I mentioned it, so I'll bore you by repeating it, but all of this investigation is for a big project I'm in that will need some sort of central data access point that can be used by all sorts of clients, most likely being WinForms, WPF (one of my colleagues is really excited about WPF), ASP.NET and Silverlight. Ideally, we want all of these to be able to use the same point of access for data, with the business logic behind that point of access.

RIA looked like the answer, but doesn't seem to play ball with anything other than Silverlight. So, I went looking at its big brother WCF. The idea was to build an end-to-end solution that had a WCF service on top of an entity framework model, and various clients consuming the service.

This posts describes my initial excitement, great disappointment and final happiness (so far) with consuming a WCF service in WinForms, ASP.NET and Silverlight.

Tuesday, 26 October 2010 15:14:16 (GMT Daylight Time, UTC+01:00)