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

Whilst working on a new version of one of the main windows in an application, I ended up dumping loads of small jobs onto one of the other developers, as he was the main one working on the XAML file for the window, and if we both tried to edit the file, we ended up with conflicts.

After dumping the umpteenth extra job on him, I was trying to work out if there is a way I could ease his burden a little. There had been quite a few new issues where the extent of my involvement had been to modify the database and update the model. After that, I had to pass it over to him, to avoid us stomping on each other when working on the same files.

So, I got to wondering if there was any way we could split the new quote window up, so multiple people could work on it at the same time. I immediately rejected using user controls for parts of the window, as this has been a road to complexity that we've trodden before, and I for one really don't want to go down the route of handling multiple view models again. It gets too messy and complex. You know me, I'm a simple sort!

So, I looked into including XAML fragments, but gave up on that as a lost cause. I'm not the only one to want it, but it looks like no-one has successfully done it yet, at least, not without some scary code.

The next idea was to store some of the XAML as control templates in a resource dictionary. You don't want to go there, believe me!

However, the brain cell woke up around this point, and I contemplated using user controls, but sharing one view model between them. Unsure of how neat this would be, I tried it out, and was pleasantly surprised by something actually very obvious. My initial thought was to declare the view model as the DataContext for each control, but that led to problems with multiple instances of the view model, so was quickly abandoned.

However, a light bulb went on at this point, and I realised I was making it too complex.

When you add a control to your XAML, it automatically inherits the DataContext of its parent. This is true of user controls as well as built-in controls. What this means is that you can have a window whose DataContext is set as usual, then have user controls for bits of the window, don't have a separate view model for them, and don't set a DataContext on them at all. They will automatically inherits the DataContext of whatever is above them, enabling you to work as usual. This allows you to use the same view model for all user controls on the window.

This means that we could hive out various sections of the XAML into separate user controls, enabling me to work on one, and him to work on another. See the attached sample project, where I did just this. As you can see, if you click the button to show the rather simple quote window, the window itself and both user controls are using the same view model (check the hashcode shown in three places), and if you open another window, it uses its own view model. Download ShareViewModel.zip.

Quite amazing, but quite obvious when you think about it. It has a huge potential for simplifying many of our XAML files, which are often far too big to be manageable anyway.

We would have to be careful about naming and placing all of these user controls, to make sure we don't end up wasting time trying to find them all. I suggested that a VrtQuoteDetailsWindow.xaml would have a VrtQuoteDetailsWindowKeyInfoUserControl.xaml, a VrtQuoteDetailsWindowSomethingElseUserControl.xaml and so on, and that these should be stored in the same folder as the VrtQuoteDetailsWindow.xaml file. Yes, this moves away from the convention of splitting windows and user controls, but my personal opinion is that this is somewhat arbitrary anyway, and no great loss. I much prefer to keep related .xaml files together, irrespective of whether they are windows or user controls.

In order to keep the user controls together with the parent window, they should be nested. Whilst this can be done manually, it's slow and painful, and very easy to get wrong, which mucks up your project file and causes Visual Studio to have a hissy fit. Thankfully, someone has been kind enough to write a very neat extension, which enables you to nest files quickly and easily. Once you have it installed, you right-click on the file(s) that is/are to be a child(ren), and choose File Nesting -> Nest Item from the context menu (or just click Ctrl-Alt-N if you like keyboard shortcuts). This will pop up a small window, which will show you all the other files in the same folder...

Pick one and click the OK button. This will then nest the file(s) under the parent, leaving a neat structure. You can select multiple files, and nest them all under one parent in one go, which is nice.

As you can see, this worked very nicely for the quote window...

We were then able to work on separate parts of the same window, with a minimal amount of conflicts.

This then left the question of how to handle the view model, as we would still only have one of those. However, I have previously solved this problem by splitting the view model into several files. I had previously split another view model across four separate files, which makes it much easier to handle...

This is pretty easy to do. I was working with a class named VRTSystemsListViewModel. In such a case, you would add a new class to the same folder, and name it (say) VRTSystemsListViewModel_Commands. Then change the file name to VRTSystemsListViewModel.Commands.cs, and the class name to VRTSystemsListViewModel (making it partial of course). Then, you need to nest the child view model files under the parent (see above for those with an extremely short memory).

Note that the systems list view model was split into separate files for commands, INPC properties, messages, etc. On reflection, this wasn't the best way to do it, partly because it leaves related code spread over multiple files, and partly because it increases the chances of conflicts. If they had been split according to functionality, then we would have had the same benefits as explained earlier. I later did this for the system details window view model...

As you can see, the view model has been split according to features, making it less likely that two people would be working on the same files at the same time.

There was an unexpected side benefit to this idea. If you've spent any amount of time twiddling your thumbs while Visual Studio loads or saves a XAML file, you'll know how frustrating this is.

It's known issue with Visual Studio, which Microsoft have never acknowledged, and will presumably never fix. However, by splitting the XAML as described above, we dramatically reduced the amount of time Visual Studio spent thinking about loading and saving the XAML files. That made us happy

Thursday, 18 February 2016 17:00:00 (GMT Standard Time, UTC+00:00)

Every now and then, I have seen my CPU usage jump up to close to 100% on all cores, which can slow things down somewhat...

This looks really impressive, like I'm working so hard that my machine can't keep up with my frantic pace. Sadly, this isn't always the truth!

Looking at Task Manager, shows the culprit to be microsoft.alm.shared.remoting.remotecontainer.dll.

If you are using VS2013 or later, you may notice some annotations above your methods and properties...

This feature is known as Code Lens, and is one of those things that is really worth getting to know, as it's a massive time-saver.

Quick digression from the main theme of today's symposium to tell you why it's so good...

By default, there are about five or six code lenses, but as I've changed my options to show only one, only that one is visible in the picture above. This one allows you to see all references to the item in question. Click on the link and you'll see something like this...

This can be docked as a window (click the little rectangular icon in the top-right corner of the code lens pop up). If you double-click an item in the list, you are taken to the appropriate line. Jolly useful.

End of digression, back to the point

However, this fab feature comes with a price. The assembly responsible for scanning your code and updating the Code Lens is the one mentioned above, and can use whopping amounts of CPU.

However, as the most (and in my opinion only) useful part of Code Lens is the references, you can tell VS not to bother with the rest, which will avoid the CPU usage. If you write unit tests (I know, we all should, but let's be honest, most of us don’t!), then the unit test one is also very useful, as it shows you how many tests hit that method and how many passed. However, unless you're really doing TDD properly, it won't be that much use.

Go to Tools -> Options -> Text Editor -> All Languages -> Code Lens and uncheck all of the individual checkboxes. Leave the "Enable CodeLens" checkbox checked, as this will give you the references link...

This should make a big difference to the CPU usage.

Possibly useful extra tip

The other thing that sometimes helps is to have a look in C:\Users\<username>\AppData\Local\Temp\ALM\ShadowCopies\<some_guid> and see how many folders there are. The more there are, the slower Code Lens will be.

You can safely delete them all, and it will slowly replace them for you. I had 5,400 of them, but have seen reports of 190,000! You'll need to do this every now and then if you find that microsoft.alm.shared.remoting.remotecontainer.dll continues to use CPU.

However, I found that they were replaced almost as quickly as I deleted them, so your mileage may vary.

Wednesday, 17 February 2016 17:00:00 (GMT Standard Time, UTC+00:00)
# Tuesday, 02 August 2011

Sadly, whilst building a solution yesterday, my machine started behaving in a very weird manner, with applications not responding, the taskbar disappearing and so on, followed by the dreaded blue screen of death. When I checked the event log after pulling the plug out (I hate doing that!) and rebooting, I found lots of errors, which led me to a Microsoft Connect article where someone was reporting a very similar problem.

To my amazement, the very last comment by a Microsoft employee in response to this bus report was “This is known issue, this bug was resolved by mistake, we are already addressing this issue.”

Surely they didn’t mean that did they? Someone tell me i read that wrong!

Tuesday, 02 August 2011 13:47: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)

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)));
   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)