Friday, December 07, 2012

The Silverlight.net web site is apparently now gone, merged into the broader msdn.com ecosystem (where it belonged in the first place imo):

http://www.zdnet.com/microsoft-pulls-the-plug-on-its-silverlight-net-site-7000008494/

As we’ve known now for a long time, Silverlight is “dead”. It is in support mode and will be for a decade.

Just like Windows Forms has been since 2005, and WPF is now as well (do you really think Microsoft is going to divert money from WinRT to do anything with WPF at this point??? If so I’ve got this beachfront property for sale…).

As an aside, ASP.NET Web Forms also “died” in 2005, but recently got a major infusion of money in .NET 4.5 – showing that even a “dead” technology can receive a big cash investment sometimes – though it still isn’t clear that this will be enough to breath any new life into Web Forms for most organizations. I suspect it is more likely that this recent investment will just allow organizations with massive Web Forms sites to keep them limping along for another 5-10 years.

If a technology is defined as “dead” when its vendor stops enhancing it and starts maintaining it while they put most of their money into the future, then I must say that I’ve spent pretty much my entire ~25 year career working on dead technologies. And it has been fun! Smile

Although some of us tech geeks like to jump to the next potential upcoming thing, the people who actually fund software projects rarely want to accept that kind of risk. They generally prefer to build applications on stable technology. Most stable technology is “dead” or “dying” based on this idea of “live” technology being rapidly changing and evolving.

Obviously there’s a fine line here.

Target stable technology that is too old and you really are in trouble. Windows Forms is an example of this, because its underlying technology has no migration path to a WinRT future. Although a lot of organizations have massive investments in Windows Forms, I would hope that they’d shy away from starting new development on this extremely stable, but now too old, technology.

Target stable technology that is new, but old enough to be stable and life is generally pretty good. WPF and Silverlight (for smart clients, not for cross-platform RIA) are examples of this. The reason is that these technologies (especially Silverlight) have a good migration story to a WinRT future. A lot of organizations are investing in WPF, and that’s good. But I’d be shocked if Microsoft invests anything in WPF going forward – its future is the one Windows Forms has enjoyed since 2005 – stable maintenance of the technology. Perfect for building critical business apps. Organizations also have large investments in Silverlight, and as long as the intent was smart client development (not cross-platform RIA) it seems to me that they are in the exact same place as everyone using WPF. Arguably better, because Silverlight is much closer to WinRT than WPF.

http://magenic.com/Portfolio/WhitePaperWindows8DevelopmentPlatform.aspx

If you are using Silverlight for cross-platform rich web development, then I do agree that the news is not good. The current alternative appears to be HTML 5, though it is also clear that this is an expensive alternative with an unsure future. Just like every other silver bullet to write once and run anywhere, I think you have to go into such a venture expecting a lot of cost and pain. There’s no widely successful example in the history of computing that indicates otherwise…

The final option is to target “live” technologies. You know, the ones where vendors are dumping huge amounts of money, and where the technology and platform are changing rapidly. Things like HTML 5 and WinRT are examples of this. As a tech geek I love it when organizations want to do this sort of thing, because the challenge is high and we all get to learn a lot of new stuff. Of course the development costs are also quite high because we’re getting paid to learn this new stuff. And the overall costs for the software are high because the technology/platform isn’t stable and the app probably needs to be rewritten (in whole or part) every few months to deal with platform changes.

Some organizations are willing to accept the costs and inconvenience associated with using “live” technologies. But most organizations don’t have the time or money or risk tolerance, and are far better off targeting “dead” technologies like WPF and Silverlight. They just need to be careful to have strategic migration plans so they can get off those technologies before they reach the point of where Windows Forms is today.

Friday, December 07, 2012 11:23:33 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [6]  | 
 Tuesday, October 09, 2012

CSLA 4 version 4.5 supports the async and await keywords across all platforms (WinRT, .NET 4.5, .NET 4, Silverlight 5).

You can use these async features to implement async rules in the CSLA rules engine. Here’s one such rule:

public class CustomRule : Csla.Rules.BusinessRule
{
  public CustomRule(Csla.Core.IPropertyInfo primaryProperty)
    : base(primaryProperty)
  {
    InputProperties.Add(primaryProperty);
    IsAsync = true;
  }

  protected async override void Execute(Csla.Rules.RuleContext context)
  {
    var cmd = new LongRunningCommand();
    cmd = await DataPortal.ExecuteAsync(cmd);
    context.AddInformationResult("Rule complete: " + cmd.Output);
    context.Complete();
  }

  [Serializable]
  public class LongRunningCommand : CommandBase<LongRunningCommand>
  {
    public static readonly PropertyInfo<string> OutputProperty = RegisterProperty<string>(c => c.Output);
    public string Output
    {
      get { return ReadProperty(OutputProperty); }
      private set { LoadProperty(OutputProperty, value); }
    }

    protected new async Task DataPortal_Execute()
    {
      Output = "Before delay";
      await Task.Delay(3000);
      Output = "After delay";
    }
  }
}

Notice that the rule’s constructor sets the rule’s IsAsync property to true. This tells the CSLA rules engine that the rule will be async.

Also notice that the rule’s Execute method is marked with the async keyword, allowing the use of the await keyword within the method. In this example, the rule uses the data portal to asynchronously execute a command object by awaiting the ExecuteAsync method.

Because the rule has IsAsync true, the Execute method must call context.Complete to indicate that the rule has finished processing. If you don’t call context.Complete the CSLA rule engine will never process the rule’s result, and you’ll have a bug in your application.

The command object itself also uses the async keyword to implement the DataPortal_Execute method. Notice that this method returns a Task. The server-side data portal components are smart enough to detect when a DataPortal_XYZ method returns type Task, so the DataPortal_XYZ method is invoked correctly.

Within the DataPortal_Execute method I just use Task.Delay to create an artificial delay. This represents some long-running operation such as calling a slow web service, invoking an intensive oData query, or something like that.

The end result is that a business object can attach this CustomRule to a property, and the rule will run asynchronously. This is done in the business class’s AddBusinessRules method.

In your UI you can use helper components such as Csla.Xaml.PropertyInfo to determine that the property is running an async rule. For example, you might use XAML like this in WinRT:

<StackPanel Orientation="Horizontal">
  <TextBox Text="{Binding Path=Name, Mode=TwoWay}"/>
  <TextBlock Text="{Binding ElementName=NameInfo,Path=RuleDescription}" Foreground="Yellow"/>
  <ProgressRing IsActive="{Binding ElementName=NameInfo,Path=IsBusy}"/>
  <csla:PropertyInfo Name="NameInfo" Source="{Binding}" Property="Name"/>
</StackPanel>

The specific XAML syntax is a little different in WPF/Silverlight because the XAML language is more mature there than in WinRT. But the basic concept of building a rich user experience based on an async rule is the same across all smart client platforms.

Tuesday, October 09, 2012 3:59:52 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Tuesday, November 08, 2011

Disclaimer: I know nothing. The following is (hopefully) well educated speculation on my part. Time will tell whether I’m right.

I really like Silverlight. I’ve been a strong proponent of Silverlight since 2007 when I rushed to port CSLA .NET to the new platform.

In fact, Magenic provided me with a dev and test team to make that transition happen, because we all saw the amazing potential of Silverlight.

And it has been a good few years.

But let’s face reality. Microsoft has invested who-knows-how-much money to build WinRT, and no matter how you look at it, WinRT is the replacement for Win32. That means all the stuff that runs on Win32 is “dead”. This includes Silverlight, Windows Forms, WPF, console apps – everything.

(this is partially in answer to Mary-Jo’s article on Silverlight 5)

I wouldn’t be surprised if Silverlight 5 was the last version. I also wouldn’t be surprised if .NET 4.5 was the last version for the Win32 client, and that future versions of .NET were released for servers and Azure only.

Before you panic though, remember that VB6 has been “dead” for well over a decade. It died at the PDC in 1999, along with COM. But you still use VB6 and/or COM? Or at least you know organizations who do? How can that be when it is dead??

That’s my point. “dead” isn’t really dead.

Just how long do you think people (like me and you) will continue to run Win32-based operating systems and applications? At least 10 years, and many will probably run 15-20 years into the future. This is the rate of change that exists in the corporate world. At least that’s been my observation for the past couple decades.

Microsoft supports their technologies for 10 years after a final release. So even if SL5 is the end (and they haven’t said it is), that gives us 10 years of supported Silverlight usage. The same for the other various .NET and Win32 technologies.

That’s plenty of time for Microsoft to get WinRT mature, and to allow us to migrate to that platform over a period of years.

I don’t expect WinRT 1.0 (the Windows 8 version) to be capable of replacing Win32 or .NET. I rather expect it to be pretty crippled in many respects. Much like VB 1.0 (and 2.0), .NET 1.0 and 1.1, Silverlight 1 and 2, etc.

But Windows 9 or Windows 10 (WinRT 2.0 or 3.0) should be quite capable of replacing Win32 and .NET and Silverlight.

If we assume Win8 comes out in 2012, and that Microsoft does a forced march release of 9 and 10 every two years, that means 2016 will give us WinRT 3.0. And if we hold to the basic truism that Microsoft always gets it right on their third release, that’ll be the one to target.

I think it is also reasonable to expect that Win9 and Win10 will probably continue to have the “blue side” (see my Windows 8 dev platform post), meaning Win32, .NET, and Silverlight will continue to be released and therefore supported over that time. They may not change over that time, but they’ll be there, and they’ll be supported – or so goes my theory.

This means that in 2016 the clock might really start for migration from Win32/.NET/Silverlight to WinRT.

Yes, I expect that a lot of us will build things for WinRT sooner than 2016. I certainly hope so, because it looks like a lot of fun!

But from a corporate perspective, where things move so slowly, this is probably good news. Certain apps can be ported sooner, but big and important apps can move slowly over time.

What to do in the meantime? Between now and 2016?

Focus on XAML, and on n-tier or SOA async server access as architectural models.

Or focus on HTML 5 (soon to be HTML 6 fwiw, and possibly HTML 7 by 2016 for all we know).

I’m focusing on XAML, creating a CSLA 4 version 4.5 release that supports .NET 4.5 on servers, Azure, Windows (Win32), and Windows (WinRT). And Silverlight 5 of course.

In fact, the plan is for a version 4.3 release to support Silverlight 5, then version 4.5 with support for .NET 4.5 and WinRT.

I suspect that you can use Silverlight or WPF as a bridge to WinRT. The real key is architecture.

  1. An n-tier architecture is fine, as long as the data access layer is running on a server, and the client uses async calls to interact with the server. WinRT requires a lot of async, at a minimum all server interactions. Silverlight forces you to adopt this architecture already, so it is a natural fit. WPF doesn’t force the issue, but you can choose to do “the right thing”.
  2. You can also build your client applications to be “edge applications” – on the edge of a service-oriented system. This is a less mature technology area, and it is more costly. But it is also a fine architecture for environments composed of many disparate applications that need to interact as a loosely coupled system. Again, all service interactions by the edge applications (the ones running on the clients) must be async.
  3. Or you can build “hybrid solutions”, where individual applications are built using n-tier architectures (with async server calls). And where some of those applications also expose service interfaces so they can participate as part of a broader service-oriented system.

I favor option 3. I don’t like to accept the cost and performance ramifications of SOA when building an application, so I’d prefer to use a faster and cheaper n-tier architecture. At the same time, many applications do need to interact with each other, and the requirement to create “application mashups” through edge applications happens from time to time. So building my n-tier applications to have dual interfaces (XAML and JSON for example) is a perfect compromise.

The direct users of my application get n-tier performance and maintainability. And the broader organization can access my slower-moving, standards-based, contractual service interface. It is the best of both worlds.

So do I care if Silverlight 5 is the last version of Silverlight?

Only if WPF continues to evolve prior to us all moving to WinRT. If WPF continues to evolve, I would expect Silverlight to, at a minimum, keep up. Otherwise Microsoft has led a lot of people down a dead-end path, and that’s a serious betrayal of trust.

But if my suspicions are correct, we won’t see anything but bug fixes for WPF or Silverlight for many years. I rather expect that these two technologies just became the next Windows Forms. You’ll notice that WinForms hasn’t had anything but bug fixes for 6 years right? The precedent is there for a UI technology to be “supported, stable, and stagnant” for a very long time, and this is my expectation for WPF/SL.

And if that’s the case, then I don’t care at all about a Silverlight 6 release. We can use WPF/SL in their current form, right up to the point that WinRT is stable and capable enough to act as a replacement for today’s Win32/.NET applications.

Tuesday, November 08, 2011 8:51:12 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [22]  | 
 Monday, October 24, 2011

At Visual Studio Live! last week I used some slides that several of us at Magenic have been working on to provide clarity around the “Windows 8” development platform, based on what we know from //Build/ 2011. I wanted to share some of these slides here.

We’re also working on a related white paper that will be online soon, and I’ll link to that when it is available.

First, is the obligatory Microsoft “boxology” diagram that generated so much controversy due to its over-simplistic design:

image

Although this diagram is usually found to be lacking, it did set the standard for the green/blue color scheme and overall layout of everyone else’s “boxology” diagrams – including ours.

Magenic Windows 8 Diagram

Here is the Magenic diagram that provides more detail and clarity:

image

Win32 (blue) is the existing Windows operating system API, and it shouldn’t be surprising that it supports existing technologies.

WinRT (green) is the new Windows operating system API, that I suspect will replace Win32 over a period of many, many years. In my mind this is absolutely necessary. Win32 is more than 16 years old, and just doesn’t provide the capabilities we want in a modern operating system. Hopefully the new WinRT API will provide these capabilities, and will last for another 15+ years.

The idea in the Magenic diagram is to clearly show the WinRT (Metro, green) and Win32 (desktop, blue) sides of the Windows 8 platform, and the various development technology stacks that can be used to build software for each operating system API.

To provide even more clarity, we have a series of highlight diagrams for various technology stacks.

The Desktop (blue)

I’ll start by walking through all the technology stacks on the desktop (blue) side of the master diagram:

  • Silverlight
  • WPF
  • Web sites with plugins
  • Web sites with pure HTML/js
  • Windows Forms
  • C++, MFC, ATL

Each technology maps directly from today into Windows 8.

Silverlight

image

Silverlight runs in Win8 in the desktop browser, and out of browser, just like it does today on Win7.

WPF

image

WPF runs in the Win8 desktop just like it does today in Win7.

Web sites with plugin support

image

Today’s web sites that use HTML, js, Flash, Silverlight, ActiveX, and other common web technologies all run in the desktop web browser. This is the same as web sites work today in Win7.

Web sites with pure HTML/js

image

If a web site only uses HTML, CSS, and js, then it can run in the WinRT and desktop browsers interchangeably. Microsoft clearly expects this type of web site to become more common over time, though it is interesting that a large number of existing Microsoft web sites are really only useful in the desktop browser.

Windows Forms

image

Windows Forms continues to run in Windows 8 on the desktop, just like it does in Win7. This isn’t surprising, given that Windows Forms is almost certainly still the dominant technology for building Windows smart client applications, even though the technology hasn’t had anything beyond bug fixes since 2005. It goes to show how stability in a platform is important, and attracts widespread use for business development.

C++, MFC, ATL

image

Although little business development is done with C++ anymore, this technology remains relevant for game developers, OS and device driver developers, and every now and then I encounter someone using it for business development. From my perspective, the important thing about C++ support is that my favorite games will probably continue to run on Win8 in the desktop.

WinRT (green)

Next, I’ll walk through the three technologies that support the WinRT API:

  • WinRT .NET
  • WinRT HTML 5
  • WinRT C++

Each technology draws from existing technologies by the same names, but in each case there’s a little “twist” as you move from the Win32 to the WinRT platform.

WinRT .NET and XAML

image

I expect this to be the most widely used technology stack for building WinRT applications. The .NET available to WinRT applications is (I think) best thought of as being like .NET on the Windows Phone. It is basically the Silverlight subset of .NET, plus a bunch of WinRT-specific features and capabilities. The differences between Silverlight and WinRT are a bit more dramatic than with WP7, but the analogy remains quite accurate.

The XAML is very close to Silverlight and WPF, and the types of code you can write using C# and VB are very comparable to what you can write today using Silverlight.

As a preview: the white paper we’re creating at Magenic ultimately concludes that using Silverlight today provides the easiest transition to WinRT in the future. Not seamless or trivial, but practical. We also conclude that WPF can enable a WinRT transition too – especially if you limit your use of WPF and .NET to the Silverlight subset of behaviors and features.

WinRT HTML 5

image

Microsoft has made much of the HTML 5 technology stack for building WinRT applications. In no way are we talking about web sites, web pages, or web applications here. This is smart client development done using technologies that were previously web-focused.

For a .NET developer, the technologies map like this:

  • HTML instead of XAML
  • JavaScript instead of C#
  • WinJS instead of the .NET BCL

In my conversations with traditional web developers, it is a brain-bending moment when I point out that there is no web server involved, and so no server-side code at all here. All the stuff that is done in ASP.NET or PHP is now done in JavaScript. From an architecture, design, and application functionality perspective, a WinRT HTML 5 app is almost, but not completely, unlike a web app.

On the positive side, if a web developer can learn and embrace the smart client architectural model, their skills with HTML, CSS, and JavaScript will carry over to this new platform. Some HTML and CSS assets, and perhaps some js assets, will carry from web development into this type of smart client development as well.

WinRT C++

image

Finally, C++ remains relevant on WinRT as well. This should come as no surprise, given that the Windows OS developers primarily use C++, and there’ll hopefully be games and other applications that are traditionally created using this technology.

I also suspect that Objective C apps will port to WinRT more directly through C++ than with C# or js, and (at least for my part) I hope that some of the existing iPad/iPhone apps quickly make their way onto WinRT so I can enjoy them.

Summary

Through this series of diagrams, we clearly show how today’s technologies map directly into the Win8 desktop world, still running on the Win32 API. And we show the three technology stacks that enable development of applications on the new WinRT API.

From everything we know today, it seems clear that migrating to WinRT will require effort, regardless of the technology used today, or in the Win8 desktop. Of all existing technologies, Silverlight and then WPF appear to offer the easiest migration. HTML 5, css, and js skills, along with some code assets will also migrate, but there’s a non-trivial architectural difference between web development and smart client development that shouldn’t be overlooked.

As Microsoft releases updates to the Win8 preview and moves into a beta process, I’m sure that we’ll learn more about the platform and how existing technologies map into the future. It will be interesting to see how we need to update these diagrams as Microsoft provides more information over time.

Windows 8 is exciting, and the new WinRT platform is long-overdue. I look forward to building WinRT applications in the not-to-distant future!

Monday, October 24, 2011 11:08:54 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [7]  | 
 Friday, February 18, 2011

Bxf and CSLA .NET both include a TriggerAction control. This control helps support the MVVM design pattern in WPF, Silverlight, and WP7 applications.

(Bxf is completely independent from CSLA – I donated TriggerAction from CSLA to the Bxf project a while back though, so this type is available from either framework)

The specific problem addressed by TriggerAction is the need to invoke a verb (method/command) on your viewmodel object in response to any arbitrary UI event. One common UI event is something like a button click event, though you can often use commanding in that case. But there are numerous other UI events from many controls other than buttons, and you might want to have one of those UI events cause the viewmodel to perform an action.

TriggerAction basically wires arbitrary UI events to methods on the current DataContext (usually the viewmodel object).

<bxf:TriggerAction TargetControl="{Binding ElementName=MyControl}"
                                           TriggerEvent="MouseOver"
                                           DataContext="{Binding Source={StaticResource vm}}"
                                           MethodName="MyAction" />

TriggerAction listens for the trigger event from the TargetControl. When it handles that event, it invokes the specified method (MethodName) on its current DataContext object. There’s nothing more to it.

To get TriggerAction working you need two things: source and target.

Source:

  1. TargetControl must be set
  2. TriggerEvent may be set (default is “Click”)

Target:

  1. DataContext must be set (or inherited from the container)
  2. MethodName must be set

Parameter (optional):

  1. MethodParameter may be set (to a value or binding expression)
  2. RebindParameterDynamically may be set to true (to force rebinding of MethodParameter to work around issues with certain control properties such as ListBox.SelectedItems)

The most common causes of failure when using TriggerAction are that the TargetControl isn’t set right, or the DataContext isn’t set right, and of those two the most common is that the DataContext isn’t what you think it is (that happens to me all the time).

The method TriggerAction invokes on the DataContext object can accept either 0 or 2 parameters:

public void MyAction()

or

public void MyAction(object sender, ExecuteEventArgs e)

The ExecuteEventArgs class is also defined in Bxf and CSLA. If you use TriggerAction from Bxf.Xaml, you must use ExecuteEventArgs from Bxf.Xaml. If you use TriggerAction from Csla.Xaml, you must use ExecuteEventArgs from Csla.Xaml.

If you are using Bxf and CSLA together it is important to understand that the ViewModel<T> class from Csla.Xaml uses the Csla.Xaml.ExecuteEventArgs type. If you are using the Bxf TriggerAction control, you’ll need to create your own viewmodel types from Csla.Xaml.ViewModelBase<T> to accept the Bxf.Xaml.ExecuteEventArgs type.

Bxf | CSLA .NET | Silverlight | WP7 | WPF
Friday, February 18, 2011 5:31:39 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [2]  | 
 Tuesday, November 09, 2010

Over the past few months there’s been this ongoing buzz about whether WPF is dead, or whether Silverlight is really mature – in short, people trying to figure out whether to use WPF or Silverlight or both.

Having worked with WPF since it came out, and with Silverlight 2.0 and higher since before it came out, I thought I’d share my thoughts.

This post flows from my experiences with CSLA .NET, UnitDriven and Bxf – three frameworks I’ve created or been directly involved with, that run on WPF (.NET), Silverlight and now Windows Phone 7 (WP7). With CSLA in particular, I’ve been maintaining this one codebase on .NET since 2001, and to my knowledge it was the first major framework ported to Silverlight from .NET. Also, as I write about this, I’m thinking about how I build XAML-based apps, using the MVVM pattern as discussed in the CSLA 4 MVVM video series and some of my previous blog posts.

The way I use SL and WPF there is no meaningful difference between them. My MVVM demos, for example, are mostly the same across WPF, SL and even WP7.

The business layer, created with CSLA 4, is typically identical across all three platforms. That’s one of the big benefits of CSLA 4, in that you can write your business, validation and authorization rules once and use them across multiple interface technologies. And with the data portal managing any interactions with the application server, you are shielded from any complexity or differences you’d normally encounter there as well.

The way I use MVVM, with a strong focus on having zero code-behind any XAML, means that nearly all interface control logic (any actual code in the presentation layer) is also reused. Any presentation layer code is either in the viewmodel, in value converters, in attached properties or custom controls. This reuse isn’t always 100%, especially when you get to WP7, because the tiny phone screen often forces a different user workflow than if you have a full-size screen like in WPF or SL. But between WPF and SL, the viewmodel code is typically the same, as is most value converter and attached property code. Some custom controls may be different – again especially on the phone.

This commonality of viewmodel code is thanks to the use of Bxf. But any decent MVVM framework will offer the same kind of abstractions, so your application code is never directly interacting with the UI shell or any platform-specific constructs or types.

With WPF and SL there are places of direct difference however, depending on how you structure your user experience.

  • WPF doesn't have a URL based navigation scheme or a navigation framework, so you have to come up with your own UI framework to manage any sort of navigation model. I usually do this by having exactly one Window, and that hosts all my content in the form of UserControl objects, but you could use many Window objects.
  • SL does have an optional URL based navigation scheme and framework, which is nice - makes things simpler. However, you can use the same "one Window that hosts UserControl objects" model just like WPF (hence my samples are the same). What you can't do is have a lot of Window objects (which to me is no loss, since the multiple SDI interface went out of style in 1997).
  • WP7 also has a URL based navigation scheme and framework. I still use the hosted UserControl idea too, and that makes a lot of the code common with SL and WPF.

I think the thing to understand, is that while SL runs in the browser, it is a smart client technology. It is far more like WPF than like HTML. In fact it is virtually identical to WPF in most ways that matter for a business app.

And the key to my success in this area, is that all my business “forms” or “pages” are always a subclass of UserControl. So every bit of meaningful UI content (forms/pages) are UserControl objects that can be hosted by the UI shell. This means that I can usually change out the shell, or even have different shell styles (URL navigation vs Outlook-style navigation for example) and this has no effect on the actual business UI elements. Yes, the shell code may be different, but the business code is unchanged.

This is one powerful technique that makes it quite realistic to create your app in Silverlight, even using the navigation framework, and then port it to WPF if you need to in the future. You might have to write some new WPF shell code, but your UserControl XAML, your viewmodels, your business domain objects, your data access code and your database remain unchanged.

Beyond UI and navigation differences, there are some technical differences between WPF and SL, including:

  • Some minor, niggling differences in XAML - this is the sort of thing I personally want fixed now that the WPF and SL product teams have merged - this niggling differences are stupid and are nothing but an annoyance – why is the binding Mode default different between WPF and SL (for example)??
  • SL requires that all server interactions be async, WPF allows sync or async - I tend to use async in both places, because the user experience is so superior with async, I can't figure out why I'd want to punish my end users just because they are using WPF
  • SL has the navigation framework, WPF doesn't
  • WPF has an application model that includes navigation, but it is hopelessly broken - it tried to emulate the worst features of the web without any of the benefits - to me this is the "ActiveX Documents" of WPF
  • WPF apps can use all of .NET, SL uses a subset - but the SL subset is everything I've needed to build typical business apps
  • WPF apps can interact with the full client workstation hardware (odd peripherals, the full hard drive, etc)
  • WPF apps are (typically) deployed via ClickOnce, SL apps are deployed transparently via the browser - so WPF is slightly more "in your face" for your users, but the difference should be pretty incidental
  • WPF apps can tap into all of DirectX, though SL now has hardware acceleration for some graphics scenarios too - so this difference is probably less meaningful for most business apps than for games
  • SL doesn't have the complexity of the legacy "crap" that comes with WPF (DataSet, IBindingList, etc) so it is a simpler, easier and more consistent programming environment
  • SL runs on Windows, in the browser, on the Mac, in the browser on the Mac, and in WP7; WPF of course runs only on Windows

Again however, I come back to the same thing - I always use as little of any platform/technology as necessary to get the job done. SL is a subset, so if I can get the job done with SL then that's the best thing to do (I can always upsize to WPF later if necessary). If I can't get the job done with SL, I'll use WPF.

In my mind it is a superset/subset decision - always default to the subset that meets your needs.

As long as you understand both technologies, you can architect your UI so transitioning from SL to WPF is relatively easy (the other way isn't always so easy - because your WPF code might use superset technologies).

In conclusion, my recommendation has been (since SL3 at least) to design your app for SL, and fall back to WPF only if SL can’t meet your needs. The most common scenarios for business apps to fall back to WPF are:

  • Your app is only occasionally connected, and is mostly offline, so you use a client-side database like SQL Express or SQL CE
  • Your app needs to interact with client-side peripherals
  • Your app needs full access to the client-side hard drive

I don’t think this is a “WPF vs SL” thing at all. I think it is a sliding scale, where you default to SL, and slide up to WPF if necessary. All the angst is unnecessary.

Bxf | CSLA .NET | Silverlight | WP7 | WPF
Tuesday, November 09, 2010 10:06:24 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [18]  | 
 Friday, October 22, 2010

I am pleased to announce the first beta release of CSLA 4 version 4.1 with support for Windows Phone 7, and continuing support for .NET 4 and Silverlight 4.

Download CSLA 4 version 4.1.0 here

With this release, it is now possible to write a single business layer composed of business domain objects that run unchanged on a WP7 device, in Silverlight, on a Windows client, on Windows Server and on Windows Azure.

The samples download includes Samples\Net\cs\SimpleNTier, which does implement the following interfaces over one common business layer:

  • Windows Phone
  • WPF
  • Silverlight
  • ASP.NET MVC

Of course this is just the first beta release, so there’s more work to be done. At the same time, we have completed the vast majority of the effort, and it is quite possible to build WP7 applications using this beta.

As with all CSLA releases, this one does include some bug fixes and enhancements to other parts of the framework. Please see the change log for a list of all changes. Enhancement highlights include:

  • Add ability to get a consolidated list of broken rules for an object graph
  • New BackgroundWorker component that automatically initializes background threads with the current principal and culture from the UI thread
  • TriggerAction provides better debugging information, following the lead of many Microsoft XAML controls
  • and much more…

In related news, UnitDriven has also been updated to support WP7, and provides a pretty comprehensive unit test runner and framework for WP7 code. CSLA uses UnitDriven for its automated testing, but UnitDriven can be used for any application on .NET, Silverlight or WP7.

Similarly, Bxf (Basic XAML Framework) has been updated to support WP7, thereby providing a common MVVM framework for WPF, Silverlight and WP7 UI development efforts. Some CSLA sample apps use Bxf, but Bxf can be used for any application, including those that don’t involve CSLA at all.

Bxf | CSLA .NET | Silverlight | Web | Windows Azure | WP7 | WPF
Friday, October 22, 2010 1:35:18 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Saturday, July 31, 2010

The CSLA .NET and MVVM video series is now complete and online.

The first video in the series is available for free from the download page, so you can get a better idea about the approach I’m taking in using MVVM with CSLA 4 and Silverlight or WPF.

This is a six part series (nearly 3.5 hours of content) covering the Model-View-ViewModel (MVVM) design pattern and how to efficiently apply it when your model is constructed using CSLA 4, and your UI is built using Silverlight or WPF.

That means you have a rich business domain model that fully encapsulates your business logic (validation, authorization, calculations, etc), and those objects (thanks to CSLA) fully support all the data binding semantics for Silverlight and WPF. And it means you have access to useful helper components and controls from the Csla.Xaml namespace, including viewmodel base classes, validation information display and UI event triggering to help wire up UI events to viewmodel verbs/methods.

The series also makes use of the Bxf framework, which is an extremely lightweight MVVM UI framework designed to illustrate the basic concepts of an MVVM framework. Like MVC, it is really impossible to make effective use of the MVVM design pattern without some level of framework support. Something has to manage the creation and display of views, and the process of wiring up a viewmodel to a view, just like something has to route commands to a controller and render views in MVC. Bxf is the smallest possible set of framework behaviors I’ve been able to identify that makes MVVM practical to implement.

As a bonus, the sixth video in the series discusses how to apply the concepts from the video series in CSLA .NET 3.8.4 with Visual Studio 2008. Even if you can’t move to CSLA 4, .NET 4 and Visual Studio 2010 yet, the vast majority of the content in this video series is still valuable!

If you are using CSLA .NET to build Silverlight or WPF applications, or if you want to explore some practical ways to think about and implement the MVVM design pattern, this video series is a must have!

Saturday, July 31, 2010 11:36:49 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [1]  | 
 Tuesday, July 13, 2010

I have put the CSLA 4 MVVM video series on the store:

http://store.lhotka.net/Default.aspx?tabid=1560&ProductID=21

The video series is not complete, but the first two segments are online.

The current $44.95 $74.95 purchase price is a limited time offer - a discount from the final price (to be determined) for people willing to buy now and get the rest of the content as it is completed.

I expect to complete the series by the end of July, so if you want the discount please act soon.

Tuesday, July 13, 2010 8:45:07 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [5]  | 
 Tuesday, June 08, 2010

Over the past few months I’ve been researching, writing and speaking about MVVM quite a lot. One of the teaching tools I’ve developed has turned out to be useful for both teaching and actually building applications. This is the Bxf (Basic XAML Framework) code I’ve developed.

I must confess, I have little interest in becoming a UI framework author. But I also recognize that you can’t do any UI pattern like MVVM (or MVC) without some minimal framework support – there’s just some plumbing code you must have for the pattern to be actually useful.

Bxf is the minimum set of functionality I’ve been able to identify to support MVVM, with a couple other key goals:

  1. Support MVVM so a developer only creates a View, ViewModel and Model
  2. Same functionality/code in Silverlight and WPF
  3. Zero code-behind the XAML – any UI code goes in the viewmodel, and binding/commanding/trigger actions are used to allow the view to interact with the viewmodel
  4. Enable the use of the Visual Studio 2010 XAML designer (“Cider”), most notably the drag-and-drop data binding support it provides
  5. Enable the use of Expression Blend

I’ve included Bxf in some samples from the Visual Studio 2010 launch and for CSLA 4. But I’ve decided that’s too random, so I created http://bxf.codeplex.com to house the code.

My hope is that other people who find Bxf useful might choose to join the project as contributors and extend it to be more broadly useful. However, I also hope that the framework remains extremely simple and minimalistic (since there are already several quite robust and complex frameworks out there for people who need more than a simple solution can offer).

Bxf | Silverlight | WPF
Tuesday, June 08, 2010 12:23:23 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [3]  | 
 Wednesday, June 02, 2010

I am working on a video series discussing the use of the MVVM design pattern, plus a “zero code-behind” philosophy with CSLA .NET version 4.

I’ve decided to put the intro video out there for free. It is a good video, covering the basics of the pattern, my approach to the pattern and how a CSLA-based Model works best in the pattern.

http://www.lhotka.net/files/MvvmIntro.wmv

The rest of the series will be demo-based, covering the specifics of implementation. I’ll add another blog post when that’s available for purchase, but I thought I’d get this intro online now so people can make use of it.

Wednesday, June 02, 2010 12:36:58 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [4]  | 
 Monday, April 19, 2010

I have put the demos from my Visual Studio 2010 launch talks online:

http://www.lhotka.net/files/devconn/VS2010Launch.zip

BasicVM and LiveDemo are literally the code I created on stage, so they are nothing to look at and probably have little value if you weren’t at the talks. The other demos are more complete and may be useful – especially UsingBxf, which shows some interesting UI proto-framework concepts in a pretty straightforward manner.

BasicVM

Demo created on stage to illustrate the most basic MVVM concepts.

Collective

Demo/prototype of a knowledge base/forum application that makes use of a pre-release version of CSLA 4, MVVM and other Silverlight concepts. It is a 3-tier physical deployment (Silverlight client, web/app server, SQL Server database) architecture using many CSLA .NET concepts.

This code uses the Bxf (“Basic XAML Framework”) to implement its shell and viewmodel code in a way that can be unit tested.

This project has a dependency on a pre-release version of CSLA 4.

LiveDemo

Demo created on stage to illustrate the basic use of the Visual Studio 2010 XAML designer.

UsingBxf

Demo showing simple use of the “Basic XAML Framework” (Bxf) in WPF. The same Bxf code works in Silverlight as well. The Bxf code and this demo show how to implement a basic UI shell that shows content and a status bar. For more advanced uses of Bxf see the Collective demo.

This project has a dependency on a pre-release version of CSLA 4.

VSL01

Demo showing some concepts and implementation around MVVM.

VSL02

Demo showing some concepts and implementation around MVVM.

Monday, April 19, 2010 8:59:44 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

Here’s a link to an article I wrote on using code-gen vs building a more dynamic runtime:

http://msdn.microsoft.com/en-us/library/ff621668.aspx

Update: There doesn't appear to be a code download on the Microsoft site. Click here to download the code.

Sunday, April 18, 2010 11:30:24 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [2]  | 
 Friday, February 26, 2010

Continuing on my quest to use the Visual Studio 2010 XAML designer, MVVM and absolutely no code behind, I ran into the common problem of setting focus to a control as a form loads.

This is easily accomplished using code-behind:

firstControl.Focus();

But of course that requires code-behind, which I believe should be unnecessary.

It can also be accomplished by creating an attached property or (with the Blend 3 SDK) trigger action or behavior. Neither of these are great with the VS10 designer though, because the designer has no way to apply attached properties and doesn’t know about the Blend 3 SDK concepts.

So while those solutions are fine, they require manual typing of XAML, which I believe should be unnecessary (as unrealistic as that view might be…).

My solution is to create a FrameworkElement called SetFocus. This shows up in the Toolbox and so can be dragged directly onto the form using the designer. The SetFocus control has no visual aspect, so it doesn’t interfere with the layout or look of the form. Once SetFocus is on the form, the Properties window can be used to set its TargetProperty property, indicating the property that should get focus when the form is loaded.

image

This requires no code-behind and no manual typing of XAML. It keeps the concept of startup focus completely in the view, which (I think) is a good place for it. So my viewmodel doesn’t know or care about this issue. And the same control works in Silverlight and WPF, which should be the goal for any good XAML control.

Here’s the code:

using System;
using System.Windows;
using System.Windows.Controls;
using System.ComponentModel;

namespace Collective.Controls
{
  /// <summary>
  /// Sets the focus to the TargetControl property as the
  /// form is loaded.
  /// </summary>
  public class SetFocus : FrameworkElement
  {
    /// <summary>
    /// Gets or sets the target UI control.
    /// </summary>
    public static readonly DependencyProperty TargetControlProperty =
      DependencyProperty.Register("TargetControl", typeof(Control),
      typeof(SetFocus), new PropertyMetadata((o, e) =>
      {
        var sf = o as SetFocus;
        if (sf != null && sf.TargetControl != null)
          sf.TargetControl.Focus();
      }));
    /// <summary>
    /// Gets or sets the target UI control.
    /// </summary>
    [Category("Common")]
    public Control TargetControl
    {
      get { return (Control)GetValue(TargetControlProperty); }
      set { SetValue(TargetControlProperty, value); }
    }
  }
}

Friday, February 26, 2010 11:25:09 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [8]  | 
 Friday, February 19, 2010

As noted in a previous post, I’ve been spending some quality time with the new VS10 XAML designer. It is fun, but challenging to figure out how the designer wants everything to work, and to adapt existing CSLA .NET components to work smoothly in the new environment.

Yesterday I spent a substantial amount of time trying to get PropertyStatus, InvokeMethod and Execute to work nicely. These three controls have one thing in common: they all interact directly with the real data object. InvokeMethod and Execute both invoke methods on the data object (usually a viewmodel), and PropertyStatus reads property-specific metadata about a property, such as whether the property has any info/warning/error messages that the user should see.

The VS10 designer uses something called a CollectionViewSource as its primary binding target. When you drag-and-drop a type from the Data Sources window onto your form, the designer creates a CVS resource in the form and uses that as the DataContext for your UI elements. In this regard it is not entirely unlike a data provider control in WPF, though it is certainly not a data provider control.

If you are using a viewmodel (and I am), then your DataContext is actually a hierarchy of object instances.

image

This is made slightly more complex when you realize that the Source property of a CollectionViewSource can only be a list. So really the CVS contains a list of viewmodel objects – but in my case that list has only one item.

InvokeMethod and Execute both need access to the viewmodel – that’s the object containing the methods to be invoked. PropertyStatus actually needs access to the Model (the real business object), because that’s the object where the business properties and associated metadata are actually implemented.

None of this would be that complex, except that the VS10 designer sets the DataContext to the CVS, and then uses currency to make one item in the Source property “current”. But if you, in code, get access to the DataContext for a control you get the CVS. If you get a BindingExpression object for a given binding, the DataItem is the current item in the CVS, which turns out to not be the viewmodel. Instead the DataItem on a binding is an internal type within .NET.

And this is what had me stuck. The CVS has no CurrentItem property, but this internal type does. However (short of reflection), there’s no way to interact with members of an internal type. What to do? Thanks to help from Mark Boulter I now know that this internal type implements the public ICollectionView interface, and that interface does have a CurrentItem property.

Whew!

What this means is that in InvokeMethod and Execute, I can take the associated UI control (like a Button or something) and use it to find the viewmodel:

public static object GetTarget(UIElement ctrl)
{
  object result = null;
  result = ctrl.GetValue(TargetProperty);
  if (result == null)
  {
    var fe = ctrl as FrameworkElement;
    if (fe != null)
      result = fe.DataContext;
  }
  var icv = result as ICollectionView;
  if (icv != null)
    result = icv.CurrentItem;
  return result;
}

This basically takes the DataContext value, sees if it is an ICollectionView, and if so it returns the CurrentItem – which is the real data object, or at least the viewmodel.

PropertyStatus is a little more complex, because it has to trace down to the actual underlying business object, and if so it needs to dereference elements of the property name path. For example, the property name might be Name, or it might be Model.Name. If it is Name, the assumption is that CurrentItem is the actual data object. If it is something like Model.Name, the assumption is that PropertyStatus needs to use the Name property on the object referenced by the Model property. The code actually goes n levels like this, allowing for access deep into hierarchical object graphs.

private object GetRealSource(object source, string bindingPath)
{
  var icv = source as ICollectionView;
  if (icv != null)
    source = icv.CurrentItem;
  if (source != null && bindingPath.IndexOf('.') > 0)
  {
    var firstProperty = bindingPath.Substring(0, bindingPath.IndexOf('.'));
    var p = MethodCaller.GetProperty(source.GetType(), firstProperty);
    return GetRealSource(
      MethodCaller.GetPropertyValue(source, p),
      bindingPath.Substring(bindingPath.IndexOf('.') + 1));
  }
  else
    return source;
}

Again, if the source is an ICollectionView, the code skips right to the CurrentItem property, which is the first “real” object worth using.

I suppose writing controls that interact with the real data object isn’t something people do every day, but if you end up writing such a control hopefully this blog post will help save you some time and frustration.

Friday, February 19, 2010 2:42:23 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Thursday, February 18, 2010

OK, this is cool. Magenic is running a Silverlight/WPF development contest, open to anyone. The primary prizes for first to third place are sizable donations to the Haiti relief effort, with respectable cash prizes for the winning teams.

Even if your visual UI design skills aren’t super-solid (like mine), all teams get an hour of Magenic Studio’s assistance, which might at least jump-start a decent looking visual layout :)

The app must use Silverlight or WPF (versions 3 or 4 are both acceptable), otherwise pretty much anything goes. Well, obviously the judges need to be able to run the app and view the code, but otherwise…

The contest starts on Feb 22 and ends March 22.

So go to the web site, read the rules, send email to get registered and start exercising those mad XAML and .NET skilz!!

Thursday, February 18, 2010 10:07:32 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Tuesday, February 16, 2010

Visual Studio 2010 includes a new XAML designer, with capabilities roughly comparable to the Windows Forms designer we’ve enjoyed all these many years.

This means you can use drag-and-drop design concepts to get controls from the Toolbox onto the design surface, drag them around, see snaplines and use the Properties window to set properties (including data binding). And the Data Sources window works, so you can drag entire objects or specific properties from a data source (like a CSLA .NET business object) onto the design surface to create a UI control with the data binding all set up.

image

I’m very excited about this designer, as I think the lack of a good designer has been the single biggest roadblock to WPF (and now Silverlight) adoption. While some people are OK with manually typing XAML, I think a lot more people have been (im)patiently waiting for tooling so they don’t have to work at that level. I’m in the latter camp, but I’ve been forcing myself to type XAML for a few years now because the results are so much better than Windows Forms that it has been worth the pain.

However, with the designer being out now (stable and fast in the RC) I’ve been spending some quality time with it. And what I’m finding is that I have to unlearn a lot of techniques. Things that work great when you manually type XAML don’t always translate exactly into the designer metaphor and/or workflow.

CollectionViewSource Indirection

For example, when you drag something from the Data Sources window to the design surface the designer creates a CollectionViewSource resource to manage the data object. Suppose the data source is your business object – the CVS now contains your business object. Suppose the data source is your viewmodel object – the CVS now contains your viewmodel object.

It is this last point that is tricky. I have been building my viewmodel objects so they are the resource. Now they are contained inside the resource. There’s a new level of indirection involved.

Oh, and the CVS only contains a list of objects, never a single object. So when I drag my single viewmodel onto the designer it ends up in a list of 1 item in the CVS. And that’s OK, it just means your binding expressions need to take this into account. Instead of setting the DataContext directly to the resource, you must set it to the current item in the resource:

DataContext=”{Binding Source={StaticResource viewModelViewSource}, Path=/}”

image It is the Path=/ part that is new and different. Of course you don’t really type that binding expression – the designer has a dialog where you set up or edit the DataContext and other binding details.

In the screen shot to the left you can see some regions on the form. The top, where the button and checkbox are visible, is bound to the / path. The bottom, where the datagrid is visible, is bound to the Model property – which means the datagrid is bound directly to the business object, and that’s a fine thing since CSLA 4 BusinessListBase objects derive from ObservableCollection<T> and are fully bindable in XAML.

Executing ViewModel Verbs

The other area of challenge I’ve encountered is with triggering viewmodel verbs/commands/actions/methods when a UI event occurs. Remember that Silverlight doesn’t have commanding, and even in WPF commanding is not a complete solution to this problem.

Blend 3 introduced the concept of trigger actions and behaviors, and CSLA .NET 3.8 has an Execute trigger action that executes a method on the viewmodel when an event occurs on a UI control. Prior to that, in version 3.6, there was the InvokeMethod attached property that did the same basic thing.

The problem with both InvokeMethod and the Blend 3 trigger action concept is that there’s no access to these concepts from the VS10 designer. You can use them, but you have to manually type the XAML. My personal goal and hope with the designer is to never type (or even see) XAML.

image So this evening I took the ideas from InvokeMethod and Execute and created a new control I’m calling TriggerAction (see code here). The TriggerAction control is a real control – it shows up in the Toolbox and you can drag it onto the design surface. It is invisible (collapsed), as it really has no UI aspect. But it does have some important properties:

  • TargetControl – use element binding to connect it to the UI control that’ll raise the event
  • TriggerEvent – the name of the event raised by the UI control
  • MethodName – the name of the method/verb/action on the viewmodel (DataContext) object to invoke in response to the trigger event
  • MethodParameter – a bindable parameter value that can optionally be passed to the viewmodel method

In short, TriggerAction does exactly what InvokeMethod and Execute do, but in a way that is friendly to the XAML designer. This means not requiring any manual editing of XAML.

I’m not done yet, but I’m becoming increasingly convinced that the VS10 designer really will allow creation of XAML interfaces using patterns like MVVM and requiring zero code-behind the XAML – without the developer ever having to see (much less edit) XAML directly. Happiness!!

Tuesday, February 16, 2010 8:48:16 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Monday, February 01, 2010

CSLA .NET 3.8.2 is now available for Windows and Silverlight

This is a bug-fix release, and has been in beta for several months.

There is only one real functional (and breaking) change, which affects only people building WPF or Silverlight applications and using the design-time data support built into the data portal. This feature has been disabled in 3.8.2 because there’s an issue in WPF (and possibly Silverlight) where detecting design time vs runtime in a high volume runtime scenario would cause a Win32 exception in the .NET runtime.

Since Visual Studio 2010 and .NET 4.0 have a different way of handling design time data, this was going to change anyway; but making this change now helps avoid this WPF runtime issue, and so was important.

Monday, February 01, 2010 11:35:17 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Wednesday, January 13, 2010

I’m often asked whether CSLA .NET supports the MVC, MVP, MVVM or other “M” patterns.

The answer is an absolute YES! Of course it does, because CSLA .NET is all about the “M”.

The “M” in all these patterns stands for Model – the business layer that is supposed to encapsulate all your business logic and the data required for that logic to work.

Since its inception 13+ years ago, CSLA has been primarily focused on helping people build a powerful business layer composed of business domain objects. This implies strong separation of concerns where UI issues are (as much as possible) kept out of the business layer, as are data access concerns.

The various “M” patterns also support separation of concerns. Their perspective is from the UI level, as they are all UI patterns. But at the core of each of them is the idea that the “M” should encapsulate all the business logic, business processing and data required to perform that processing.

Whether you want a Controller-View or a Presenter-View or a View-ViewModel to organize your UI code, in every case you need a clearly separate Model against which the UI will work.

CSLA .NET 3.8 specifically added a bunch of features to simplify the use of MVVM in Silverlight and WPF, but that’s just simplification. MVVM worked fine without those enhancements, it is just a little easier now. Of course you still need an MVVM UI framework, because CSLA isn’t about the UI, it is about the Model.

CSLA .NET 3.8.2 includes a CslaModelBinder for ASP.NET MVC. Again, this simplifies one aspect of using ASP.NET MVC for your UI framework, but it isn’t strictly necessary – it just makes life easier. The same rule applies, CSLA isn’t a UI framework and so does as little as possible at the “V” and “C” level because its focus is all about the “M”.

Wednesday, January 13, 2010 12:39:46 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Friday, November 06, 2009

In Visual Studio 2010 and .NET 4.0 Microsoft is amping up the visibility of the “client profile” concept. In fact, when you install the 4.0 client profile on a machine, it doesn’t drag the rest of the framework to that client later – they just get the client profile. And when you create a WPF or Windows Forms project in VS10 you default to targeting the client profile.

That’s all good – great in fact!!

But I’ve fallen in love with the validation attribute concepts in System.ComponentModel.DataAnnotations.dll. These attributes are designed specifically to enable a UI framework author (or a business layer framework author – like me with CSLA .NET) to automatically create a rich user experience based on the attributes decorating business objects.

This concept was first fully realized in Silverlight 3 – a client technology – and is now fully supported in .NET 4.0 full profile. But it is a client side technology, and so should be in the client profile.

I’ve logged this issue on connect, and recommend you vote for this to be resolved:

https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=502807

 

Friday, November 06, 2009 3:41:13 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Wednesday, November 04, 2009

Of course I’m referring to Windows Forms, which is about 8 years old. Even in dog years that’s not old. But in software years it is pretty old I’m afraid…

I’m writing this post because here and in other venues I’ve recently referred to Windows Forms as “legacy”, along with asmx and even possibly Web Forms. This has caused a certain amount of alarm, but I’m not here to apologize or mollify.

Technologies come and go. That’s just life in our industry. I was a DEC VAX guy for many years (I hear Ted Neward laughing now, he loves these stories), but I could see the end coming years before it faded away, so I switched to the woefully immature Windows platform (Windows 3.0 – what a step backward from the VAX!). I know many FoxPro people who transitioned, albeit painfully, to VB or other tools/languages. The same with Clipper/dBase/etc. Most PowerBuilder people transitioned to Java or .NET (though much to my surprise I recently learned that PowerBuilder still actually exists – like you can still buy it!!).

All through my career I’ve been lucky or observant enough to jump ship before any technology came down on my head. I switched to Windows before the VAX collapsed, and switched to .NET before VB6 collapsed, etc. And honestly I can’t think of a case where I didn’t feel like I was stepping back in time to use the “new technology” because it was so immature compared to the old stuff. But every single time it was worth the effort, because I avoided being trapped on a slowly fading platform/technology with my skills becoming less relevant every day.

But what is “legacy”? I once heard a consultant say “legacy is anything you’ve put in production”. Which might be good for a laugh, but isn’t terribly useful in any practical sense.

I think “legacy” refers to a technology or platform that is no longer an area of focus or investment by the creator/maintainer. In our world that mostly means Microsoft, and so the question is where is Microsoft focused, where are they spending their money and what are they enhancing?

The answers are pretty clear:

  • Azure
  • Silverlight
  • ASP.NET MVC
  • WPF (to a lesser degree)
  • ADO.NET EF
  • WCF

These are the areas where the research, development, marketing and general energy are all focused. Ask a Microsoft guy what’s cool or hot and you’ll hear about Azure or Silverlight, maybe ADO.NET EF or ASP.NET MVC and possibly WPF or WCF. But you won’t hear Windows Forms, Web Forms, asmx web services, Enterprise Services, Remoting, LINQ to SQL, DataSet/TableAdapter/DataTable or numerous other technologies.

Some of those other technologies aren’t legacy – they aren’t going away, they just aren’t sexy. Raw ADO.NET, for example. Nobody talks about that, but ADO.NET EF can’t exist without it, so it is safe. But in theory ADO.NET EF competes with the DataSet (poorly, but still) and so the DataSet is a strong candidate for the “legacy” label.

Silverlight and WPF both compete with Windows Forms. Poor Windows Forms is getting no love, no meaningful enhancements or new features. It is just there. At the same time, Silverlight gets a new release in less than 12 month cycles, and WPF gets all sorts of amazingly cool new features for Windows 7. You tell me whether Windows Forms is legacy. But whatever you decide, I’m surely spending zero cycles of my time on it.

asmx is obvious legacy too. Has been ever since WCF showed up, though WCF’s configuration issues have been a plague on its existence. I rather suspect .NET 4.0 will address those shortcomings though, making WCF as easy to use as asmx and driving the final nail in the asmx coffin.

Web Forms isn’t so clear to me. All the buzz is on ASP.NET MVC. That’s the technology all the cool kids are using, and it really is some nice technology – I like it as much as I’ll probably ever like a web technology. But if you look at .NET 4.0, Microsoft has done some really nice things in Web Forms. So while it isn’t getting the hype of MVC, it is still getting some very real love from the Microsoft development group that owns the technology. So I don’t think Web Forms is legacy now or in .NET 4.0, but beyond that it is hard to say. I strongly suspect the fate of Web Forms lies mostly in its user base and whether they fight for it, whether they make Microsoft believe it continues to be worth serious investment and improvement into the .NET 5.0 timeframe.

For my part, I can tell you that it is amazingly (impossibly?) time-consuming to be an expert on 7-9 different interface technologies (UI, service, workflow, etc). Sure CSLA .NET supports all of them, but there are increasing tensions between the stagnant technologies (most notably Windows Forms) and the vibrant technologies like Silverlight and WPF. It is no longer possible, for example, to create a collection object that works with all the interface technologies – you just can’t do it. And the time needed to deeply understand the different binding models and subtle differences grows with each release of .NET.

CSLA .NET 4.0 will absolutely still support all the interface technologies. But it would be foolish to cut off the future to protect the past – that way lies doom. So in CSLA .NET 4.0 you should expect to see support for Windows Forms still there, but probably moved into another namespace (Csla.Windows or something), while the main Csla namespace provides support for modern interface technologies like WPF, ASP.NET MVC, Silverlight, etc.

I am absolutely committed to providing a window of time where Windows Forms users can migrate their apps to WPF or Silverlight while still enjoying the value of CSLA .NET. And I really hope to make that reasonably smooth – ideally you’ll just have to change your base class types for your business objects when you switch the UI for the object from Windows Forms to XAML – though I suspect other minor tweaks may be necessary as well in some edge cases.

But let’s face it, at some point CSLA .NET does have to drop legacy technologies. I’m just one guy, and even with Magenic being such a great patron it isn’t realistic to support every technology ever invented for .NET :)  I don’t think the time to drop Windows Forms is in 4.0, because there are way too many people who need to migrate to WPF over the next 2-3 years.

On the other hand, if you and your organization aren’t developing a strategy to move off Windows Forms in the next few years I suspect you’ll eventually wake up one day and realize you are in a bad spot. One of those spots where you can’t hire anyone because no one else has done your technology for years, and nobody really remembers how it works (or at least won’t admit they do unless you offer them huge sums of money).

I don’t see this as bad. People who want stability shouldn’t be in computing. They should be in something like accounts receivable or accounts payable – parts of business that haven’t changed substantially for decades, or perhaps centuries.

Wednesday, November 04, 2009 9:20:16 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Sunday, October 25, 2009

I’ve blogged about MVVM several times over the past few months. If you watch my posts you’ll see that I started out pretty skeptical of the pattern, and then worked through it trying to find the shiny silver lining that was promised.

One of the biggest challenges with patterns is that people expect them to be a recipe, when in reality they are just a vague formalization of a concept. Just look at MVC, an incredibly mature pattern, and all the radically different ways it gets implemented (for better or often worse) in applications. While MVVM isn’t nearly as mature as MVC, it turns out that it really is a good concept – when “applied correctly”.

In my view a pattern should only be used if its positive consequences outweigh its negative consequences. Many patterns, oddly enough, require extra code and/or configuration over what you’d normally write – which is a negative consequence. And in some interpretations of MVVM this is very much the case – which was the primary reason for my initial skepticism.

On the other hand, with some thought, foresight and work it is often possible to mitigate some of the more negative consequences of many of the more popular patterns. This turns out to be absolutely true for MVVM.

To me, the real sweet spot for a pattern is if it can provide its positive consequences with little or no negative impact at all.

My time with CSLA .NET 3.8 has been divided into just a few areas:

  • Bug fixes (minor)
  • DataAnnotations (minor – but really nice)
  • Silverlight 3 element binding (major – also really nice)
  • MVVM support (major – and very cool)

In the end, I think I’ve got something that enables the use of the MVVM design pattern, probably in several variations, to work swimmingly with CSLA .NET. I’ll go so far as to say that I think this implementation of MVVM makes developing Silverlight and WPF apps easier than out-of-the-box coding (drag-and-drop, handling UI events, using data provider controls). And by easier I mean no more code, often less code, and easier to read/test/maintain code. So the pattern is purely helpful, with no negative consequences of note. Exactly what you’d hope for.

What does this look like?

CSLA .NET MVVM Support

First, you must realize that CSLA .NET helps you create what’s called a rich model as opposed to various other technologies (like Add Service Reference) that help you create an anemic model. Using MVVM with an anemic model is useful, but can require a lot of work, because your viewmodel object needs to compensate for all the stuff the model doesn’t do. But with a rich model, the viewmodel requires far less work because the model is already first-class citizen.

To this end, CSLA .NET provides some helper types that you may optionally use to enable a rich model MVVM implementation. At the same time, I fully recognize that many (most?) people will find/build and use an MVVM UI framework, so the CSLA .NET helper types can be used individually, all together or not at all – as you choose.

Two parts of MVVM already (mostly) exist if you are using CSLA .NET and Silverlight or WPF. CSLA .NET helps you create business domain objects that are your Model, and XAML helps you create your View (with a little help). So in my mind those are essentially a given. What’s left is the need to create the ViewModel.

Notice that I said XAML gives you the view – with a little help. This is because WPF commanding isn’t quite enough to do MVVM, and Silverlight doesn’t even have commanding. So the “little help” is something that handles arbitrary UI events and transforms them into arbitrary method calls on the DataContext (presumably your viewmodel). I would expect any decent MVVM UI framework to solve this most basic problem, and of course they do. Sadly there’s no standard solution, so each UI framework does their own thing.

View Event Handling

While not a UI framework, CSLA .NET does provide a basic solution to this one critical problem with using XAML to create a view. In fact it provides two solutions: InvokeMethod and Execute.

InvokeMethod is an attached property that understands how to handle an arbitrary UI event and to call an arbitrary method on the DataContext when that event is raised. As an attached property, you can attach it to any UIElement (FrameworkElement in Silverlight) to handle any event to call any method on the DataContext. Here’s a simple example:

<Button Content=”Save”
            csla:InvokeMethod.TriggerEvent=”Click”
            csla:InvokeMethod.MethodName=”SaveData” />

Execute is similar, but relies on the Blend 3 System.Windows.Interactivity event trigger concept to detect that the event was raised:

<Button Content="Save">
  <i:Interaction.Triggers>
    <i:EventTrigger EventName="Click">
      <csla:Execute MethodName="SaveData" />
    </i:EventTrigger>
  </i:Interaction.Triggers>
</Button>

The advantage of using InvokeMethod is that it has several options around data binding that simply aren’t available to a trigger action like Execute. Most notably, InvokeMethod has a MethodParameter property that can be bound using a binding expression – so it can pull values from other UI controls, resources, the DataContext, etc. There’s no way to do this with a trigger action like Execute.

The advantage of using Execute is that trigger actions are something the Blend 3 designer understands. So InvokeMethod pretty much requires typing XAML, while Execute integrates more naturally into the Blend design experience.

In either case, the method on your viewmodel looks like this:

public void SaveData()
{
}

Or this:

public void SaveData(object sender, ExecuteEventArgs e)
{
}

Either one is fine, as InvokeMethod and Execute will work with either method signature. If you use the second option, the args parameter contains information about the control the raises the event, the event’s args and an optional MethodParameter value.

Creating a ViewModel

When using a rich model, I believe that a good viewmodel object will expose the model as a property, so the View can bind directly against the Model and still have access to the viewmodel. This way the viewmodel can extend and enhance the model without any extra effort. This works particularly well if the model already understands data binding – which is one of the primary features of CSLA .NET.

CSLA .NET includes ViewModelBase<T> and ViewModel<T>, both of which are base classes designed to make it easy to build a viewmodel for a CSLA .NET business object.

ViewModelBase has a public Model property, a handful of other useful public properties (like CanSave), and a whole bunch of protected methods. Again, my assumption is that many people will use some MVVM UI framework, and that framework will have its own constraints on how public methods must be implemented for their particular “commanding equivalent” functionality. The ViewModelBase class allows you to create public methods matching your UI framework’s requirements, but you can usually just delegate those calls to existing protected methods that do most of the work. These methods include:

DoRefresh

(WPF only) Synchronously invokes a static factory method to create/fetch the Model.

BeginRefresh

Asynchronously invokes a static factory method to create/fetch the Model.

DoSave

(WPF only) Synchronously saves the Model (if it is a root object).

BeginSave

Asynchronously saves the Model (if it is a root object).

AddItem

Adds an item to the collection (if the Model is a BusinessListBase).

Remove

Removes an item from the collection (if the Model is a BusinessListBase).

Delete

Marks the Model for deletion (if the Model is a root BusinessBase).

Cancel

Cancels any changes that have been made to the Model (if ManageObjectLifetime is true).

ViewModel is a subclass of ViewModelBase that implements public methods for use by InvokeMethod and/or Execute. If you use InvokeMethod/Execute, then you’ll want to create your viewmodel objects by subclassing ViewModel:

public class CustomerViewModel : ViewModel<Customer>
{
  public CustomerViewModel()
  {
    BeginRefresh(“NewCustomer”);
  }
}

In many cases the constructor is all you’ll need to write, since the ViewModel<T> base class already implements the methods necessary to build a standard data entry form.

Again, if you are using an MVVM UI framework, you’ll probably want to create your own base class, somewhat like ViewModel<T>, by subclassing ViewModelBase<T> and implementing your public methods to match the requirements of the UI framework. You can use the code in ViewModel<T> as an example of how to do this.

I should also point out that the Model property is bindable. This means you can create “child viewmodel” objects that get their Model value by being bound to the property of some “parent viewmodel” or parent model. For example, you might have a form for working with SalesOrder objects, so your top level viewmodel exposes a SalesOrder object through its Model property. The following would be the XAML to set up the viewmodel for the form:

<UserControl.Resources>
  <this:SalesOrderViewModel x:Key="ViewModel" />
</UserControl.Resources>
<Grid Name=”LayoutRoot” DataContext=”{Binding Source={StaticResource ViewModel}}”>

Now you could just bind the detail region of the form (where you show the line items) to the LineItems property of the business object, and that works fine.

But suppose you want to bind a button or hyperlink control to an AddItem() method so the user can add items to the LineItems collection. How do you do that without writing code? The answer is that you set up a viewmodel (probably LineItemsViewModel) for that child region of the form, and you have the Model property of LineItemsViewModel bound to the LineItems property of the SalesOrder business object. In the child region you’d do something like this:

<Grid Name=”ChildRegionContainer”>
  <Grid.Resources>
    <this:LineItemsViewModel x:Key=”LineItemsViewModel”
                                           Model=”{Binding Path=Model.LineItems}”/>
  </Grid.Resources>
  <Grid Name=”ChildRegion” DataContext=”{Binding Source={StaticResource LineItemsViewModel}}”>

The advantage of this is that any controls inside the ChildRegion grid can invoke methods on LineItemsViewModel – such as AddItem() or Remove() to add and remove items from the collection – all with no coding on your part.

Creating the Model

This is the part where I just smile. Because you already have the model if you used CSLA .NET and good object-oriented design to build your business domain objects. The same business objects you may already be using for Windows Forms or Web Forms will almost certainly just work in your WPF or Silverlight application (assuming you are using CSLA .NET 3.5 or higher – and can upgrade to CSLA .NET 3.8).

The primary goal of CSLA .NET, first and foremost, is to enable you to create a business layer that encapsulates your business, validation and authorization logic into a set of business domain objects. By doing so, you end up with a formal business layer on top of which you can build Silverlight, WPF, ASP.NET MVC, Web Forms, Windows Forms, asmx service or WCF service interfaces.

So the whole point of having this business layer is that when something like XAML comes along all you need to worry about is how to rebuild the UI, possibly using MVVM. But you don’t need to worry about rebuilding the business layer, or the data access layer or the database.

I’m pretty happy with the way CSLA .NET 3.8 enables the MVVM design pattern in Silverlight and WPF. As I said to start with, you’d hope that a pattern gives you positive consequences with little or no downside. With the support of InvokeMethod, Execute, ViewModelBase and ViewModel I think CSLA .NET makes MVVM meet that goal. And in fact, I think it allows you to build a UI with less code than many, seemingly simpler, alternatives.

Sunday, October 25, 2009 10:23:04 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Monday, October 05, 2009

One of the new features in CSLA .NET 3.8 is the ability to use the data annotation attributes from System.ComponentModel.DataAnnotations.

The DataAnnotations namespace was added in .NET 3.5 SP1, and includes a ValidationAttribute class that acts as the base class for validation attributes. An example of a validation attribute is Required, which is used to indicate that a property is a required value.

DataAnnotations are available in both .NET and Silverlight, though it turns out that their implementations aren’t quite the same. Still, their usage is the same, in that you decorate properties with data annotation attributes.

The idea behind DataAnnotations is that they are UI independent. If you put a Required attribute on a property, and then you build a UI using a technology that understands these ValidationAttribute subclasses, the UI will honor the attribute. The Silverlight DataForm is one example of a UI technology that does understand these attributes, and I suspect we’ll see many more UI technologies start to leverage them.

What’s interesting about this, is that the attribute object itself contains the validation rule logic. So the UI doesn’t actually implement the Required rule logic – it just asks the attribute object to do the evaluation. This is where things aren’t the same on .NET and Silverlight. On .NET ValidationAttribute subclasses override IsValid(), returning true if the rule is satisfied, false if not. On Silverlight ValidationAttribute subclasses override GetValidationResult() which returns null if the rule is satisfied, and a result object if the rule is broken. Either way the basic concept is the same, but the implementation code is different.

I wanted to support these attributes in CSLA .NET (for Windows and Silverlight). This is really a two-part process.

First, I needed to have a way to detect the attribute on a property, and attach a CSLA validation rule to that property so CSLA knows to execute the attribute’s rule when appropriate. CSLA .NET already has a business/validation rule subsystem that knows how to execute rules – I just needed to auto-add rules for data annotation attributes.

Second, I needed a way to execute any ValidationAttribute subclass, since that’s how one of these rules is evaluated. Again, CSLA .NET already has a validation rule subsystem that says validation rules are methods. So I just needed to create a CSLA-style rule method that knows how to invoke a ValidationAttribute to actually evaluate the rule’s condition.

I added a ValidationRules.AddDataAnnotations() method that you can call in your AddBusinessRules() override. This method reflects against your properties, detects any ValidationAttribute subclasses on any of your properties and adds a CSLA-style rule to link that property to the rule attribute. I also changed BusinessBase.AddBusinessRules() (this is the base method) so AddDataAnnotations() is called if you don’t override AddBusinessRules() – effectively making the use of data annotation attributes a default behavior.

Then I created a Csla.Validation.CommonRules.DataAnnotation() rule method. This is the rule method that is automatically associated with properties by AddDataAnnotations(). The DataAnnotation() rule method is pretty simple – it just executes the attribute object’s IsValid() or GetValidationResults() methods (depending on whether the code is running on .NET or Silverlight).

The end result is that when using CSLA .NET 3.8 you can apply data annotation attributes to your business class properties, and (assuming AddDataAnnotations() is called) they’ll be automatically linked into the normal CSLA .NET validation subsystem and executed like any other CSLA .NET business or validation rules.

[Serializable]
public class Data : BusinessBase<Data>
{
  private static PropertyInfo<int> IdProperty = 
    RegisterProperty<int>(c => c.Id);
  [Range(0, 10, ErrorMessage = "Id must be between 0 and 10")]
  public int Id
  {
    get { return GetProperty(IdProperty); }
    set { SetProperty(IdProperty, value); }
  }

  private static PropertyInfo<string> NameProperty =
    RegisterProperty<string>(c => c.Name);
  [Required(ErrorMessage = "Name is required")]
  public string Name
  {
    get { return GetProperty(NameProperty); }
    set { SetProperty(NameProperty, value); }
  }
}

Notice that this class doesn’t override AddBusinessRules(), so the base implementation is used, and the base implementation calls ValidationRules.AddDataAnnotations().

When AddDataAnnotations() is called, it detects the Range and Required attributes on the properties, and those attributes are automatically linked into the normal CSLA .NET business rule subsystem. This means the rules are automatically checked when a new instance of the object is created, and any time the property values are set – exactly the behavior you’d get with regular CSLA .NET rule methods.

But what’s nice about this is that these attributes are also honored by some UI technologies (like DataForm). This means that you automatically get the UI behaviors (if any) and yet you know that the rules will be run in the business layer regardless of whether the UI honors the attributes or not.

So this object will work nicely in the Silverlight DataForm, and will have the same business behavior in Windows Forms, behind a WCF service or anywhere else the object is used – even if the UI technology doesn’t honor the attributes.

You can also use this approach to create your own validation attributes by subclassing the ValidationAttribute base class in System.ComponentModel.DataAnnotations.

The only limitation I’ve found is that these attribute-based rules can only operate on a single property value. You can’t use this technique to do multi-property rules, or rules that operate on child collections or across other objects. You’ll need to use the normal CSLA .NET business/validation rule method approach to implement anything beyond simple single-property rules.

Monday, October 05, 2009 11:06:45 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Sunday, September 13, 2009

I have put two new pre-releases online, and they are available on the download pages:

CSLA .NET 3.7.1 Beta 3 is near-stable. In fact it would have been a release, except for one change I just added that I feel needs a beta cycle.

The 3.7.1 release is primarily bug fixes for a few issues in 3.7.0.

The only new feature is some support for creating custom FieldInfo<T> subclasses, which requires creating PropertyInfo<T> subclasses. If you are doing this, the new 3.7.1 changes in Beta 3 may make your life much easier.

CSLA .NET 3.8.0 Alpha 2 shows my continuing work and thoughts around the new Silverlight 3 binding capabilties and MVVM support.

All the new changes in Alpha 2 are on the Silverlight side, and impact:

  • CslaDataProvider - where the ObjectInstance property is now bindable, so you can "chain" data provider controls in parent-child relationships. This means you can have a child region on a form that is bound to a CslaDataProvider that got its data from the child property of a parent CslaDataProvider.
  • ViewModelBase - a base class that provides protected members you can use to more easily create a ViewModel class for your CSLA .NET business objects. The approach taken is one that exposes the Model (your business object) as a Model property of the ViewModel object; this is the flavor of MVVM that works best with CSLA .NET.
    This does include a protected method to create/fetch the Model as requested in one of the recent MVVM threads on the CSLA .NET forum.
  • ViewModel - a subclass of ViewModelBase that exposes public members for use with InvokeMethod or Execute (see below) so the methods can be invoked directly by XAML. Warning: I may or may not keep this class, depending on your feedback, as I don't know if it is the best plan overall.
  • InvokeMethod - which has breaking changes, but now automatically binds to the current DataContext and does a whole bunch of other nice work on your behalf to invoke methods on a data provider or ViewModel.
  • Execute - a new event trigger action using the new Blend 3 SDK feature of event triggers. The Execute action is similar to InvokeMethod, but works within the new event trigger infrastructure.
  • PropertyStatus - which has breaking changes, and is now bindable using element binding, and binds to the business object property instead of using a string literal for the property name. It also now exposes properties so a UI control can bind to PropertyStatus, instead of having PropertyStatus directly alter the UI control - this offers major new flexibility in UI design.

If you are using SL3 and/or are at all interested in MVVM, please take a look at what I'm doing in 3.8 and provide feedback.

As always, my intent is not for CSLA .NET to become a UI framework. At the same time, I feel the need to fill in at least the most glaring holes in the UI layer to enable use of CSLA .NET - and this means providing a basic way for XAML to invoke ViewModel methods, and for validation/authorization rules to be expressed in a rich manner in the UI.

It should be the case that any MVVM UI framework will be compatible with viewmodel objects you create by subclassing ViewModelBase. If that's not true, I'd like to hear about the issues you run into. Since ViewModelBase exposes nearly all protected members (except for Model, IsBusy and Error, which are public), I expect that it will provide an incredibly flexible start point for creating viewmodel objects.

The ViewModel base class is an example of how ViewModelBase can be subclasses to create a base that works with a specific UI implementation - specifically InvokeMethod and/or Execute.

Assuming generally positive feedback on the changes I've made on the Silverlight side, I'll port the appropriate changes to the WPF side, and then release 3.8.

Sunday, September 13, 2009 11:22:15 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Friday, July 31, 2009

The current contender for the pattern to displace IoC as “the trendy pattern” is MVVM: Model-View-ViewModel.

MVVM, often called the ViewModel pattern, has its origins in Silverlight, and to a lesser degree WPF has murky origins (maybe Expression Blend, Smalltalk or from aliens in the 8th dimension). It applies well to Silverlight and WPF, because those environments use XAML to describe the actual user presentation, and there’s a very valid desire to avoid having any code-behind a XAML page. A traditional MVC or MVP model isn’t sufficient to accomplish that goal (at least not efficiently), because it is often necessary to have some “glue code” between the View and the Model, even when using data binding.

The challenge is that some Models aren’t shaped correctly to support the View, so something needs to reshape them. And ideally there’d be some way (WPF commanding or similar) to “data bind” button click events, and other events, to some code other than code-behind. The idea being that when a user selects an item in a ListBox, the code that runs in response isn’t in the code-behind.

The idea behind ViewModel is to create a XAML-friendly object that sits between the View and the Model, so there’s a place for what would have been code-behind to go into a testable object. The ViewModel becomes the container for the code-behind, but it isn’t code-behind. Clearly the ViewModel object is part of the UI layer, so the architecture is something like this.

image

It turns out that there are various ways of thinking about the role of a ViewModel. I think there are two broad approaches worth considering.

ViewModel as Sole Data Source

You can set up the ViewModel to be the sole data source for the View. In this case the ViewModel exposes all the properties and methods necessary to make the View function. This can work well with an anemic Model, where the Model is composed of a bunch of dumb data container objects (think DataTable, DTO and most entity objects).

With an anemic data-centric Model it is common to reshape the Model to fit the needs of the View. And since the Model is anemic, something needs to apply any business, validation and authorization rules and it surely won’t be the Model itself.

Creating this type of ViewModel is non-trivial, because the ViewModel must use containment and delegation (a concept familiar to VB6 developers) to literally wrap, reshape and alter/enhance the behavior of the underlying Model.

image

Every Model property must be reimplemented in the ViewModel, or the View won’t have access to that property. The ViewModel must implement INotifyPropertyChanged, and very possibly the other data binding interfaces (IDataErrorInfo, IEditableObject, etc).

In short, the ViewModel will almost certainly become quite large and complex to overcome the fact that the Model is anemic.

What’s really sad about this approach, is that the end result will almost certainly require more code than if you’d just used code-behind. Arguably the result is more testable, but even that is debatable, since the ViewModel now implements all sorts of data binding goo and you’ll need to test that as well.

ViewModel as Action Repository

Another way to think about a ViewModel is to have it be a repository for actions/commands/verbs. Don’t have it reimplement all the properties from the Model, just have it augment the Model.

This works well if you already have a rich Model, such as one created using CSLA .NET. If the Model is composed of objects that already fully support data binding and have business, validation and authorization rules, it seems silly to reimplement large chunks of that functionality in a ViewModel.

Instead, have the ViewModel expose the Model as a property, alongside any additional methods or properties exposed purely by the ViewModel itself.

image

Again, this presupposes the Model is powerful enough to support direct data binding to the View, which is the case with CSLA .NET business objects, but may not be the case with simpler DTO or entity objects (which probably don’t implement IEditableObject, etc).

The value to this approach is that the ViewModel is much simpler and doesn’t replicate large amounts of code that was already written in the Model. Instead, the ViewModel augments the existing Model functionality by implementing methods to handle View requirements that aren’t handled by the Model.

For example, the Model may be a list of objects that can be bound to a ListBox control in the View. When the user double-clicks an item in the ListBox it might be necessary for the UI to navigate to another form. Clearly that’s not a business layer issue, so the Model knows nothing about navigation between forms. Typically this would be handled by a MouseDoubleClick event handler in code-behind the XAML, but we want no code-behind, so that option is off limits.

Since neither the View nor the Model can handle this double-click scenario, it is clearly in the purview of the ViewModel. Assuming some way of routing the MouseDoubleClick event from the XAML to a method on the ViewModel, the ViewModel can simply implement the method that responds to the user’s action.

This is nice, because the View remains pure XAML, and the Model remains pure business. The presentation layer concept of navigation is handled by an object (the ViewModel) who’s sole job is to deal with such presentation layer issues.

Routing XAML Events to a ViewModel

Regardless of which kind of ViewModel you build, there’s a core assumption that your XAML can somehow invoke arbitrary methods on the ViewModel in response to arbitrary actions by the user (basically in response to arbitrary events from XAML controls). WPF commanding gets you part way there, but it can’t handle arbitrary events from any XAML control, and so it isn’t a complete answer. And Silverlight has no commanding, so there’s no answer there.

When we built CSLA .NET for Silverlight, we created something called InvokeMethod, which is somewhat like WPF commanding, but more flexible. In the upcoming CSLA .NET 3.7.1 release I’m enhancing InvokeMethod to be more flexible, and porting it to WPF as well. My goal is for InvokeMethod to be able to handle common events from a ListBox, Button and other common XAML controls to invoke methods on a target object in response. For the purposes of this blog post, the target object would be a ViewModel.

The ListBox control is interesting to work with, because events like SelectionChanged or MouseDoubleClick occur on the ListBox control itself, not inside the data template. There’s no clear or obvious way for the XAML code to pass the selected item(s) as a parameter to the ViewModel, so what you really need to do is pass a reference to the ListBox control itself so the ViewModel can pull required information from the control in response to the event. In my current code, the solution looks like this:

<ListBox ItemsSource="{Binding Path=Model}"
         ItemTemplate="{StaticResource DataList}"
         csla:InvokeMethod.TriggerEvent="SelectionChanged"
         csla:InvokeMethod.Resource="{StaticResource ListModel}"
         csla:InvokeMethod.MethodName="ShowItem"/>

Notice that the ItemsSource is a property named Model. This is because the overall DataContext is my ViewModel object, and it has a Model property that exposes the actual CSLA .NET business object model. In fact, I have a CslaViewModel<T> base class that exposes that property, along with a set of actions (Save, Cancel, AddNew, Remove, Delete) supported by nearly all CSLA .NET objects.

For the InvokeMethod behaviors, the ListModel resource is the ViewModel object, and it has a method called ShowItem(), which is invoked when the ListBox control raises a SelectionChanged event:

public void ShowItem(object sender, object parameterValue)
{
  var lb = (System.Windows.Controls.ListBox)sender;
  SelectedData = (Data)lb.SelectedItem;
}

The ShowItem() method gets the selected item from the ListBox control and exposes it via a SelectedData property. I have a detail area of my form that is databound to SelectedData, so when the user clicks an item in the ListBox, the details of that item appear in that area of the form. But the ShowItem() method could navigate to a different form, or bring up a dialog, or do whatever is appropriate for the user experience.

The point is that the SelectionChanged, or other event, from a XAML control is used to invoke an arbitrary method on the ViewModel object, thus eliminating the need for code-behind the XAML.

Why this isn’t Ideal

My problem with this implementation is that the View and ViewModel are terribly tightly coupled. The ShowItem() implementation only works if the XAML control is a ListBox. It feels like all I’ve done here is moved code-behind into another file, which is not terribly satisfying.

What I really want is for the XAML to pick out the selected item – something like this pseudocode:

<ListBox ItemsSource="{Binding Path=Model}"
         ItemTemplate="{StaticResource DataList}"
         csla:InvokeMethod.TriggerEvent="SelectionChanged"
         csla:InvokeMethod.Resource="{StaticResource ListModel}"
         csla:InvokeMethod.MethodName="ShowItem"
         csla:InvokeMethod.MethodParameter="{Element.SelectedItem}"/>

Where “Element” refers to the current XAML control, and “SelectedItem” refers to a property on that control.

Then the ShowItem() code could be like this:

public void ShowItem(object parameterValue)
{
  SelectedData = (Data)parameterValue;
}

Which would be much better, since the ViewModel is now unaware of the XAML control that triggered this method, so there’s much looser coupling.

There’s no direct concept for what I’m suggesting built into XAML, so I can’t quite do what I’m showing above. The “{}” syntax is reserved by XAML for data binding. But I’m hopeful that I can make InvokeMethod do something similar by having a special syntax for the MethodParameter value, using characters that aren’t reserved by XAML data binding. Perhaps:

csla:InvokeMethod.MethodParameter=”[[Element.SelectedItem]]”

Or maybe more elegant would be a different property:

csla:InvokeMethod.ElementParameter=”SelectedItem”

Anyway, I think this is an important thing to solve, otherwise the ViewModel is just a more complicated form of code-behind, which seems counter-productive.

Friday, July 31, 2009 9:44:09 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Wednesday, May 27, 2009

Since WPF came out there’s been one quirk, one “optimization” in data binding that has been a serious pain.

Interestingly enough the same quirk is in Windows Forms, but the WPF team tells me that the reason it is also in WPF is entirely independent from how and why it is in Windows Forms.

The “optimization” is that when a user changes a value in the UI, say in a TextBox, that value is then put into the underlying source object’s property (whatever property is bound to the Text property of the TextBox). If the source object changes the value in the setter the change will never appear in the UI. Even if the setter raises PropertyChanged, WPF ignores it and leaves the original (bad) value in the UI.

To overcome this, you’ve had to put a ValueConverter on every binding expression in WPF. In CSLA .NET I created an IdentityConverter, which is a value converter that does nothing, so you can safely attach a converter to a binding when you really didn’t want a converter there at all, but you were forced into it to overcome this WPF data binding quirk.

WPF 4.0 fixes the issue. Karl Shifflett describes the change very nicely in this blog post.

This should mean that I can remove the (rather silly) IdentityConverter class from CSLA .NET 4.0, and that makes me happy.

Wednesday, May 27, 2009 9:28:10 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Wednesday, March 11, 2009

I have been working extensively with both WPF and Silverlight over the past many months. Not too long ago, my workstation started having trouble – specifically Visual Studio 2008 was crashing when trying to open XAML files. Not just crashing either; Visual Studio was disappearing in the blink of an eye.

This started happening every now and then, and became more frequent until it was happening multiple times a day.

After working with some Microsoft people to try and trace down the problem (which we never really did – as it is hard to attach a debugger or other diagnostic tool to VS after it disappears), they suggested I try this patch:

https://connect.microsoft.com/VisualStudio/Downloads/DownloadDetails.aspx?DownloadID=16827&wa=wsignin1.0

(the *.msu are for Vista and Server 2008, and *.exe are for XP and Server 2003, and the x86 patch should be used for 64 bit machines too

Update: For x64 users, you should install the x64 patch, and this will update the 32 bit CLR as part of the installation)

This patch solved my problem. Just like that.

Apparently this patch solves a wider set of problems related to stability when editing or working with XAML files in Visual Studio, and is a generally good thing to apply for developers working with WPF and Silverlight.

Wednesday, March 11, 2009 6:01:23 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Wednesday, January 28, 2009

This is one tip that any WPF or Silverlight developer can’t be without. Talk about instant gratification!

http://weblogs.asp.net/fmarguerie/archive/2009/01/29/life-changer-xaml-tip-for-visual-studio.aspx

I wish I’d known about this months ago.

Wednesday, January 28, 2009 10:59:24 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Friday, October 31, 2008

PDC 2008 was a lot of fun - a big show, with lots of announcements, lots of sessions and some thought-provoking content. I thought I'd through out a few observations. Not really conclusions, as those take time and reflection, so just some observations.

Windows Azure, the operating system for the cloud, is intriguing. For a first run at this, the technology seems surprisingly complete and contains a pretty reasonable set of features. I can easily see how web sites, XML services and both data-centric and compute-centric processing could be built for this platform. For that matter, it looks like it would be perhaps a week's work to get my web site ported over to run completely in Azure.

The real question is whether that would even make sense, and that comes down to the value proposition. One big component of value is price. Like anyone else, I pay a certain amount to run my web site. Electricity, bandwidth, support time, hardware costs, software costs, etc. I've never really sorted out an exact cost, but it isn't real high on a per-month basis. And I could host on any number of .NET-friendly hosting services that have been around for years, and some of them are pretty inexpensive. So the question becomes whether Azure will be priced in such a way that it is attractive to me. If so, I'm excited about Azure!! If not, then I really don't care about Azure.

I suspect most attendees went through a similar thought process. If Microsoft prices Azure for "the enterprise" then 90% of the developers in the world simply don't care about Azure. But if Microsoft prices Azure for small to mid-size businesses, and for the very small players (like me) then 90% of the developers in the world should (I think) really be looking at this technology

Windows 7 looks good to me. After the Tuesday keynote I was ready to install it now. As time goes by the urgency has faded a bit - Vista has stabilized nicely over the past 6-8 months and I really like it now. Windows 7 has some nice-sounding new features though. Probably the single biggest one is reduced system resource requirements. If Microsoft can deliver on that part of the promise I'll be totally thrilled. Though I really do want multi-monitor RDP and the ability to manage, mount (and even boot from) vhd files directly from the host OS.

In talking to friends of mine that work at Microsoft, my level of confidence in W7 is quite high. A couple of them have been running it for some time now, and while it is clearly pre-beta, they have found it to be a very satisfying experience. When I get back from all my travels I do think I'll have to buy a spare HD for my laptop and give it a try myself.

The Oslo modeling tools are also interesting, though they are more future-looking. Realistically this idea of model-driven development will require a major shift in how our industry thinks about and approaches custom software development. Such a massive shift will take many years to occur, regardless of whether the technology is there to enable it. It is admirable that Microsoft is taking such a gamble - building a set of tools and technologies for something that might become acceptable to developers in the murky future. Their gamble will pay off if we collectively decide that the world of 3GL development really is at an end and that we need to move to higher levels of abstraction. Of course we could decide to stick with what has (and hasn't) worked for 30+ years, in which case modeling tools will go the way of CASE.

But even if some of the really forward-looking modeling ideas never become palatable, many of the things Microsoft is doing to support modeling are immediately useful. Enhancements to Windows Workflow are a prime example, as is the M language. I've hard a hard time getting excited about WF, because it has felt like a graphical way to do FORTRAN. But some of the enhancements to WF directly address my primary concerns, and I can see myself getting much more interested in WF in the relatively near future. And the ability of the M language to define other languages (create DSLs), where I can create my own output generator to create whatever I need - now that is really, really cool!

Once I get done with my book and all my fall travel, you can bet I'll be exploring the use of M to create a specialized language to simplify the creation of CSLA .NET business classes :)

There were numerous talks about .NET 4.0 and the future of C# and VB.

Probably the single biggest thing on the language front is that Microsoft has finally decided to sync VB and C# so they have feature parity. Enough of this back-and-forth with different features, the languages will now just move forward together. A few years ago I would have argued against this, because competition breeds innovation. But today I don't think it matters, because the innovation is coming from F#, Ruby, Python and various other languages and initiatives. Both VB and C# have such massive pre-existing code-bases (all the code we've written) that they can't move rapidly or explore radical ideas - while some of these other languages are more free to do just that.

The framework itself has all sorts of changes and improvements. I spent less time looking at this than at Azure and Oslo though, so I honestly just don't have a lot to say on it right now. I look at .NET 4.0 and Visual Studio 2010 as being more tactical - things I'll spend a lot of time on over the next few months anyway - so I didn't see so much need to spend my time on it during PDC.

Finally, there were announcements around Silverlight and WPF. If anyone doubts that XAML is the future of the UI on Windows and (to some degree) the web, now is the time to wake up and smell the coffee. I'm obviously convinced Silverlight is going to rapidly become the default technology for building business apps, with WPF and Ajax as fallback positions, and everything at the PDC simply reinforced this viewpoint.

The new Silverlight and WPF toolkits provide better parity between the two XAML dialects, and show how aggressively Microsoft is working to achieve true parity.

But more important is the Silverlight intersection with Azure and Live Mesh. The fact that I can build smart client apps that totally host in Azure or the Mesh is compelling, and puts Silverlight a notch above WPF in terms of being the desired start-point for app development. Yes, I really like WPF, but even if it can host in Azure it probably won't host in Mesh, and in neither case will it be as clean or seamless.

So while I fully appreciate that WPF is good for that small percentage of business apps that need access to DirectX or rich client-side resources, I still think most business apps will work just fine with access to the monitor/keyboard/mouse/memory/CPU provided by Silverlight.

A couple people asked why I think Silverlight is better than Ajax. To me this is drop-dead simple. I can write a class in C# or VB that runs on the client in Silverlight. I can write real smart client applications that run in the browser. And I can run that exact same code on the server too. So I can give the user a very interactive experience, and then re-run that same code on the server because I don't trust the client.

To do that in Ajax you'd either have to write your code twice (in C# and in Javascript), or you'd have to do tons of server calls to simulate the interactivity provided by Silverlight - and that obviously won't scale nearly the same as the more correct Silverlight solution.

To me it is a no-brainer - Ajax loses when it comes to building interactive business apps like order entry screens, customer maintenance screens, etc.

That's not to say Ajax has no home. The web and browser world is really good at displaying data, and Ajax makes data display more interesting that simple HTML. I strongly suspect that most "Silverlight" apps will make heavy use of HTML/Ajax for data display, but I just can't see why anyone would willingly choose to create data entry forms or other interactive parts of their app outside of Silverlight.

And that wraps up my on-the-flight-home summary of thoughts about PDC.

Next week I'm speaking at the Patterns and Practices Summit in Redmond, and then I'll be at Tech Ed EMEA in Barcelona. I'm doing a number of sessions at both events, but what's cool is that at each event I'm doing a talk specifically about CSLA .NET for Silverlight. And in December I'll be at VS Live in Dallas, where I'll also give a talk directly on using CSLA .NET.

Friday, October 31, 2008 7:10:16 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Thursday, October 23, 2008

This blog post indicates no, based on a number of good arguments.

It is really true that Silverlight 2.0, out of the box, has a lot of holes or gaps that must be filled in or worked around.

Of course my shameless plug is for CSLA .NET for Silverlight, which fills in most of those gaps. We did encounter the issues listed, and many others. Ultimately CSLA .NET for Silverlight is the result of around 9-10 man-months of effort. That's 9-10 man-months of time finding, researching and solving issues around business application development in Silverlight 2.0.

So while I agree that just picking up Silverlight and running with it will require some serious effort (as compared to WPF, Windows Forms or Web Forms), I don't think that's the whole story. The reality is that frameworks and tools will come into existence (or already have in the case of CSLA .NET) that bring Silverlight's productivity at least up to the level of WPF.

Then the argument becomes that WPF (and Silverlight) lack solid tooling for building the UI. When compared to the designers available for Windows Forms and Web Forms that's absolutely true. However, if you look under the covers, the amount of code and effort required to actually build an app with WPF/Silverlight is absolutely less than Windows Forms or Web Forms - at least when using CSLA .NET.

I say this, because the exact same business objects and data access work in all those environments. So the business and data code is a wash - it is the same in all cases.

But the UI code for WPF/Silverlight is a tiny fraction of the code required for Windows Forms or Web Forms. XAML does require a learning curve, but once you get over that curve it is far more productive, even without good designer tooling.

Yes, I'm totally sold on the Silverlight/WPF/XAML UI future. Yes, there's a learning curve, and yes there's some initial pain. But once you get past that initial hurdle it is sooooo nice. You won't find me going back!

Thursday, October 23, 2008 10:50:46 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Saturday, April 12, 2008

Someone on the CSLA .NET discussion forum recently asked what new .NET 3.5 features I used in CSLA .NET 3.5. The poster noted that there are a lot of new features in .NET 3.5, which is true. They also included some .NET 3.0 features as "new", though really those features have now been around for 15 months or so and were addressed in CSLA .NET 3.0. CSLA .NET 3.0 already added support for WCF, WPF and WF, so those technologies had very little impact on CSLA .NET 3.5.

My philosophy is to use new technologies only if they provide value to me and my work. In the case of CSLA .NET this is extended slightly, such that I try to make sure CSLA .NET also supports new technologies that might be of value to people who use CSLA .NET.

While .NET 3.5 has a number of new technologies at various levels (UI, data, languages), many of them required no changes to CSLA to support. I like to think this is because I'm always trying to look into the future as I work on CSLA, anticipating at least some of what is coming so I can make the transition smoother. For example, this is why CSLA .NET 2.0 introduced a provider model for the data portal - because I knew WCF was coming in a couple years and I wanted to be ready.

Since CSLA .NET already supported data binding to WPF, Windows Forms and Web Forms, there was no real work to do at the UI level for .NET 3.5. I actually removed Csla.Wpf.Validator because WPF now directly supplies that behavior, but I really didn't add anything for UI support because it is already there.

Looking forward beyond 3.5, it is possible I'll need to add support for ASP.NET MVC because that technology eschews data binding in favor of other techniques to create the view - but it is too early to know for sure what I'll do in that regard.

Since CSLA .NET has always abstracted the business object concept from the data access technique you choose, it automatically supported LINQ to SQL (and will automatically support ADO.NET EF too). No changes required to do that were required, though I did add Csla.Data.ContextManager to simplify the use of L2S data context objects (as a companion to the new Csla.Data.ConnectionManager for raw ADO.NET connections). And I enhanced Csla.Data.DataMapper to have some more powerful mapping options that may be useful in some L2S or EF scenarios.

LINQ to Objects did require some work. Technically this too was optional, but I felt it was critical, and so there is now "LINQ to CSLA" functionality provided in 3.5 (thanks to my colleague Aaron Erickson). The primary feature of this is creating a synchronized view of a BusinessListBase list when you do a non-projection query, which means you can data bind the results of a non-projection query and allow the user to add/remove items from the query result and those changes are also reflected in the original list. As a cool option, LINQ to CSLA also implements indexed queries against lists, so if you are doing many queries against the same list object you should look into this as a performance booster!

So all that's left are some of the language enhancements that exist to support LINQ. And I do use some of them - mostly type inference (which I love). But I didn't go through the entire body of existing code to use the new language features. The risk of breaking functionality that has worked for 6-7 years is way too high! I can't see where anyone would choose to take such a risk with a body of code, but especially one like CSLA that is used by thousands of people world-wide.

That means I used some of the new language features in new code, and in code I had to rework anyway. And to be honest, I use those features sparingly and where I thought they helped.

I think trying to force new technologies/concepts/patterns into code is a bad idea. If a given pattern or technology obviously saves code/time/money or has other clear benefits then I use it, but I try never to get attached to some idea such that I force it into places where it doesn't fit with my overall goals.

Saturday, April 12, 2008 3:11:52 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Sunday, March 09, 2008

I'm just back from the MIX 08 conference. This was the first conference I've attended in many years (around 10 I think) where I wasn't speaking or somehow working. I'd forgotten just how fun and inspiring it can be to simply attend sessions and network with people in the open areas. No wonder people come to conference!! :)

Not that it was all fun and games. I did have meetings with some key Microsoft people and Scott Hanselman interviewed me for an upcoming episode of Hanselminutes (discussing the various data access and ORM technologies and how they relate to CSLA .NET 3.5).

The Day 1 keynote was everything I'd hoped for.

Well, nearly. The first part of the keynote was Ray Ozzie trying to convey how Microsoft and the web got to where it is now. The goal was to show the vision they are pursuing now and into the future, but I thought the whole segment was rather flat.

But then Scott Guthrie came on stage and that was everything you could hope for. Scott is a great guy, and his dedication and openness seem unparalleled within Microsoft. I remember first meeting him when ASP.NET was being unveiled. At that time he seemed so young and enthusiastic, and he was basically just this kick-ass dev who'd created the core of something that ultimately changed the Microsoft world. Today he seems nearly as young and easily as enthusiastic, and he's overseeing most of the cool technologies that continue to change the Microsoft world. Awesome!

So ScottGu gets on stage and orchestrates a keynote that really illustrates the future of the web. Silverlight (which makes me SOOoooo happy!), IE8, new data access technologies (like we needed more, but they are still cool!) and things like ASP.NET MVC and more.

As I expected, they released a whole lot of beta code. You can get a full list with links from Tim Sneath's blog. He also has links to some getting started materials.

The real reason for keynotes though, is to inspire. And this keynote didn't disappoint. The demos of Silverlight and related technologies were awesome! There was some funny and cute banter with the casting director from Circ del Sole as she demonstrated using a cool disconnected WPF app. There was a fellow RD, Scott Stanfield, showing integration of SeaDragon into Silveright so we can look (in exquisite detail) at the memorabilia owned by the Hard Rock Cafe company, some thought-provoking demos of Silverlight on mobile devices and more.

Now to be honest, I've never been a fan of the web development model. Having done terminal-based programming for many years before coming to Windows, I find it hard to get excited about returning to that ancient programming model. Well, a worse one actually, because at least the mainframe/minicomputer world had decent state management...

AJAX helps, but the browser makes for a pretty lame programming platform. It is more comparable perhaps to an Apple II or a Commodore 64 than to a modern environment, and that's before you get into the inconsistencies across browsers and that whole mess. Yuck!

Which is why Silverlight is so darn cool! Silverlight 2.0 is really a way to do smart client development with a true web deployment model. Much of the power of .NET and WPF/XAML, with the transparent deployment and cross-platform capabilities of the browser world. THIS is impressive stuff. To me Silverlight represents the real future of the web.

It should come as no surprise then, that I spent my time in Silverlight 2.0 sessions after the keynote. Sure, I've been working (on and off) with Silverlight 1.1/2.0 for the past several months, but it was a lot of fun to see presentations by great speakers like Joe Stegman (a Microsoft PM) and various other people.

One of the best sessions was on game development with Silverlight. I dabble in game development whenever I have spare time (not nearly as much as I'd like), and so the talk was interesting from that perspective. But many of the concepts and techniques they used in their games are things designers and developers will likely use in many other types of application. Background loading of assemblies and content while the app is running, and some clever animation techniques using pure XAML-based concepts (as opposed to some other animation techniques I saw that use custom controls written in C#/VB - which isn't bad, but it was fun to see the pure-XAML approaches).

Many people have asked about "CSLA Light", my planned version of CSLA .NET for Silverlight. Now that we have a Beta 1 of Silverlight I'll be working on a public release of CSLA Light, based on CSLA .NET 3.5. Microsoft has put a lot more functionality into Silverlight 2.0 than they'd originally planned - things like data binding, reflection and other key concepts are directly supported. This means that the majority of CSLA can be ported (with some work) into Silverlight. The data portal is the one big sticking point, and I'm sure that'll be the topic of future blog posts.

My goal is to support the CSLA .NET 3.5 syntax for property declaration and other coding constructs such that with little or no change you can take a business class from full CSLA and have it work in CSLA Light. This goal excludes the DataPortal_XZY implementations - those will almost always be different, though if you plan ahead and use a DTO-based data access model even that code may be the same. Of course time will tell how closely I'll meet this goal - but given my work with pre-beta Silverlight 2.0 code I think it is pretty realistic.

Scott Guthrie indicated that Silverlight 2.0 Beta 1 has a non-commercial go-live license - right now. And that Beta 2 would be in Q2 (I'm guessing June) and would have a commercial go-live license, meaning it can be used for real work in any context.

The future of the web is Silverlight, and Beta 1 is the start of that future. 2008 is going to be a great year!

Sunday, March 09, 2008 5:18:27 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Monday, March 03, 2008

Another place where I was able to reduce business object code in CSLA .NET 3.5 was to effectively eliminate the GetIdValue() method.

Prior to version 3.5, GetIdValue() was required, and you had to provide a unique value identifying your object. This value was used to implement Equals() and GetHashCode(), and was used as the ToString() value. This was good, because it enabled the concept of logical equality, where objects were equal to each other based on their id value.

For better or worse, WPF doesn't support logical equality. They only support absolute equality - ideally implemented by comparing all properties of the two objects so two objects are only equal if all their properties are equal. A poor man's replacement is to use reference equality - which is much faster but is technically less accurate. The effective default in .NET is reference equality.

CSLA .NET 3.5 no longer overrides Equals() or GetHashCode(), so it now uses the .NET default behavior. This makes WPF happy. This might break some people's existing code (though a poll on the forum indicates it is a non-issue for virtually everyone), because there is no longer any idea of logical equality unless you implement it yourself.

The upside though, is that you no longer need to override GetIdValue(). I left the method in the framework for backward compatibilty, so if you do override it your code will continue to compile (though the value is now only used in a ToString() override).

Monday, March 03, 2008 8:53:36 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Wednesday, February 27, 2008

I'm psyched! I finally figured out how to get the Csla.Wpf.CslaDataProvider control to support a Delete command that removes child items from a databound list object.

As you might expect, the answer to the problem was staring me in the face the whole time - I just didn't see it. Isn't that the way things often work? ;)

Since day one, CslaDataProvider has support the Save, Undo and AddNew commands (using XAML commanding), so it has been possible to create Save, Cancel and Add buttons on a form purely through XAML - no code-behind required at all.

Now, with this new change it is also possible to implement a Remove button in a DataTemplate with no code-behind. The button can use the standard Delete command to tell the CslaDataProvider managing the BusinessListBase object to remove the child object bound to that row in the DataTemplate. The XAML looks like this:

<DataTemplate x:Key="lbTemplate">
  <Grid>
    <StackPanel Orientation="Horizontal">
      <TextBlock>Id:</TextBlock>
      <TextBox Text="{Binding Path=Id, Converter={StaticResource IdentityConverter}, ValidatesOnDataErrors=True}" Width="100" />
      <TextBlock>Name:</TextBlock>
      <TextBox Text="{Binding Path=Name, Converter={StaticResource IdentityConverter}, ValidatesOnDataErrors=True}" Width="250" />
      <Button
        Command="ApplicationCommands.Delete"
        CommandParameter="{Binding}"
        CommandTarget="{Binding Source={StaticResource RoleList}, Path=CommandManager, BindsDirectlyToSource=True}"
        HorizontalAlignment="Left">Remove</Button>
    </StackPanel>
  </Grid>
</DataTemplate>

The key was realizing that the CommandParameter could be bound to the entire object that is represented by this DataTemplate - the individual row object. This revelation meant that the CslaDataProvider control can in fact remove that item because an equality comparison is possible. So ApplicationCommands.Delete passes the child object reference to the data provider, which removes the item from the databound list object and that's it!

So this means you can now create a typical maintenance screen with no code behind the XAML. None. You have to write zero lines of VB/C#. Too cool!!

And it means that even on a more complex screen you still don't need to write save/cancel/add new/remove code. That's a lot of code savings! Often all you need to write is code dealing with navigation from this screen to some other screen, perhaps some exception handling code (which I put in a base class) and some authorization code to provide visual cues to the user about what they can and can't do.

Is this really the final step? I doubt it. I already have some ideas on how to expose the authorization knowledge encapsulated by the business object such that it can be directly used within the XAML. I don't know if I'll get that working, but if I can reduce/elminate the UI authorization code (that provides visual cues to the user) and get that into XAML then even more forms will become codeless.

Wednesday, February 27, 2008 8:41:14 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Tuesday, January 22, 2008

in a recent email thread someone was wondering why component vendors are being so slow in coming out with grid controls for WPF/XAML.

One obvious reason is that grid controls are hard to build, and WPF/XAML is radically different from Windows Forms or Web Forms. But still, it is fair to wonder why these highly experienced control vendors haven't overcome that challenge.

I think the reason is that technology isn't the issue. At least not in the raw "learn how to use XAML" way. I think the real issue is much bigger!

Consider the incredible risk a vendor would assume by creating a grid control now.

Microsoft hasn’t come out with a WPF grid, and so there are no standard interfaces in .NET to support data binding to a grid. Certainly the current interfaces used by WPF are not nearly powerful enough to get in-place grid editing like we have in Windows Forms – and that’s a requirement if WPF is ever going to replace Windows Forms for business development.

Windows Forms and Web Forms both have benchmark grids from Microsoft. They set the standard, and define the core interaction used by data binding. The other vendors can then build around that core to do cool stuff. In particular, Windows Forms defines a whole set of powerful interfaces to allow in-place editing so the user can navigate freely in a grid, edit cells, add rows and delete rows – and press ESC to cancel changes to whatever row they are on. All features most users would consider critical to the in-place experience. The majority of those interfaces are not used by WPF today!! Nor does WPF have replacements for them. And if they do replace those interfaces then you can’t bind to a DataTable, which shuts out most developers from WPF again – probably a bad idea.

The WPF team has already shown that they’ll supersede existing interfaces (INotifyCollectionChanged was invented even though IBindingList was already there). So it is somewhat hard to predict where Microsoft might go in this regard. It is quite possible they’ll do the “worse of all worlds” and support the DataTable (all the existing Windows Forms interfaces) and invent a whole new model as well… (again, see INotifyCollectionChanged – invented for WPF, but IBindingList is also fully supported by WPF)

So in WPF the poor component vendors are really stuck. There’s no defined standard for this kind of data binding, so they need to invent it. They’ll each invent something different from the other vendors – and NONE of them will likely match whatever Microsoft eventually does. That means they are all in deep trouble when Microsoft does set the standard. And so are all consumers of those grids (all of us!).

This is very much like pre-ODBC database access, except in this case it is a very safe bet that “ODBC” is coming (in the form of some standard grid definition) and so investing in building a proprietary solution is a known dead-end. A waste of money and very likely a way to make many, many angry customers who may hate you forever.

Nasty business just now… :(

WPF
Tuesday, January 22, 2008 12:17:53 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Wednesday, December 19, 2007

I've been working all day on this WPF/WCF application, mostly trying to figure out how to configure WCF to actually do what I want in terms of security and authentication. All those angle brackets from the config files have given me a splitting headache... WCF may be cool, but configuring even relatively simple security scenarios is ridiculously difficult.

And then distaster struck. As though fighting with WCF and SSL wasn't enough, VS 2008 decided to quit publishing my app for ClickOnce. In order to test this app, I need to publish for ClickOnce on my dev box, copy the results to a test server and then run the code on a test client (thankfully we live in an age of virtual machines!!).

So the failure to publish to ClickOnce brought me up short. The issue is that the WPF project wouldn't build. It would build and run fine in all other ways, but not when I tried to publish for ClickOnce. It had been publishing just fine, and then BOOM!

(The only thing I can think of is that I was publishing for online only, then I published for online/offline, and then I switched back to online only - maybe VS doesn't like that sort of waffling and wants me to be more decisive?)

The specific problem is that the .g.i.cs files for each XAML source file that should have been in the obj\Debug directory didn't get there. Google was no help - searching for "clickonce publish .g.i.cs obj\Debug could not be found" resulted in one hit - to an MSDN forums post that was unreachable (I kept getting an MSDN forums error page).

Build|Clean Solution had no effect. Shutting down and reopening VS had no effect. Rebooting the dev box had no effect.

Finally I thought to manually delete the obj and bin folders in the project directory. And for good measure I deleted the .user file and .suo file for the project and solution. Then I reopened the project and it how publishes just fine.

Wednesday, December 19, 2007 5:10:22 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Tuesday, November 13, 2007

I was recently asked whether CSLA incorporates thread synchronization code to marshal calls or events back onto the UI thread when necessary. The short answer is no, but the question deserves a bit more discussion to understand why it isn't the business layer's job to handle such details.

The responsibility for cross-thread issues resides with the layer that started the multi-threading.

So if the business layer internally utilizes multi-threading, then that layer must abstract the concept from other layers.

But if the UI layer utilizes multi-threading (which is more common), then it is the UI layer's job to abstract that concept.

It is unrealistic to build a reusable business layer around one type of multi-threading model and expect it to work in other scenarios. Were you to use Windows Forms components for thread synchronization, you'd be out of luck in the ASP.NET world, for example.

So CSLA does nothing in this regard, at the business object level anyway. Nor does a DataSet, or the entity objects from ADO.NET EF, etc. It isn't the business/entity layer's problem.

CSLA does do some multi-threading, specifically in the Csla.Wpf.CslaDataProvider control, because it supports the IsAsynchronous property. But even there, WPF data binding does the abstraction, so there's no thread issues in either the business or UI layers.

Tuesday, November 13, 2007 11:09:54 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

I haven't tried this yet, but it looks like a very nice tool for WPF developers:

Woodstock for WPF - The Code Project - Windows Presentation Foundation

WPF
Tuesday, November 13, 2007 10:48:41 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Wednesday, October 10, 2007

Earlier this week I co-presented a session at ReMIX in Boston, with Anthony Handley, a fellow Magenicon. Anthony is a User Experience Specialist, and the two of us have been working on a WPF/Silverlight project (that also happens to use CSLA .NET of course :) ) and in this presentation we discussed our experiences using WPF from the perspectives of a developer and a designer.

Here are the links to the video of the session.

Real World Experiences Building Applications Using WPF and Silverlight

Part 1
http://channel9.msdn.com/Showpost.aspx?postid=346810
Part 2
http://channel9.msdn.com/Showpost.aspx?postid=346812
Part 3
http://channel9.msdn.com/Showpost.aspx?postid=346815
Part 4
http://channel9.msdn.com/Showpost.aspx?postid=346818

Wednesday, October 10, 2007 3:10:17 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

In CSLA .NET 3.0 I implemented Csla.Wpf.Validator. This control provides functionality similar to the Windows Forms ErrorProvider control, only in WPF. Of course the ErrorProvider relies on the standard IDataErrorInfo interface, which CSLA supports on behalf of your business objects, and so my Validator control used that same interface.

While I was researching and designing the Validator control, I was in contact with the WPF product team. As a result, I had (shall we say) a "strong suspicion" that my control was a temporary stop-gap until Microsoft provided a more integrated solution. And that's fine - we needed something that worked, and Validator was the ticket.

This blog post provides some good, detailed, insight into the real solution in .NET 3.5: 

Windows Presentation Foundation SDK : Data Validation in 3.5

A couple people have emailed me, asking what I think about this. My answer: I'm happy as can be!

As I say, I knew Validator was temporary. WPF is a version 1.0 technology, and it is very clear that Microsoft will be evolving it rapidly over the next few years. And it is equally clear that WPF must evolve to catch up to, and hopefully exceed, Windows Forms. That means more robust data binding support, including an ErrorProvider equivalent.

So to me, this just means that CSLA .NET 3.5 can drop the Validator control, because there's now a directly supported solution in .NET itself. While this will require changing XAML when moving from .NET 3.0 to 3.5, it is a worthwhile change to make.

Wednesday, October 10, 2007 9:31:01 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Friday, September 28, 2007

CSLA .NET version 3.0 adds support for Microsoft .NET 3.0 features. This ~120 page ebook covers how to use these new capabilities:

  • Windows Presentation Foundation (WPF)
    • Creating WPF forms using business objects
    • Using the new controls in the Csla.Wpf namespace
      • CslaDataProvider
      • Validator
      • Authorizer
      • ObjectStatus
      • IdentityConverter
    • Maximizing XAML and minimizing C#/VB code
  • Windows Communication Foundation (WCF)
    • Using the new WCF data portal channel to seamlessly upgrade from Remoting, Web services or Enterprise Services
    • Building WCF services using business objects
    • Applying WCF security to encrypt data on the wire
    • Sending username/password credentials to a WCF service
      • Including use of the new Csla.Security.PrincipalCache class
    • Using the DataContract attribute instead of the Serializable attribute
  • Windows Workflow Foundation (WF)
    • Creating activities using business objects
    • Invoking a workflow from a business object
    • Using the WorkflowManager class in the Csla.Workflow namespace

Version 3.0 is an additive update, meaning that you only need to use the .NET 3.0 features if you are using .NET 3.0. CSLA .NET 3.0 is useful for people using .NET 2.0!! These features include:

  • Enhancements to the validation subsystem
    • Friendly names for properties
    • Better null handling in the RegExMatch rule method
    • New StringMinLength rule method
    • Help for code generation through the DecoratedRuleArgs class
  • Data binding issues
    • Fixed numerous bugs in BusinessListBase to improve data binding behavior
    • Throw exception when edit levels get out of sync, making debugging easier
    • N-level undo changed to provide parity with Windows Forms data binding requirements
  • AutoCloneOnUpdate
    • Automatically clone objects when Save() is called, but only when data portal is local
  • Enhancements to the authorization subsystem
    • CanExecuteMethod() allows authorization for arbitrary methods

CSLA .NET 3.0 includes numerous bug fixes and some feature enhancements that benefit everyone. If you are using version 2.0 or 2.1, you should consider upgrading to 3.0 to gain these benefits, even if you aren't using .NET 3.0.

See the change logs for version 3.0, version 3.0.1 and version 3.0.2 for a more detailed list of changes.

Using CSLA .NET 3.0 is completely focused on how to use the new features in version 3.0. The book does not detail the internal changes to CSLA .NET itself, so all ~120 pages help you use the enhancements added since version 2.1.

Get the book at store.lhotka.net.
(C# available now, VB available in early October)

Download the 3.0.2 code from the CSLA .NET download page.

Books | CSLA .NET | WCF | Workflow | WPF
Friday, September 28, 2007 3:21:26 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

It is a reasonably well-known fact that WPF misuses the Equals() method in the data binding implementation.

If you set a DataContext to an object, then set it to another object that is logically equal to the first, but which has different data, WFP gladly ignores the new object's data:

form.DataContext = A;
B = A.Clone();
B.Value = "new value";
form.DataContext = B;

Assuming A and B retain logical equality even though Value has changed, this code results in the UI not showing the new value. Apparently the reasoning is that if the objects are equal, then there's no need to update any data through data binding.

Of course this totally confuses ReferenceEquals() with Equals(), and the result is that objects used by WFP can no longer have logical equality. They can only have reference equality.

(or, arguably, WPF forces 100% property-level equality across objects, so equality can extend to two different instances as long as they have absolutely no different property values - which seems entirely useless)

In .NET 3.0 I had a solution, at least in CslaDataProvider. The solution was to temporarily set the DataContext to null, then to the new object. The result was that the faulty (imo anyway) equality comparison was defeated.

Unfortunately, it appears that .NET 3.5 may have "fixed a bug" that prevents this from working. The result is that it appears there is NO WAY TO REFRESH DATA when fields of an object change, but the object's logical identity remains the same.

I'm not yet sure of a final solution. The current situation is very bad, because you can either use WPF or you can have logical equality between objects - but not both.

It might be the case that people who need logical equality will have to implement their own parallel Equals() concept - ignoring the standard one built into .NET. That's a really poor solution, but if Microsoft isn't going to use their own framework responsibly then we're kind of stuck. Of course operators become an issue then, since operator overloading is related to Equals() as well. I suppose you could break that relationship, but then you'd get really odd stuff like this:

x = y is true

x.Equals(y) is false

But if WPF forces Equals() to be ReferenceEquals() instead of actual equality, then we come back to being stuck.

I love WPF - it is really cool. But this particular issue is a real problem. Apparently one without a real solution.

WPF
Friday, September 28, 2007 9:02:38 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Friday, September 21, 2007

I just got back from VS Live NY - which was a great show. It sold out, and the people attending were very engaged and fun to be with. I love crowds like that!

In my all-day workshop on building distributed apps using objects I showed how to use WPF commanding to automatically enable/disable Save and Cancel buttons on a form by connecting them to a CslaDataProvider control. That's a really cool feature of WPF that I am leveraging with some of the new CSLA .NET 3.0 features.

An attendee asked if it was possible to hide the Save button, not just disable it. I hadn't thought about that, and came up with some answer involving code.

Josh Smith, who was also in the audience, has given this even further thought and sent me an email with a better, pure XAML, solution. Thank you Josh!! Here's the relevant bit of the email:

During the presentation a fellow asked you how, in WPF, to hide a Button when it is disabled.  The Button was disabled because its associated command could not execute, and he wanted to hide the Button instead of letting it sit in the UI disabled.

The solution you gave him involved some code, which threw a red flag in my mind.  IMO, this is the kind of thing you should use XAML to express, so that there are less "moving parts" in your app.  Here's one way to implement that functionality with no code at all:

<Button Command="Open" Content="_Open">
  <Button.Style>
    <Style TargetType="Button">
      <Style.Triggers>
        <Trigger Property="IsEnabled" Value="False">
          <Setter Property="Visibility" Value="Collapsed" />
        </Trigger>
      </Style.Triggers>
    </Style>
  </Button.Style>
</Button>

Depending on your layout, you might want to set Visibility to Hidden instead.

Friday, September 21, 2007 7:01:20 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Wednesday, June 20, 2007

A CSLA .NET user, Aaron Nottestad, has been helping test 3.0 and ran into some issues when using the new WPF CslaDataProvider with editable objects. Thanks Aaron!

As a result, I had to do some work with CslaDataProvider, so it can manage the object’s entire lifetime from create/fetch through to save/cancel. If it can’t manage the lifetime, especially the save, then it can’t get the new object that comes back as a result of save. And if it doesn’t get that new object, then neither does data binding, so the UI controls end up editing an old instance of the object.

So the CslaDataProvider now has Save() and Cancel() methods that you can call to trigger saving or canceling of the business object. Also, as the object is created/fetched CslaDataProvider automatically calls BeginEdit() on the object.

This behavior is all optional, and is controlled by the ManageObjectLifetime property of the CslaDataProvider control. So if you want this behavior, you have to set that property to True. If you leave it at False (the default), then you must manage everything through code – though honestly you can’t manage editable objects through code while using CslaDataProvider. So maybe I should make the default be True? Hmm.

Anyway, this was easy enough to do and worked great. The resulting forms had exactly 4 lines of code – 2 to call Save() and 2 to call Cancel(). It occurred to me that there must be a way to avoid writing those 4 lines of boring code, and Aaron put me onto the RoutedCommand concept in XAML.

A RoutedCommand allows a control like a button or menu item to invoke a method on another control – purely through XAML. There are many examples out there about how this works to create standard Copy/Paste menu items that run against the current TextBox control, and that sort of thing. But none that I found which routed a command to a data provider control.

The reason turns out to be that the target of a command must be a UIElement, and data providers don’t inherit from that base class. Oops…

I thought I was stuck, because I really do want to route the command to CslaDataProvider in this case. However, I figured out a solution.

CslaDataProvider now has a read-only CommandManager property. This property exposes a “command manager” object which does inherit from UIElement and which does handle the Save and Undo routed commands. When it is created by CslaDataProvider, it is given a reference to the CslaDataProvider control, so it simply delegates all Save commands to the CslaDataProvider.Save() method and all Undo commands to CslaDataProvider.Cancel().

With that done, you can route a command from a button or menu item (or any other valid command source) to this CommandManager object, which effectively means you’ve routed the command to the CslaDataProvider control.

The CslaDataProvider gets declared like this:

    <csla:CslaDataProvider x:Key="ChildList"

                           ObjectType="{x:Type this:ChildList}"

                           FactoryMethod="GetList"

                           IsAsynchronous="False"

                           ManageObjectLifetime="True">

    </csla:CslaDataProvider>

 

Then the button controls get declared like this:

            <Button

              Command="ApplicationCommands.Save"

              CommandTarget="{Binding Source={StaticResource ChildList},

                              Path=CommandManager, BindsDirectlyToSource=True}"

              HorizontalAlignment="Left" IsDefault="True">Save</Button>

            <Button

              Command="ApplicationCommands.Undo"

              CommandTarget="{Binding Source={StaticResource ChildList},

                              Path=CommandManager, BindsDirectlyToSource=True}"

              HorizontalAlignment="Left" IsCancel="True">Cancel</Button>

 

The result is very cool: a form that can edit an object without the need to write any C# or VB code at all. Coupled with the CSLA .NET ValidationPanel to display validation results, you can create a highly interactive data edit form purely with XAML – and of course a CSLA .NET style business object doing all the work behind the scenes.

These new capabilities will appear in CSLA .NET 3.0 Beta 2 - hopefully later this week.

Wednesday, June 20, 2007 10:14:03 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

I’ve been spending some quality time with WPF and Visual Studio 2008 Beta 1 (Orcas) over the past few months. A couple observations I’ve made:

Observation ichi:

Putting code in a Page/Window constructor is bad. Yes, I know it is the “C# way”, but it is bad. The “VB way” of putting code in the Loaded event handler is better.

Why?

Because any exceptions thrown in the constructor prevent the page/window from loading at all, and you have to catch those exceptions in the code that is creating the page/window. In many navigation scenarios you can’t catch them, so the user gets an ugly WPF exception dialog.

However, if you do all your init work in the Loaded event handler, the page/window instance already exists. Navigation has already happened, so the “calling code” is no longer responsible for your page/window going haywire. Instead, you can actually handle the exception and show a nice dialog, explaining to the user what happened, and you can (if desired) navigate somewhere else or whatever.

Observation ni:

Handing control events with += or AddHandler is superior to using WithEvents/Handles. Yes, I am a strong advocate of WithEvents/Handles, and it is one of the major missing features in C#, but for WPF it turns out to be a negative.

Why?

Because the Handles clause links the name of the control to the code behind. The AddHandler or += approach, while less attractive in many ways, only couples the event name to the code behind.

In other words, when using Handles you get code like:

Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) _
  Handles Button1.Click

While the AddHandler approach results in this code:

Private Sub SaveData(ByVal sender As Object, ByVal e As EventArgs)

The value of the second approach is that any control can route an event to SaveData(). It doesn’t have to be a button, much less Button1. It actually doesn’t even have to be a Click event. It could be almost any event.

The result is that the Presentation (XAML) is less coupled to the UI (VB/C# code) this way than when using Handles.

Unfortunately the Handles approach is more explicit and thus more readable (which is why C# should really get the Handles feature), so we’re left trading readability in order to gain loose coupling…

WPF
Wednesday, June 20, 2007 9:51:35 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  |