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

Archives


Categories


Disclaimer

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!


Acknowledgments

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

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>)
                                  .Include("User");

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)

Avid readers (if there are any!) may remember my recent post in which I extolled the virtues of the DomainDataSource control, and how it enabled us to use RIA services in ASP.NET sites. Well, having bashed my head against the wall for a week or so trying to get RIA services working with ASP.NET, I have decided that the support for this is actually quite limited, and not enough to make it a viable option.

This post gives more details of my exploration, discoveries and eventual disappointment at the conclusion.

Tuesday, 12 October 2010 15:48:05 (GMT Daylight Time, UTC+01:00)

Well, having posted about my excitement over discovering ASP.NET Dynamic Data (ADD), I spent the last couple of weeks digging deep into it, and have eventually come to the conclusion that it was a great idea, but ultimately of little use. I mentioned a few misgivings in that previous post, and I've added a few more to the list. All in all, I don't see me using this technology much.

Having spent so much time on it, I had about ten blog posts in my head, explaining what I'd learnt, but I guess they stay in the recesses of my mind until they fade away into synaptic relapse.

This post explains why I'm moving on.

Sunday, 19 September 2010 15:40:07 (GMT Daylight Time, UTC+01:00)