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

# Thursday, 28 July 2011

If you’ve read my recent diatribes, you will be relived to know that this will be a very short post! It wasn’t going to be, but thankfully all the problems I was going to describe have been solved very simply.

Whilst tinkering around with my first Lightswitch application, I wanted to move some code into a separate class library, so it could be reused around the application. Naively, I added a C'# class library to the solution, moved the code over and then couldn’t add a reference to it from my Lightswitch project.

Whilst wondering what was going on, it dawned on me that Lightswitch is really just Silverlight underneath, so needs a Silverlight class library, not a normal .NET class library. I deleted the one I had just created, and added a new Silverlight C# class library. This time, I was able to add a reference and use the code from my Lightswitch application. Phew, one problem solved.

I then decided to write some unit tests for the class. That’s where I ran into the next problem. Normally, I just right-click a method, and choose “Create unit tests” from the context menu. Trouble was, there wasn’t a “Create unit tests” option there.

I spent rather longer than I should trying to work out how to do this, and failed. I even tried adding my own project and making into a test project, but that failed as I couldn’t add references to the appropriate test libraries. This is one of those occasions when you really wonder why Microsoft split Silverlight off from the rest of the .NET framework.

Anyway, the good news is that I just discovered that if you install the Silverlight Toolkit April 2010, you get new Visual Studio templates for unit testing Silverlight applications. They don’t work in quite the same way as normal unit tests, in that the tests themselves run in a Silverlight web application, but the basic principles are the same. You can even use the same code, and the same test attributes as you do in your normal tests.

Apparently, you can even test the UI with this framework, but I haven’t tried that. Needless to say, the fact that I could test my class library was enough to make me happy, and keep this blog post a lot shorter than it would have been - although it’s still a lot longer than it should have been, given the actual amount of useful information it contained! I must learn to be more concise.

Thursday, 28 July 2011 20:55:00 (GMT Daylight Time, UTC+01:00)

Laugh and cry with me as I describe my attempts to deploy my first Lightswitch application.

Read how it all went wrong, the started to go right, then went wrong again, then went wrong some more, then... well just read the full blog post and you'll get the picture!

Thursday, 28 July 2011 18:29:00 (GMT Daylight Time, UTC+01:00)
# Tuesday, 26 July 2011

Having mentioned a few weeks ago that I was quite impressed with my first impressions of Microsoft Visual Studio Lightswitch, I have since had a chance to play with it some more, and I am still very impressed – perhaps even more than I was. My initial fears about it being another ASP.NET Dynamic Data fiasco seem to have been unfounded.

As promised, it provides a very fast way to produce high-quality data-driven Silverlight applications (web or out-of-browser), but seems flexible enough not to restrain you by the way the Lightswitch developers want to work. Admittedly, I am still a rank newbie with it, but have already produced most of the administrative back-end for a web site I’m developing, and have done so in a mere few hours, as opposed to the few weeks it would have taken otherwise.

What’s even better (or maybe that’s only by comparison), it doesn’t have some of the stupid design “features” that plagued Dynamic Data. For example, one of my peeves with DD was this it did not attempt to stop you trying to delete a customer who had orders in the database. However, when you tried it, the delete failed due to the obvious referential constraints, ie you can’t delete the customer if there are still orders that reference that customer. Despite having jumped through quite a lot of hoops, I never found a satisfactory way to disable the delete link. I found one way, but it was so convoluted as to be pretty useless. As if that wasn’t bad enough, DD didn’t give any graceful way to handle the inevitable exception, so the end-user was presented with a rather ugly (and very unprofessional) unhandled exception. You couldn't even tell it to do a cascading delete for those occasions when you really did want to delete the customer and everything associated with it. It was a great idea, but really badly implemented.

Not so Lightswitch! By default, the delete button is always enabled, which would give an exception if you tried to delete something that you shouldn’t, but (and this is a huge “but”), if you tried it, you got a very neat validation error shown on the screen, telling you that the record couldn’t be deleted. Next bit of friendliness is that it’s really easy to disable the delete button when you want to. You simply override the code, and handle the CanExecute method, which simply returns a Boolean, indicating whether or not the current record can be deleted. As you have full access to the current entities on the screen, this is no more complex than something like this…

partial void CustomerListDeleteSelected_CanExecute(ref bool result) {
  Customer c = Customers.SelectedItem;
  result = (c.Orders == null || c.Orders.Count() == 0);
}

Pretty simple stuff eh? You are dealing with strongly-typed entities, and simply check the properties that interest you, setting the return value as appropriate. Because Lightswitch applications are built on MVVM (basically a WPF or Silverlight-specific implementation of MVP/MVC), the framework handles the enabling and disabling of the button for you. All you need to do is set the Boolean return value of CanExecute. This makes it very easy to prevent the user from trying to delete something that they shouldn't be able to.

The other nice touch in this area is that you can specify that cascading deletes are allowed for an entity, so if you do allow them to delete a customer, all the customer’s orders can be deleted at the same time. Whilst this isn’t the sort of thing you’d want to do too often, it’s nice to know that the functionality is there if you want it.

Just last night I was reading about using custom controls in Lightswitch. This allows you to extend the functionality in pretty much any way you want, simply by using normal Silverlight controls. I haven’t tried this yet, but it looks fairly simple, and means you aren’t restricted to the controls included in the Lightswitch framework. I even saw an example of a game someone had written in Lightswitch, which whilst not being the most logical use of the framework, served well to show how easy it is to extend.

Anyway, I intend to post more technical details when I’ve played some more. In the meantime, Lightswitch launches today, although as I’m writing, it’s not yet launched. This is probably because it’s only just today in Redmond, and the Microsoft people are probably all still in bed!

Tuesday, 26 July 2011 08:16:00 (GMT Daylight Time, UTC+01:00)

Always on the lookout for ways to improve my coding efficiency, I was very interested to hear about WebFormsMvp, which is a framework for writing ASP.NET web sites, based on the MVP design pattern. This post describes my initial frustrations, and eventual delight in using the framework.

In a future post, I intend to describe how to get going with WebFormsMvp, as well as how I extended it to reduce the boilerplate code even more.

Monday, 11 July 2011 16:03:00 (GMT Daylight Time, UTC+01:00)

Putting reality aside for a moment, and imagining that this blog has at least one avid reader, then he/she may remember that some time ago, I got all excited about ASP.NET Dynamic Data, which looked like a brilliant way to produce CRUD web sites (ideal for the admin back-end of most modern web sites) in almost no time at all. The same avid reader would no doubt also remember that I learnt quite quickly that it was a huge waste of time, great for management demos, but useless for the Real World, and gave up with it.

Well, another day, another new technology from Microsoft, and here we are with very similar promises about being able to produce CRUD web sites in minutes – introducing Microsoft Visual Studio LightSwitch. A moment’s pause over the name will probably reveal the pun on another Microsoft technology, SilverLight. LightSwitch is being promoted as the equivalent for SilverLight that Dynamic Data was for ASP.NET, in other words, a RAD development tool that allows you to produce CRUD sites very quickly.

So, why am I bothering? After all, my previous experience was, shall we say, less than positive! Read more to find out...

Sunday, 03 July 2011 12:59:00 (GMT Daylight Time, UTC+01:00)

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)));
   4:   
   5:  public bool ShowToolbar {
   6:    get {
   7:      return (bool)GetValue(ShowToolbarProperty);
   8:    }
   9:    set {
  10:      SetValue(ShowToolbarProperty, value);
  11:    }
  12:  }
  13:   
  14:  private static void AdjustControl(DependencyObject source, DependencyPropertyChangedEventArgs e) {
  15:    (source as Cameras).UpdateControls((bool)e.NewValue);
  16:  }
  17:   
  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>)
                                  .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)