Rockford Lhotka's Blog

Home | Lhotka.net | CSLA .NET

 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]  | 
 Monday, July 30, 2012

I want to summarize some of the more major changes coming to the data portal in CSLA 4 version 4.5. Some of these are breaking changes.

I’ve done four big things with the data portal:

  1. Added support for the new async/await keywords on the client and server
  2. Merged the .NET and Silverlight data portal implementations into a single code base that is now common across WinRT, .NET, and Silverlight
  3. Removed the public virtual DataPortal_XYZ method definitions from Silverlight, because it can now invoke non-public methods just like in .NET. Also, all local Silverlight data portal methods no longer accept the async callback handler, because they now support the async/await pattern
  4. Remove the ProxyMode concept from the Silverlight data portal, because the RunLocal attribute is now available on all platforms

All four have some level of breaking change.

Adding comprehensive support for async/await changes the way .NET handles exceptions. Although I’ve worked to keep the top level exceptions consistent, the actual exception object graph (nested InnerExceptions) will almost certainly be different now.

Merging the .NET and Silverlight data portal implementations introduces a number of relatively minor breaking changes for Silverlight users. Though if you’ve created custom proxy/host pairs or other more advanced scenarios you might be more affected than others. There may also be unintended side-effects to .NET users. Some might be bugs, others might be necessary to achieve platform unification.

Removing the public virtual DataPortal_XYZ methods from BusinessBase and BusinessListBase will break anyone using the local Silverlight data portal. The fix is minor – just change the public scopes to protected. This change shouldn’t affect anyone using .NET, or using a remote data portal from Silverlight.

Removing the async callback parameter from all Silverlight client-side DataPortal_XYZ methods will break anyone using the local Silverlight data portal. The fix is to switch to the new async/await pattern. The code changes are relatively minor, and generally simplify your code, but if you’ve made extensive use of the client-side data portal in Silverlight this will be a pretty big change I’m afraid.

Similarly, removing the ProxyMode concept from the Silverlight data portal is a breaking change for people using the local Silverlight data portal. Again, the fix is pretty simple – just add the RunLocal attribute to the DataPortal_XYZ (or object factory) methods as you have always done in .NET.

On the upside, the coding patterns for writing code in .NET, WinRT, and Silverlight are now the same.

For example, a DataPortal_Fetch method on any platform looks like this:

private void DataPortal_Fetch(int id)

or like this

private async Task DataPortal_Fetch(int id)

The data portal will automatically detect if your method returns a Task and it will await the method, allowing you to use the await keyword inside your DataPortal_XYZ methods.

Similarly, all platforms can now write this client-side code:

var obj = await CustomerEdit.GetCustomerAsync(123);

or the older event-style code:

CustomerEdit.GetCustomer(123, (o, e) =>
  {
      if (e.Error != null)
          throw e.Error;
     else
          obj = e.Object;
  });

Only .NET code can use the synchronous approach:

var obj = CustomerEdit.GetCustomer(123);

This is one of the few platform-specific concepts left in the data portal.

What is really cool is that the client and server sync/async concepts can be mixed (as long as you know what to expect).

Client method Client platform Server method Server platform Remarks
Fetch .NET only void DataPortal_Fetch any Client call is synchronous; server call is synchronous
Fetch .NET only Task DataPortal_Fetch any Client call is synchronous; server call is asynchronous; note that client will block until the server’s work is complete
BeginFetch any void DataPortal_Fetch any Client call is asynchronous (event-based); server call is synchronous; client will not block, and must handle the callback event to be notified when the server call is complete
BeginFetch any Task DataPortal_Fetch any Client call is asynchronous (event-based); server call is asynchronous; client will not block, and must handle the callback event to be notified when the server call is complete
FetchAsync any void DataPortal_Fetch any Client call is asynchronous; server call is synchronous; client will block or not, depending on how you invoke the client-side Task (using await or other techniques); the client-side Task will complete when the server call is complete
FetchAsync any Task DataPortal_Fetch any Client call is asynchronous; server call is asynchronous; client will block or not, depending on how you invoke the client-side Task (using await or other techniques); the client-side Task will complete when the server call is complete

I expect all client-side data portal code to switch to the async/await versions of the methods, and so I’ve made them the mainline path through the data portal. The synchronous and event-based async methods use async/await techniques behind the scenes to do implement the desired behaviors.

There is a lot of variety in how you can invoke an awaitable method like FetchAsync. The specific async behaviors you should expect will vary depending on how you invoke the method. For example, there’s a big difference between using the await keyword or the Result or RunSynchronously methods:

var obj = await CustomerEdit.GetCustomerAsync(123);

var obj = CustomerEdit.GetCustomerAsync(123).Result;

The former is async, the latter is sync. The former will return a simple exception (if one occurs), the latter will return an AggregateException containing the simple exception. This has little to do with CSLA, and nearly everything to do with the way the async/await and task parallel library (TPL) are implemented by .NET.

Finally, I do need to state that the actual network transport (typically WCF) used by .NET, Silverlight, and WinRT aren’t the same. This is because WCF in .NET is far more flexible than in Silverlight or WinRT. And because the WCF client-side proxies generated for Silverlight use event-driven async methods, and in WinRT the proxy is task-based.

The data portal hides these differences pretty effectively, but you should understand that they exist, and as a result there may be subtle behavioral differences between platforms, especially when it comes to exceptions and exception details. The success paths for creating, fetching, updating, and deleting objects are identical, but there may be edge cases where differences exist.

All in all I am quite pleased with how this is turning out. I’ve put a massive amount of work into the data portal for 4.5, especially around unifying the implementations across platforms. I suspect there’ll be some issues to work through during the beta testing phase, but the end result is a far more consistent, maintainable, and streamlined codebase for all platforms. That will benefit all of us over time.

Monday, July 30, 2012 10:53:23 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Sunday, March 04, 2012

I am pleased to announce the release of CSLA 4 version 4.3. It is available from the CSLA download page and from nuget.

This release adds support for Silverlight 5.

Silverlight 4 is still supported. The assemblies are in a Silverlight4.zip file in the bin folder created by the setup program in your Program Files folder or other install location.

Other major enhancements include:

  • New binary serialization scheme for MobileFormatter resulting in substantially smaller data flowing across the data portal from Silverlight and Windows Phone client applications. The ProjectTracker sample application has been updated to use this new scheme – look at the app server web.config and the SilverlightUI and WpUI app.xaml.cs files to see how the client and server configuration is handled.
  • Numerous enhancements to the business rules subsystem. See the change log for more information.
  • Bug fixes to address some specific data portal issues. See the change log for more information.
  • CommandBase now supports managed properties.

With this version, CSLA 4 now supports the following platforms:

  • Microsoft .NET 4
    • Windows Forms
    • ASP.NET Web Forms
    • ASP.NET asmx services
    • WPF
    • WCF services
    • ASP.NET MVC 3
  • Silverlight 5
  • Silverlight 4
  • Windows Phone 7.5
  • Mono
    • OS X
    • Linux
  • Mono for Android

The source code also includes a version of CSLA 4 that builds for WinRT (Windows 8) Consumer Preview. This is largely untested, but does demonstrate that existing business classes (especially those built for 3- and 4-tier deployments in Silverlight) can be simply recompiled for use in WinRT applications. Consider this a preview of CSLA 4 version 4.5, coming later this year with support for .NET 4.5 and WinRT.

Sunday, March 04, 2012 3:29:03 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Monday, February 13, 2012

A beta release of CSLA 4 version 4.3 is now available from here:

www.lhotka.net/cslanet/download.aspx

The big change in this beta release is that the Silverlight projects are now bound to Silverlight 5.

I plan to write a document describing how to undo the very few changes required to support Silverlight 5, so if you want to back-port the code for Silverlight 4 you'll be able to do so on your own. This document will be available within the next couple weeks - before the 4.3 release.

The really big change came in the previous alpha release: MobileFormatter now allows much more efficient creation of the serialized byte stream, resulting in much smaller amounts of data sent over the network between a Silverlight/Windows Phone client and an app server. This same technology will be used in the WinRT codebase as well.

My plan is to release 4.3 on or before Feb 29.

That will allow us to branch 4.3 in svn so the primary codebase can focus on version 4.5 with support for .NET 4.5 and WinRT.

The 4.3 release will go into maintenance mode - meaning we'll address bugs, but don't plan any more feature changes.

Monday, February 13, 2012 12:45:40 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [2]  | 
 Thursday, January 26, 2012

I have posted an alpha version of CSLA 4 version 4.3.0 for download from the CSLA download page.

Although Jonny has been extremely busy with a number of bug fixes and some feature changes, I think the biggest change in this alpha release is a major optimization of the MobileFormatter.

MobileFormatter is used to serialize object graphs on Silverlight and Windows Phone. It is used by the data portal, and n-level undo (if you use that feature).

Until now, I have recommended that you use compression on the byte stream that flows over the data portal, because the XML created by the MobileFormatter is often quite large. It compresses efficiently, and we’re quite efficient about what we put into the byte stream, but it is just plain big.

Sergey did some really nice work for version 4.3, allowing the use of alternate reader/writer objects so the data can be serialized into something other than XML. Specifically, he created binary reader and writer objects that are around 70% more efficient in terms of byte stream size. That’s about as much as you could expect to get with compression!

The result is that you can probably avoid the CPU intensive overhead of compression and still get a small byte stream to transfer over the network.

The CSLA 4 version 4.3.0 change log includes a discussion of the configuration settings you need to change to use the new reader/writer objects.

This is a non-breaking change, because the default is the same behavior as in 4.2. But this is a big change and we really appreciate your help in testing the new reader/writer objects to ensure they work across a wide range of applications.

Thursday, January 26, 2012 1:15:02 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [2]  | 
 Saturday, November 12, 2011

One of the primary goals for CSLA 4 version 4.3 (the next version we’ll be creating) is to improve the performance of the MobileFormattter that is used for Silverlight and Windows Phone applications. This is made all the more important, because it will also be used in WinRT applications in the future.

Sergey (a CSLA dev team member, and Magenic colleague) has been doing some heavy research into this area, and we’d originally thought to do the changes as part of the 4.2 release. It turns out that doing a really great job of optimization will require some breaking changes – at least for people who aren’t using managed backing fields. So we are deferring the bigger changes until 4.3.

In the meantime, Sergey has blogged about how to improve performance of MobileFormatter in 3.8 and 4 (4.0, 4.1, or 4.2). These are changes you can make to your CSLA codebase now if you want some of the performance benefits without waiting for the “big change” that’ll come in 4.3.

Saturday, November 12, 2011 12:41:27 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [2]  | 
 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

I’ve posted a number of blog entries on Windows 8 and WinRT, and thought it might be worth summarizing them. I suggest reading them in this order:

Win8, Metro, and WinRT terminology – why WinRT != Metro, and when I think each term should be used

Windows 8 Development Platform Clarified – addresses questions about today’s technologies and how they map into Windows 8, includes the Magenic Windows 8 platform diagrams

Updated Windows 8 Dev Platform - revised/improved Windows 8 Development Platform graphic

WinRT and business apps – why I am convinced that WinRT is relevant for business developers (and future business app development)

Silverlight 6 doesn't matter - why the Microsoft product support strategy, and WinRT, mean that Silverlight 6 (whether it exists or not) doesn't matter

Migrating smart clients to WinRT – somewhat CSLA .NET specific discussion on what you can do today to ease migration to WinRT in the future

WinRT and .NET – first thoughts based on the //Build/ conference – a bit rambling, but still generally useful

Why MVVM – technical post discussing why using MVVM in WPF/SL today will help migrate to WinRT in the future

CSLA on WinRT (project start) – initial findings as I started porting CSLA .NET to WinRT

WinRT BackgroundWorker type – technical post showing one way to recreate BackgroundWorker using async/await in WinRT

Monday, October 24, 2011 12:04:36 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

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]  | 
 Wednesday, September 28, 2011

I have been giving quite a lot of thought to the WinRT migration path. What is the outlook for taking a Windows Forms, WPF, or Silverlight app into WinRT/Metro in Windows 8?

The amount of effort required for any given application may vary radically, depending on the architecture used when building the application, and how well that architecture was implemented in the actual code. And it is obviously important to understand how much client-side application code uses .NET features that aren’t in WinRT, or that are substantially different in WinRT.

And of course I tend to look at this from a CSLA .NET perspective Smile  If you use CSLA 4 today, and you adhere to the architecture and coding structures recommended when using CSLA, most or all of your business layer code will probably move to WinRT without change.

So, rather simplified, and CSLA-centric, here’s a set of process flows:

image

Although the first decision point is “Using CSLA?”, you could replace that with “using a architecture/framework that abstracts all business, validation, authorization, data access and other application logic away from the UI, exposing a model that supports data binding and async server interactions”. Although I’m obviously biased, there are absolutely other architectures that offer the same layered abstraction to keep all business and data logic out of the presentation layer. And that’s really what’s required.

In the final analysis, if you have any business or data logic in your code-behind, or you aren’t using data binding to connect your existing UI views to some sort of business objects, you have some work ahead of you to get to that point.

Essentially all non-CSLA Windows Forms apps I’ve ever seen will require a complete rewrite. Most use DataSet objects, and therefore require total rework. And most use a lot of code-behind, and therefore require total rework. And a lot of them use numerous windows and modal dialogs, so the user workflow will require a complete rethink.

A surprising number of WPF apps are written much like Windows Forms apps, with code-behind, etc. Those apps will require much the same effort to migrate as Windows Forms. But if you’ve written your WPF app using MVVM, even without something like CSLA, and have strictly avoided code-behind, the migration probably won’t be too bad.

The big thing is that a lot of WPF apps aren’t written to assume async server interactions, and updating code to handle that can be a lot of work. WPF apps written using CSLA may already be using the async features in CSLA, and so can avoid this issue entirely. Worst case, if you are already using CSLA synchronously, the changes to move to async aren’t overwhelming.

If you have a Silverlight app, you are in the best position of anyone, because you are already using async server interaction, and can’t have made the mistake of using the DataSet. And if you are using MVVM without any code-behind your migration will probably be quite smooth.

If you are also using CSLA, then your existing business layer will probably translate to WinRT without change.

As I mentioned in a previous WinRT post, Windows 8 is years away for most organizations. At the same time, I do think that WinRT/Metro will be used for business app development.

Quite a number of people are mistakenly saying that “Silverlight is dead”, when in reality Silverlight has never been more important.

What are you going to use to build business apps in the years between now and when Win8 is available in your organization?

You might consider using the technology that appears to offer the easiest migration to WinRT… And that is Silverlight (plus MVVM and CSLA 4 Smile ).

Wednesday, September 28, 2011 11:35:58 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]  | 
 Monday, November 01, 2010

Halloween is over, so it is time to quit being scared and get back to reality.

This is, perhaps, easier for me, because my wife and I attended the Rally to Restore Sanity and/or Fear over the weekend. There’s nothing like being surrounded by 200,000+ sane people on a beautiful afternoon in Washington DC to refresh your spirit and appreciation for the true strength of America (and I think humanity in general).

Of course while we were enjoying great music, comedy and an inspirational speech by Jon Stewart, the Microsoft developer world was turning itself inside out with the hyperbole generated by last week’s PDC conference and some less than thoroughly explained remarks made by Bob Muglia in an interview.

My reaction, perhaps tempered by hours of restoring sanity, was relatively simple:

  1. Microsoft (and BobMu) clearly didn’t intend to gut their entire client-side development community
  2. Therefore this is just a (perhaps big) PR mistake, nothing more
  3. Therefore it is best to just wait for Microsoft to correct the mistake with clarification

I feel justified in that reaction, since we now have clarification from BobMu and SteveB:

Other Microsoft Silverlight bloggers, such as Tim Heuer, are starting to blog as well, so I’m sure there’ll be further reinforcement and refinement of these top-level responses. And I would expect to see continuing movement on the part of Microsoft and its product groups to prove their ongoing top-level commitment to Silverlight and the whole idea of a Microsoft-based smart-client experience.

I think what happened is this: at least in the US we’re just a day away from a big election. For weeks (months?) we’ve been bombarded with messages of fear and hatred from political candidates, political action committees and cable news channels. It is very challenging to maintain a positive or even moderate outlook on life itself when you are continually inundated (unless you never watch television or listen to the radio or go to your mailbox) by these vile messages from every side for weeks or months on end.

It is no surprise to me that the developers, at least in the US, fell right into the same fear/hatred mindset with the (clearly incongruous) information about Silverlight – everyone’s mind is already primed for a fight-or-flight response. Confusion leads instantly to fear, which (as we all know) leads to the dark side.

After tomorrow, the election will be over, along with the fear/hate ads. By the time our brain chemistry has returned to normal, the newly elected politicians will be well down the path of corporate-sponsored corruption and life will continue.

In the meantime, at least we now know (again) that Silverlight has a bright future as the smart client development tool of choice for Windows, the Mac, Windows Phone and other devices.

Monday, November 01, 2010 1:27:32 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [6]  | 
 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]  | 
 Tuesday, August 10, 2010

I am working on CSLA 4 for Windows Phone 7. Of course I want to get all my unit tests (or most of them anyway) running on WP7.

When we created CSLA .NET for Silverlight it was long before Silverlight 2 shipped, and there was no workable unit test framework for Silverlight. Even today, it is tricky to test async methods and features with mstest in SL. Perhaps most importantly however, I wanted to have the same exact unit test code running in .NET and Silverlight – and that’s a level of parity that is hard to achieve.

So Justin created UnitDriven and we donated it to the community through codeplex: http://unitdriven.codeplex.com.

And I have a few hundred unit tests for CSLA that rely on UnitDriven, so it isn’t a trivial thing to think about switching to something else – so it is important that UnitDriven work on WP7 too.

Fortunately Justin was able to get this done in an evening. It turns out that the only major change required was to the UI, because obviously the WP7 form factor is very space constrained compared to a full-size screen.

The end result is that there’s a preview release of UnitDriven that works on WP7 – you can download it from codeplex.

Most of my CSLA unit tests are passing at this point, which gives us some confidence that UnitDriven is working as expected. There are some UI issues still, especially with long test names and some scrolling issues.

But if you are looking for a way to write unit tests for your WP7 Silverlight code, and especially if you want to use the same unit test code on .NET, Silverlight and WP7, then UnitDriven is something you should consider.

Tuesday, August 10, 2010 1:22:31 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]  | 
 Monday, July 26, 2010

I was interviewed for MSDN Bytes while at Tech Ed in New Orleans earlier this year. The interview is now online:

http://msdn.microsoft.com/en-us/ff851876.aspx

The interview is focused on Windows Phone 7, but of course I also talk about Silverlight and CSLA .NET a little bit too.

Monday, July 26, 2010 10:39:28 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 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]  | 
 Thursday, July 01, 2010

The fact that server access is all async in Silverlight makes some common tasks a little more challenging. This includes lazy loading child objects in an on-demand manner.

When implementing lazy loading in CSLA it is pretty typical to implement the on-demand load of the child property value in the child property getter. In other words, in the parent object, there’ll be a property that exposes the child object, and in the getter of that property is where the lazy loading code goes:

public static PropertyInfo<Child> ChildProperty = RegisterProperty<Child>(c => c.Child);
public Child Child
{
  get
  {
    if (!FieldManager.FieldExists(ChildProperty))
    {
      Child = DataPortal.Fetch<ChildLoader>().Child;
      OnPropertyChanged(ChildProperty);
    }
    return GetProperty(ChildProperty);
  }
  private set { LoadProperty(ChildrenProperty, value); }
}

The ChildLoader type shown here is a command object (I typically use a ReadOnlyBase subclass) that runs to the server, loads the child object and returns it to the client. ChildLoader might look like this:

[Serializable]
public class ChildLoader : ReadOnlyBase<ChildLoader>
{
  public static PropertyInfo<Child> ChildProperty = RegisterProperty<Child>(c => c.Child);
  public Child Child
  {
    get { return ReadProperty(ChildProperty); }
    private set { LoadProperty(ChildProperty, value); }
  }

  private void DataPortal_Fetch()
  {
    Child = DataPortal.FetchChild<Child>();
  }
}

This all works great in .NET, where all this code is synchronous. But it needs a little tweaking to work in Silverlight, where server communication is async.

First, the parent property getter must return something before it has the actual value. This is kind of a big deal, because it means the UI must be able to handle getting back a null value, and then later getting the real value. This isn’t too hard though, at least if you are using data binding, because the UI will show nothing for the null value, and will automatically refresh the display when the real value arrives (because CSLA will raise a PropertyChanged event for the Child property).

Also, you’ll probably want to mark the parent object as busy while the operation is occurring, so the UI can take appropriate steps (again, by using data binding against the IsBusy property) to block the user from trying to interact with this part of the app until the actual data arrives:

public static PropertyInfo<Child> ChildProperty = RegisterProperty<Child>(c => c.Child);
public Child Child
{
  get
  {
    if (!FieldManager.FieldExists(ChildProperty))
    {
      MarkBusy();
      DataPortal.BeginFetch<ChildLoader>((o, e) =>
        {
          if (e.Error != null)
            throw e.Error;
          Child = e.Object.Child;
          MarkIdle();
          OnPropertyChanged(ChildProperty);
        });
    }
    return GetProperty(ChildrenProperty);
  }
  private set { LoadProperty(ChildrenProperty, value); }
}

When the getter is first called it will start the async load operation, and then it will return null. Later, when the BeginFetch() call completes it will set the Child property to the actual value and indicate that the parent object is no longer busy.

The ChildLoader is unaffected, since it was (and still is) running primarily on the .NET app server. The only difference is that the client is using BeginFetch() instead of Fetch(), so the ChildLoader is running async instead of sync. But that doesn’t affect the way ChildLoader works – so the only impact is to the parent object’s Child property getter.

Thursday, July 01, 2010 12:11:43 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [6]  | 
 Tuesday, June 29, 2010

CSLA includes a control called PropertyStatus, which is somewhat like the Windows Forms ErrorProvider, but far more powerful. It displays error, warning and informational messages from the business object property to which it is bound, and also exposes various metadata properties so other UI elements can bind in interesting ways (like disabling or hiding parts of the UI if the user isn’t authorized to view or edit a property).

The PropertyStatus control has been around for a couple years, in Silverlight 2 and 3 and WPF 3.5.

It broke in Silverlight 4 (but not WPF 4). I spent most of today trying to figure out why. What changed? We’d made a few changes to the control as part of the CSLA 4 project, but nothing really major – certainly nothing that seemed like it should make the control fail in SL4 and work in WPF (it is the same control for both technologies).

After a couple hours of frustration with the debugger, I enlisted the help of my friend and colleague Justin Chase. We fired up SharedView and spent a couple more hours of quality time with the VS10 debugger.

Nothing made sense. The problem was that the control would just disappear. If it was displaying an error icon, and the property was changed, but remained in error, the icon would disappear – the control would vanish.

The control is written using the VisualStateManager (VSM). So whether it is visible or not depends on which visual state is current. States are Valid, Error, Warning, Information, Busy.

There’s exactly one line of code in the control that calls the VMS GoToState() method. We could watch the code set the visual state to Error. And then we could watch the control vanish from the UI shortly thereafter.

Justin had the bright idea to put non-blank content in the Valid and Busy states (because normally they are empty). That worked – it turned out that something was setting the state to Valid.

We searched rather thoroughly through the CSLA codebase trying to find anything that might be using the VSM to set the state to Valid. We commented out most of the code in the control – including the one GoToState() call. We made sure CSLA was not setting the visual state.

And yet the state was being set to Valid.

So we changed the name of the state from Valid to Foo. That fixed the problem. Whatever code (presumably in the Silverlight runtime???) that was setting the state to Valid was no longer impacting us, because we no longer had a Valid state.

I assume this has something to do with the new validation concepts built into Silverlight 4. But talk about nasty! Apparently something in Silverlight runs through the visual tree, setting visual states of controls to “Valid” if that state is defined. I rather suspect there are other “reserved states” as well – but I don’t know for sure.

Of course my theory could be wrong, and perhaps it is yet something else that is setting visual states to Valid – but my money is on the Silverlight 4 validation system…

This is a horrific breaking change from SL3 to SL4, primarily because it isn’t something you’d expect. To have some other code hijack your visual states just because of how they are named – that’s really unpleasant.

So I’m blogging this in the hopes that anyone else using the VSM with a state name of “Valid” can avoid spending as many hours as Justin and I just did trying to figure out the problem…

Tuesday, June 29, 2010 2:58:25 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [3]  | 
 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]  | 
 Friday, May 07, 2010

There’s a lot of understandable buzz about the iPad, including this well-written post that I think conveys something important.

As a Microsoft-oriented technical evangelist I’m now almost constantly asked what I think of the iPad. I’ve spent perhaps a total of 20 minutes with one, so I’m not an expert, but I can confidently say that I found it very pleasant to use, and I think it is a great v1 product.

(as an aside, many people also call it a “Kindle killer”, which I absolutely think it is NOT. It is too heavy, the screen is shiny and backlit and the battery doesn’t last 1-2 weeks – it was almost inconceivable to me that anything could replace real books (but the Kindle did), and the iPad certainly doesn’t compete with real paper or the Kindle)

I think the iPad reveals something very, very important. As does the iPhone, the Android phones and the upcoming Windows Phone 7: most users don’t need a “computer”.

Not a computer in the traditional sense, the way we as software designer/developers think about it.

Given the following:

  • “Instant” on
  • Primarily touch-based UI for the OS
  • Apps (and OS) that is designed for touch through and through (and no non-touch apps)
  • Light weight
  • Good battery life
  • Good networking (including home LAN, corporate domain, network printing, etc)
  • Portable peripherals, and standard connectors (USB, Firewire, ESATA, etc)
  • Docking station capability

I submit that your typical user doesn’t need a traditional computer. Sure, there are the “knowledge workers” in accounting, who push computers harder than developers do, but they aren’t a typical user either.

From what I can see, a typical user spends a lot of time

  • reading and composing email
  • using specialized line of business apps, mostly doing data entry and data viewing/analysis
  • browsing the web
  • playing lightweight casual games (solitaire, Flash-based games, etc)
  • using consumer apps like birthday card makers
  • organizing and viewing pictures and home videos
  • creating simple art projects with drawing apps, etc

None of these things require anything like the new i7 quad core (w/ hyperthreading – so 8 way) laptop Magenic is rolling out to all its consultants. Most users just don’t need that kind of horsepower, and would gladly trade it to get better battery life and more intuitive apps.

Which (finally) brings me to the real point of this post: today’s apps suck (just ask David Platt).

David talks a lot about why software sucks. But I want to focus on one narrow area: usability, especially in a world where touch is the primary model, and keyboard/mouse is secondary.

I have a Windows 7 tablet, which I like quite a lot. But it is far, far, far less usable than the iPad for most things. Why? It really isn’t because of Windows, which can be configured to be pretty touch-friendly. It is because of the apps.

Outlook, for example, is absolutely horrible. Trying to click on a message in the inbox, or worse, trying to click on something in the ribbon – that’s crazy. I’m a big guy, and I have big fingers. I typically touch the wrong thing more often than the right thing…

Web browsers are also horrible. Their toolbars are too small as well. But web pages are as much to blame – all those text links crammed together in tables and lists – it is nearly impossible to touch the correct link to navigate from page to page. Sure, I can zoom in and out, but that’s just a pain.

The web page thing is one area where the iPad is just as bad as anything else. It isn’t the fault of the devices (Windows or iPad), it is the fault of the web page designers. And it really isn’t their fault either, because their primary audience is keyboard/mouse computer users…

And that’s the challenge we all face. If the traditional computing form factor is at its end, and I suspect it is, then we’re in for an interesting ride over the next 5-7 years. I don’t think there’s been as big a user interaction transition since we moved from green-screen terminals to the Windows GUI keyboard/mouse world.

Moving to a world that is primarily touch is going to affect every app we build in pretty fundamental ways. When click targets need to be 2-4 times bigger than they are today, our beautiful high-resolution screens start to seem terribly cramped. And these battery-conserving end user devices don’t have that high of resolution to start with, so that makes space really cramped.

And that means interaction metaphors must change, and UI layouts need to be more dynamic. That’s the only way to really leverage this limited space and retain usability.

For my part, I think Microsoft is in a great place in this regard. Several years ago they introduced WPF and XAML, which are awesome tools for addressing these UI requirements. More recently they streamlined those concepts by creating Silverlight – lighter weight and more easily deployed, but with the same UI power.

I’d be absolutely shocked if we don’t see some sort of Silverlight-based tablet/slate/pad/whatever device in the relatively near future. And I’d be shocked if we don’t see the iPad rapidly evolve based on user feedback.

I really think we’re entering a period of major transition in terms of what it means to be a “computer user”, and this transition will have a deep impact on how we design and develop software for these computing appliances/devices.

And it all starts with recognizing that the type of UI we’ve been building since the early 1990’s is about to become just as obsolete as the green-screen terminal UIs from the 1980’s.

It took about 5 years for most organizations to transition from green-screen to GUI. I don’t think the iPad alone is enough to start the next transition, but I think it is the pebble that will start the avalanche. Once there are other devices (most notably some Silverlight-based device – in my mind at least), then the real change will start, because line of business apps will shift, as will consumer apps.

I’m looking forward to the next few years – I think it is going to be a wild ride!

Friday, May 07, 2010 10:16:26 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [2]  | 
 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]  | 
 Thursday, March 18, 2010

I have an app that uses the SL4 RichTextBox control. It is a nice control, and I’ve been enjoying using it. I even went so far as to convert thousands of rows of HTML to Xaml in my database for use with the RTB.

But the control has a couple changes in the new release candidate that I’m having to work around – and if they are not bugs then I’ll have to write a little app to clean the data in my database.

Prior to the RC the minimum value you could set to the Xaml property was “<Section />”. This was (and is) a pain, because it won’t accept null or string.Empty – so if your actual value is null you need to detect that and change it before trying to set the Xaml property.

But in the RC the minimum value is now “<Section xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"/>”. Not a huge change, but it broke my app of course.

The bigger issue is that prior to the RC the RTB allowed the TextDecorations attribute on the <Section> element. And in fact it generated this attribute when it created Xaml.

In the RC the TextDecorations attribute is no longer valid. It isn’t generated, but more importantly it isn’t allowed, so all my Xaml data is invalid.

This is a bit of code that fixes both issues:

string xaml;
if (e.NewValue == null)
  xaml = string.Empty;
else
  xaml = e.NewValue.ToString();
// RTB won't accept an empty string, so if the value is empty/null
// replace it with the minumum necessary Xaml
if (string.IsNullOrWhiteSpace(xaml))
  xaml = "<Section xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"/>";
// RTB used to support TextDecorations, but now doesn't, so that value
// must be removed to avoid a crash
var pos = xaml.IndexOf(" TextDecorations=");
if (pos >= 0)
{
  var closeQuote = xaml.IndexOf("\"", pos);
  closeQuote = xaml.IndexOf("\"", closeQuote + 1);
  xaml = xaml.Remove(pos, closeQuote - pos + 1);
}
return xaml;

In this case e.NewValue is the Xaml text I’m hoping to put into the control, and the xaml field ends up holding the corrected result.

I’m sure other people moving from the beta to the RC will encounter this same issue. I’m rather hopeful that the TextDecorations thing is a bug so I don’t have to fix all my data, but I suspect it is an intentional breaking change…

Thursday, March 18, 2010 7:25:40 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [2]  | 
 Monday, March 01, 2010
Monday, March 01, 2010 3:04:57 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

Joost van Schaik spent some time figuring out how to get CSLA .NET 3.8.2 to work with Silverlight 4 – which takes a little effort because SL4 changes the way WCF proxies are referenced in the client config file. It is such an odd change that I rather suspect it might be a bug in SL4, but I guess we’ll see what happens as it gets closer to release.

He also wrote a nice blog post summarizing the steps required, which will probably be useful to a number of people:

.NET by Example: Running CSLALight 3.8.2 under .NET 4 and Silverlight 4

Thank you Joost!

Monday, March 01, 2010 3:01:48 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 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]  | 
 Monday, January 11, 2010

If you are doing Silverlight development and have SL unit tests, you should probably take a look at StatLight.

As CSLA .NET developers are aware, when we created CSLA .NET for Silverlight we had to create our own unit test framework, which we made as a separate open source project called UnitDriven.

Creating UnitDriven was necessary to allow us to write exactly the same test code to run on both .NET and SL. After all, CSLA .NET works the same (mostly) on both platforms, so having a unified set of tests was critical. And since SL requires a lot of async testing, we also needed a way to implement async unit tests that are exactly the same on .NET and SL.

The big drawback with UnitDriven is that it has an interactive runner – you actually run the SL test app and run the tests by clicking a button. Very nice in some ways, but not useful for continuous integration (CI). And having CI is so very nice…

StatLight works with numerous technologies, including UnitDriven, and enables CI with Silverlight. Absolutely worth checking out!

Monday, January 11, 2010 3:32:31 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]  | 
 Wednesday, September 02, 2009

I keep plucking away at the MVVM ideas, trying to make sure CSLA .NET allows people to implement the pattern in a smooth manner.

But I keep fighting with UI stuff in the process…

My scenarios center around the ListBox, because I find it to be nicely problematic. And common. Most apps have lists of stuff, and users select n items from the list and then do something with the items. So single-select and multi-select ListBox scenarios, where actions are triggered by the selection changing, or when a button is clicked – this is my current problem domain. Pure UI stuff.

I updated my existing InvokeMethod component to solve these problems, with some challenges, but it works nicely to invoke a method on a ViewModel. I’ve also played with the EventTrigger concepts from Blend 3, creating an Execute trigger action that invokes a method on the ViewModel, but there are some serious limitations here.

One scenario is pretty easy – triggering an action from the SelectionChanged event of the ListBox itself. The InvokeMethod and Execute solutions can both be handled with zero code-behind – just XAML interacting with the ViewModel.

Single-select with InvokeMethod

With InvokeMethod it looks like this:

<ListBox ItemsSource="{Binding Path=Model}"
         ItemTemplate="{StaticResource DataList}"
         Name="DataListBox"
         csla:InvokeMethod.Target="{Binding Source={StaticResource ListModel}}"
         csla:InvokeMethod.TriggerEvent="SelectionChanged"
         csla:InvokeMethod.MethodName="ShowItem"
         csla:InvokeMethod.MethodParameter="{Binding RelativeSource={RelativeSource Self}, Path=SelectedItem}" />

And the ViewModel has a ShowItem() method like this:

public void ShowItem(Data methodParameter)
{
  // process methodParameter
}

Very simple and easy, and I like it a lot – except that InvokeMethod is fairly verbose and isn’t supported by Blend. I do like that the selected item is passed into the method as a strongly typed parameter though.

Single-select with event trigger

Using the event trigger model (which is supported by Blend) the ListBox looks like this:

<ListBox ItemsSource="{Binding Path=Model}"
         ItemTemplate="{StaticResource DataList}"
         SelectedItem="{Binding Path=SelectedData, Mode=TwoWay}"
         Name="DataListBox">
  <i:Interaction.Triggers>
    <i:EventTrigger EventName="SelectionChanged">
      <csla:Execute MethodName="ShowItem2" />
    </i:EventTrigger>
  </i:Interaction.Triggers>
</ListBox>

Notice that the ListBox.SelectedItem property is now bound to the SelectedData ViewModel property:

public static readonly DependencyProperty SelectedDataProperty =
    DependencyProperty.Register("SelectedData", typeof(Data), typeof(DataListViewModel), new PropertyMetadata(null));
public Data SelectedData
{
  get { return (Data)GetValue(SelectedDataProperty); }
  set { SetValue(SelectedDataProperty, value); OnPropertyChanged("SelectedData"); }
}

And the ViewModel method looks like this:

public void ShowItem2(object sender, Csla.Silverlight.ExecuteEventArgs e)
{
  // process this.SelectedData
}

While this is supported by Blend, I dislike the fact that the command method (ShowItem2()) has an invisible side-effect in that it requires the SelectedData property to be set before it will work. No one could know this without looking at the code or at documentation, so the overall readability is reduced in my opinion.

However, both solutions end up with a ShowItem() method that has the strongly-typed selected item, and the XAML uses binding to interact with the ViewModel in a reasonably clean manner – so I think either way is perfectly acceptable.

Multi-select with InvokeMethod

The multi-select ListBox scenario requires a Button (or similar control). The user selects multiple items in the ListBox, then clicks the Button to trigger processing of those items.

This scenario is not nearly so nice. Partly this is because of the way the ListBox works I think (or binding). The problem is that the SelectedItems property of the ListBox returns an ObservableCollection<object>, and when a binding is established between SelectedItems and another property it gets a reference to a collection that is not the collection you ultimately want.

In other words, when the form loads, SelectedItems points to an empty collection, and anything bound to it gets connected to that collection. When items are later selected the SelectedItems property seems to end up pointing to a different collection, and the binding has no idea this happened. The binding is still pointing to the original empty collection.

This means the binding to SelectedItems must be refreshed at the time the event trigger occurs, such as the Button control’s Click event.

I made InvokeMethod take care of this, so when using InvokeMethod the ListBox looks like this:

<ListBox ItemsSource="{Binding Path=Model}"
         ItemTemplate="{StaticResource DataList}"
         SelectionMode="Multiple"
         Name="DataListBox" />

And the Button looks like this:

<Button Content="Process items"
        csla:InvokeMethod.TriggerEvent="Click"
        csla:InvokeMethod.MethodName="ProcessItems"
        csla:InvokeMethod.MethodParameter="{Binding ElementName=DataListBox, Path=SelectedItems}"/>

And the ViewModel method looks like this:

public void ProcessItems(System.Collections.ObjectModel.ObservableCollection<object> methodParameter)
{
  // process methodParameter
}

This only works because InvokeMethod refreshes the binding of its MethodParameter property when it gets the Click event from the Button. If it just took the normal binding value, it would always return an empty collection…

But the fact is that InvokeMethod does make this work in a very smooth and easy manner, allowing the ViewModel to implement a method that accepts the list of selected items as a parameter.

Multi-select with event trigger

Using the trigger action approach things are really messy, because there’s no way to force a refresh of anything that is bound to SelectedItems.

Worse, you can’t actually bind SelectedItems on the ListBox itself like you bind SelectedItem. In other words, the ListBox ends up looking like this:

<ListBox ItemsSource="{Binding Path=Model}"
         ItemTemplate="{StaticResource DataList}"
         SelectionMode="Multiple"
         Name="DataListBox">
</ListBox>

Where you’d want to bind SelectedItems to a property of the ViewModel, that’s not possible.

So I thought I’d use a bit of a hack and bind it to the Tag property of the Button:

<Button Content="Process items"
        Tag="{Binding ElementName=DataListBox, Path=SelectedItems}">
  <i:Interaction.Triggers>
    <i:EventTrigger EventName="Click">
      <csla:Execute MethodName="ProcessItems2" />
    </i:EventTrigger>
  </i:Interaction.Triggers>
</Button>

While this “works”, it doesn’t really. The problem is that the binding is established when SelectedItems is an empty collection, and it never changes. So this is NOT a useful way to get the list of selected items.

In the end, the solution appears to be that the ViewModel must know that it is dealing with a ListBox so it can get the items directly in the command method. That means the Button must provide a link to the ListBox (via Tag):

<Button Content="Process items"
        Tag="{Binding ElementName=DataListBox}">

This way the command method can interact with the Tag property to get a reference to the ListBox to get at the SelectedItems collection:

public void ProcessItems2(object sender, Csla.Silverlight.ExecuteEventArgs e)
{
  var listBox = ((System.Windows.Controls.Control)e.TriggerSource).Tag as System.Windows.Controls.ListBox;
  var selection = listBox.SelectedItems;
  // process selection
}

This is bad because now the ViewModel must know details about the control in the View. It is directly using the ListBox type, which means that the XAML can’t be easily changed to use some other type of list-oriented UI control – at least not without coming back here and changing this code.

I guess one solution would be to create a custom Button subclass that refreshes the binding of its Tag property when the button is clicked – but that’s not a good general solution by any means…

So in the multi-select scenario InvokeMethod is a decent solution, but trigger actions really fall down and the solution seems very inadequate. I think this is primarily due to the implementation of ListBox.SelectedItems, but I also think it is safe to assume that other UI controls will have similarly ill-behaved properties that make trigger actions harder to use than they should be.

Wednesday, September 02, 2009 3:25:26 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Friday, August 14, 2009

Based on my recent posts regarding Silverlight, MVVM and invoking methods on arbitrary target objects, a couple people suggested that behaviors or trigger actions might be a good solution.

These are new concepts introduced through the System.Windows.Interaction assembly that comes with Expression Blend 3. That’s somewhat of a drawback, since this means a developer is required to install Blend 3 to get the assembly before these features are available. It would be nicer if they were part of the standard Silverlight (and WPF) development platform.

The other challenge I’ve encountered in working with this technology is a limitation when it comes to data binding. Silverlight only full binds with dependency properties of FrameworkElement objects. Since classes like TriggerAction<T> don’t inherit from FrameworkElement, their dependency properties aren’t bindable. This means you can’t define a property on a trigger and then bind it to other elements in the UI, which is really an unfortunate limitation.

For example, I created an Execute trigger action that defines MethodName and MethodParameter properties. If I have a ListBox and a Button, and I want the Button to trigger some method that acts on the SelectedItem property of the ListBox, what I’d really like to do is this:

<Button Content="Refresh">
  <i:Interaction.Triggers>
    <i:EventTrigger EventName="Click">
      <csla:Execute MethodName="Load" MethodParameter="{Binding ElementName=MyListBox, Path=SelectedItem}" />
    </i:EventTrigger>
  </i:Interaction.Triggers>
</Button>

(in this code the ‘i’ prefix refers to System.Windows.Interactivity from Blend 3 and the ‘csla’ prefix refers to Csla.Silverlight from CSLA .NET)

Unfortunately this won’t get past the Silverlight XAML parser, because a binding expression isn’t allowed for MethodParameter…

I also wanted to implement a MethodTarget property so the Execute trigger could invoke methods on some object other than the current DataContext. Unfortunately that puts us back to needed the ability to use binding to specify the value of MethodTarget, which isn’t possible. So my current implementation can only invoke methods on the DataContext of the associated control (the Button in this case).

To get around the MethodParameter limitation I’m using a Tag hack

<Button Content="Refresh" Tag="{Binding ElementName=NewIdTextBox, Path=Text}">
  <i:Interaction.Triggers>
    <i:EventTrigger EventName="Click">
      <csla:Execute MethodName="Load" />
    </i:EventTrigger>
  </i:Interaction.Triggers>
</Button>

When the Execute trigger invokes the method, it passes an ExecuteEventArgs parameter to the method, which includes a TriggerSource property of type FrameworkElement. This means the method, in the view model class, can access the Tag property of the associated control (the Button), which can be bound because the Button is a FrameworkElement:

public void Load(object sender, ExecuteEventArgs e)
{
  var tag = e.TriggerSource.Tag.ToString();
  int id = 0;
  if (!string.IsNullOrEmpty(tag))
    id = int.Parse(tag);
  Load(id);
}

Sure this is somewhat hacky, but since the trigger action can’t define bindable properties of its own, this seems like a workable solution.

Friday, August 14, 2009 12:44:31 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Tuesday, August 04, 2009

CSLA .NET 3.6 introduced the InvokeMethod component for Silverlight, which was intended to replace at least the basic WPF commanding functionality I tend to use to trigger actions on a CslaDataProvider when buttons are clicked. And it did that.

It turns out however, that with a few tweaks, InvokeMethod is much more broadly useful than just triggering actions on a CslaDataProvider. In a more general sense, InvokeMethod can be used to call a method on nearly any object in response to nearly any event being raised by a UI control.

I’ve been reworking InvokeMethod quite a bit over the past few days, and whatever I end up doing will be in CSLA .NET 3.8. And it will be a breaking change over the 3.6 and 3.7 functionality, which is unfortunate, but I think it is worth it.

This blog post is not the final word, just kind of a “state of the control” post to solicit thoughts and feedback as I work on version 3.8.

In the new model, InvokeMethod can still invoke methods on a CslaDataProvider, so no functionality is lost.

But in the new model, InvokeMethod can invoke methods on other arbitrary objects, as long as they can be described through a binding expression. In other words, any bindable object that has a method becomes a valid target. And the range of trigger events is much broader; in fact any event should now work, though I’ve only tested a handful of common events (click, doubleclick, selectionchanged, etc).

Using some data binding trickery I’ve made the Target property (used to be the Resource property) optional. If you don’t set the Target property, InvokeMethod will target the DataContext of the control to which it is attached. This is not so useful with a data provider model, but is very useful with a ViewModel model.

Simple scenario

So an example of triggering an action on a ViewModel when a button is clicked:

<Button Content="Refresh"
        csla:InvokeMethod.TriggerEvent="Click"
        csla:InvokeMethod.MethodName="Load" />

When the button is clicked a Load() method is invoked on the current DataContext, which is probably a ViewModel class with a Load() method:

public class DataListViewModel : CslaViewModel<DataList>
{
  public void Load()
  { 
  }
}

That’s the simplest example, and could be handled by commanding in WPF.

ListBox doubleclick scenario

A more interesting example is where the UI needs to do something in response to a doubleclick of an item in a ListBox. This is interesting because there’s a temporal issue where the user could select an item in the list, and not doubleclick on it ever, or for a long time. In my mind, the ViewModel would handle the doubleclick through a method that accepts the selected item as a parameter:

public void ProcessItem(Data item)
{
}

That implies that InvokeMethod can pass the selected item as a parameter, and in the current incarnation it can do this:

<ListBox
         ItemsSource="{Binding Path=Model}"
         ItemTemplate="{StaticResource DataList}"
         csla:InvokeMethod.TriggerEvent="MouseDoubleClick"
         csla:InvokeMethod.MethodName="ProcessItem"
         csla:InvokeMethod.MethodParameter="{Binding SelectedItem, RelativeSource={RelativeSource Self}}"/>

The ambient DataContext here is the ViewModel object, and you can see that the ListBox loads its items from the Model property (where the Model is a collection of Data objects). The only really interesting thing here is that the MethodParameter property is using binding to pick up the SelectedItem property from the UI control – so from the ListBox. This directly meets my requirement of being able to pass the selected item to the ViewModel method.

The ViewModel doesn’t care what type of UI control is used, as long as it gets a selected Data item. This also means the ViewModel is quite testable, because it is a simple method that accepts a strongly typed parameter.

MultiSelect ListBox scenario

This even works with a multiselect ListBox control (though my solution seems a bit messy).

Obviously this requires a Button or some other control outside the ListBox, since a multiselect ListBox doesn’t raise events quite the same way. The user gets to select arbitrary items in the ListBox, then click a Button to trigger processing of all selected items.

The ViewModel has a method to handle this:

public void ProcessItems(ObservableCollection<object> items)
{
}

And the XAML invokes this method from the Button (assuming the ListBox has an explicit name):

<Button Content="Process items"
        csla:InvokeMethod.TriggerEvent="Click"
        csla:InvokeMethod.MethodName="ProcessItems"
        csla:InvokeMethod.MethodParameter="{Binding ElementName=DataListBox, Path=SelectedItems}"/>

Again, the ViewModel just accepts a (relatively) strongly typed parameter, not caring about the type of UI control that generated that value. There’s no real type-level coupling between the XAML and the ViewModel.

In all these cases the XAML knows nothing more than that there’s a Model to bind to, and some actions (methods) on the ViewModel that can be invoked.

And the ViewModel knows nothing more than that it is being invoked by something. XAML, a test harness, it doesn’t really matter, it just does its thing.

Whether this is “MVVM” or not, I think it is pretty darn cool :)

Tuesday, August 04, 2009 9:30:44 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

I’m trying to do something that seems like it should be so simple and obvious.

I have an attached property, MethodParameter, which I’m applying to a Button, but I’m binding to a ListBox control:

<Button Content="Process items"
        csla:InvokeMethod.TriggerEvent="Click"
        csla:InvokeMethod.MethodName="ProcessItems"
        csla:InvokeMethod.MethodParameter="{Binding ElementName=DataListBox, Path=SelectedItems}"/>

This works, and does bind. But it appears to bind only when the Button control is instantiated, not when the Click event is handled.

In other words, the binding occurs. The user then interacts with the ListBox control and selects some items, and then clicks the Button. That triggers the Click event, which causes the InvokeMethod object to actually use the MethodParameter value.

However, at that point in time the binding appears to still be using the original collection from when the form was being loaded, and so the collection is empty.

If I actually examine the SelectedItems property it has multiple items of course – but it is a different collection than the one from when the form was loaded.

In other words, ListBox seems to create a whole new collection each time SelectedItems is invoked, and that’s apparently totally messing up data binding.

I don’t know if this problem is unique to ListBox, or if it is a broader problem with element binding, but it is making my life very unpleasant…

To solve this, I’m hijacking the binding process like this:

public static object GetMethodParameter(UIElement ctrl)
{
  var fe = ctrl as FrameworkElement;
  if (fe != null)
  {
    var be = fe.GetBindingExpression(MethodParameterProperty);
    var dataItem = be.DataItem;
    string path = be.ParentBinding.Path.Path;
    if (dataItem != null && !string.IsNullOrEmpty(path))
    {
      var pi = Csla.Reflection.MethodCaller.GetProperty(dataItem.GetType(), path);
      return Csla.Reflection.MethodCaller.GetPropertyValue(dataItem, pi);
    }
  }
  return ctrl.GetValue(MethodParameterProperty);
}

Basically I’m using reflection to manually go get the property value of the target object. This works, but feels really wrong.

If we’re dealing with a nasty idiosyncrasy of the ListBox I can probably restrict this to only be messy when talking to a ListBox control, but I rather suspect ListBox isn’t the only issue.

I’ve tried all sorts of things on the binding expression - Mode=TwoWay and BindsDirectlyToSource=True. But they had no impact. It appears that the binding gets a reference to the property value when it is created and never knows enough to re-read the value later when I actually need it.

Any ideas?

Tuesday, August 04, 2009 9:13:49 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Friday, July 31, 2009

There’s no DataContextChanged event in Silverlight. And that’s a serious problem for creating certain types of control, because sometimes you just need to know when your data context has been changed!

In my case I have the Csla.Silverlight.PropertyStatus control, which listens for events from the underlying data context object so it knows when to refresh the UI. If the data context changes, PropertyStatus needs to unhook the events from the old object, and hook the events on the new object. That means knowing when the data context has changed.

In version 3.6 we implemented a Source property and required that the data source be explicitly provided. That was unfortunate, but since it was our own property we could detect when the value was changed.

I recently did a bunch of research into this topic, trying to find a better answer. I’d rather hoped that Silverlight 3 would provide an answer, but no such luck…

It turns out that there’s a hack solution that does work. Actually there are a few, but most of them seem terribly complex, and this one seems somewhat easier to follow.

The basic idea is to create a data binding connection between your DataContext property and another of your properties. Then when DataContext changes, data binding will change your property, and you can detect that your property has changed. Rather a hack, but it works.

In its distilled form, the structure looks like this. First there’s the control class, which inherits from some framework base class:

public class PropertyStatus : ContentControl
{

Then there’s the constructor, which includes a handler for the Loaded event, which is where the real magic occurs:

public PropertyStatus()
{
  Loaded += (o, e) =>
  {
    var b = new System.Windows.Data.Binding();
    this.SetBinding(SourceProperty, b);
  };
}

When the control is loaded, a new Binding object is created. This Binding object picks up the default DataContext value. The Source property is then bound to this new Binding, which effectively binds it to the default DataContext. Definitely a bit of hackery here…

Obviously this means there’s a Source property – or at least the shell of one. I don’t really want a visible Source property, because that would be confusing, but I must at least implement the DependencyProperty as a public member:

public static readonly DependencyProperty SourceProperty = DependencyProperty.Register(
  "Source",
  typeof(object),
  typeof(PropertyStatus),
  new PropertyMetadata((o, e) => ((PropertyStatus)o).SetSource(e.OldValue, e.NewValue)));

I do have a private Source property, though I’ve never found that it is invoked (breakpoints in the get/set blocks are never hit):

private object Source
{
  get { return GetValue(SourceProperty); }
  set
  {
    object old = Source;
    SetValue(SourceProperty, value);
    SetSource(old, value);
  }
}

The lambda in the static DependencyProperty declaration calls SetSource(), and this is my “data context changed” notification:

private void SetSource(object old, object @new)
{
  DetachSource(old);
  AttachSource(@new);
...
}

I suppose this could be generalized into a base class, where SetSource() really raises a DataContextChanged event. I didn’t find the need for that, as I’ve only got a couple controls that need to know the data context has changed, and they inherit from different framework base classes.

The point being, with a little data binding hackery, it is not terribly hard to implement a method that is invoked when the data context changes. Not as nice as having the actual event like in WPF, but much nicer than forcing the XAML to explicitly set some data source property on every control.

(for those interested, this will be changed in CSLA .NET 3.7.1, and it will be a breaking change because the Source property will go away)

Friday, July 31, 2009 3:41:57 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

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]  | 
 Tuesday, July 21, 2009

I have released CSLA .NET version 3.7, with support for Silverlight 3.

This is really version 3.6.3, just tweaked slightly to build on Silverlight 3. It turns out that the Visual Studio upgrade wizard didn’t properly update the WCF service reference from Silverlight 2 to Silverlight 3, so I had to rereference the data portal service. I also took this opportunity to fix a couple minor bugs, so check the change logs.

  1. If you are a CSLA .NET for Windows user, there’s just one minor change to CslaDataProvider, otherwise 3.7 really is 3.6.3.
  2. If you are a CSLA .NET for Silverlight user, there are a couple minor bug fixes in CslaDataProvider and Navigator, and 3.7 builds with Silverlight 3. Otherwise 3.7 is 3.6.3.

In other words, moving from 3.6.3 to 3.7 should be painless.

Downloads are here:

At this point the 3.6.x branch is frozen, and all future work will occur in 3.7.x until I start working on 4.0 later this year.

Tuesday, July 21, 2009 9:45:08 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Friday, July 10, 2009

You’ve probably noticed that Microsoft released Silverlight 3 today. More information can be found at

I’ve put a very stable beta of CSLA .NET 3.7 online as well

Version 3.7 is really the same code as 3.6.3, but it builds with the Silverlight 3 tools for Visual Studio 2008. So while I’m calling it a beta, it is really release-quality code for all intents and purposes.

If you are a Windows/.NET user of CSLA .NET, you’ll find that all future bug fixes, enhancements and so forth will be in version 3.7. Version 3.6.3 is the last 3.6 version.

If you are a Silverlight user of CSLA .NET, and continue to use the Silverlight 2 tools, 3.6.x is still for you, but I plan to address only the most critical bugs in that version – and I’m not currently aware of anything at that level. So 3.6.3 is really the end for Silverilght 2 as well.

In short, 3.7 is now the active development target for any real work, and you should plan to upgrade to it when possible.

Friday, July 10, 2009 11:46:31 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Wednesday, July 08, 2009

I’ve observed, in broad strokes, a pattern over the past 20 years or so.

At one time there was DOS (though I was a happy VAX/VMS developer at the time, and so didn’t suffer the pain of DOS).

Then there was Windows, which ran on DOS (sadly I did have to deal with this world).

Then we booted into Windows, which had a “DOS command prompt” window, so DOS ran on Windows (and the world got better).

Windows lasted a long time, but then came .NET, which ran on Windows.

I always expected that we’d see the time come when we’d boot into .NET, and Windows would run on .NET.

I no longer think that’s likely. Which is too bad, because that would have been cool.

But in the late 1990’s there was the very real possibility that the browser would become the OS. The dot-bomb crash eliminated that debate, robbing the browser-based company’s of their funding and allowing Windows, Linux and Mac OS to continue to dominate.

In the past 2-3 years though, we’ve seen something different. Flash/Flex/Air, Silverlight and Google Gears have shown that the “browser as the OS” idea didn’t go away, it just went to sleep for a while.

Now I’ll suggest that there are really two camps here. There’s the Google camp that really wants the browser as the OS. And there’s the Adobe/Microsoft camp (can I put them together?) that realizes that the technology of the web is really a stack of hacks, and that it is high time to move on to the next big thing. My bias is clearly toward the next big thing, and has been since the web started being misused as an app platform in the 1990’s. They are proposing the mini-runtime-as-the-OS concept, using the browser as a simple launch-pad for the real runtime.

But either way, the concept of a “client OS” has been fading for some years now in my view. Or conversely, the concept of “all my apps run in ‘the browser’” has been ascending steadily and rapidly over the past 2-3 years.

And I’m OK with this, because we’re not talking about reducing all apps to stupid browser-based mainframe-with-color architectures like the web has tried to do for over a decade.

No! We’re talking about full-blown smart-client technologies like Silverlight, where the client application can be an edge application in a service-oriented system, or the client tier of an n-tier application. We’re talking about the resurgence of the incredible productivity and scalability offered by the n-tier technologies of 1997-98. We’re talking about getting our industry back on track, so we can look back at 1999-2009 as nothing more than a “lost decade”.

(can you tell I think the terminal-based browser model is really lame?)

Does this mean that Windows, Mac OS and Linux become less relevant? I think so. Does this mean that Silverlight is the most important technology Microsoft is currently building? I think so.

Consider that Silverlight, in a <5 meg runtime, provides everything you need to build most types of powerful smart-client business applications. And consider that these applications auto-deploy and auto-update in a way that the user never sees the deploy/update process. Totally smooth and transparent.

Consider that you can write your C# or VB code and run it on the client. Or on the server. Or both (see CSLA .NET for Silverlight if you want to know more). You don’t need to learn JavaScript. You don’t need a totally different language and runtime on the client from the server. Silverlight provides a decent level of consistency between client and server, so you can reuse code, and absolutely reuse skills, knowledge and tools.

Google is totally on the bandwagon of course. Many people have seen their strategy for months, if not years. And we’re now seeing it come through, as they start to make their browser is the OS play in earnest.

What’s interesting to me, is that in either case – the browser-as-OS (Google) or the mini-runtime-as-OS (Silverlight) – leaves the previous generation OS concept (Windows/Mac/Linux) out of the loop.

Windows 7, perhaps the best version of Windows ever created, might be the last great hurrah for the legacy OS concept.

I mean all we need now is a Silverlight-based version of Office (to compete with Google Apps) and the underlying “OS” beneath Silverlight becomes rapidly irrelevant...

Wednesday, July 08, 2009 10:45:44 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Wednesday, June 10, 2009

The CSLA .NET for Silverlight video series is now complete! Segment 7, covering authentication and authorization, is now online and this completes all video segments – over 8 hours of content!

The CSLA .NET for Silverlight video series is an invaluable resource for getting started with CSLA .NET on the Silverlight platform. The series starts with the basics of setting up a Silverlight solution, covers the creation of client-only applications using CSLA .NET and then moves to a discussion of creating 2-, 3- and 4-tier applications using CSLA .NET on the client and on the server(s).

Segments 5 and 6 cover CSLA .NET object stereotypes and data access respectively. These segments are also available for purchase as individual videos, because they are useful to any CSLA .NET developer, including ASP.NET, WPF, Windows Forms and more.

Segment 7 covers the use of Windows authentication, MembershipProvider authentication and custom authentication using CSLA .NET for Silverlight against an ASP.NET web or application server. It also covers the use of per-property and per-type authorization in business classes, and talks about how the PropertyStatus, ObjectStatus and CslaDataProvider controls interact with those rules.

Buy the video series before June 20 and save $50 off the regular purchase price of $300.

Wednesday, June 10, 2009 1:09:50 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Friday, June 05, 2009

Segment 6 of the CSLA .NET for Silverlight video series is now available.

Also, both the Business Object Types and N-Tier Data Access videos (segments 5 and 6) can now be purchased separately, as each of these segments contains information valuable to any CSLA .NET developer.

Segment 6 details the various options supported by CSLA .NET for data access in n-tier scenarios. Watching this video, you will learn how to put data access code into your business class, or into a separate data access assembly, along with the pros and cons of each technique. You will also learn about the ObjectFactory attribute and base class, that can be used to create pluggable data access layers for an application.

This video is 1 hour and 49 minutes in length, so you can imagine just how much great content exists!

Not only does the video talk about editable objects and child objects and lists, it covers the common parent-child-grandchild scenario.

And it includes data access code using raw ADO.NET (for performance and long-term stability) as well as a complete walkthrough using ADO.NET Entity Framework as a data access layer.

The pre-release purchase offer of $50 off the regular price of $300 is still available. If you buy before June 20, your price is $250 for the entire video series, and you get the first 6 (of 7) video segments, nearly 7 hours of content, immediately!

And again, you can purchase segments 5 and 6 individually if you are not interested in the complete Silverlight video series.

Friday, June 05, 2009 4:30:24 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Tuesday, June 02, 2009

Segment 5 of the CSLA .NET for Silverlight video series is now available. This segment covers all the CSLA .NET object stereotypes, including:

  • Editable objects (single and list)
  • Read-only objects (single and list)
  • Name/value list
  • Command
  • Dynamic list (EditableRootListBase)
  • etc

The focus is primarily on the business class structure and features, with some time spent discussing XAML data binding and the use of the CslaDataProvider and other UI controls.

This segment is 1:37 hours in length, yes, 97 minutes. The vast majority of this time is in Visual Studio, walking through code and providing information about class development that will be immediately useful to you.

Because segments 6 and 7 are not yet complete, I’m offering a pre-release purchase offer of $50 off the regular price of $300. If you buy before June 20, your price is $250 for the entire video series, and you get the first five segments, over 5 hours of content, immediately!

 

Also, I’m looking for feedback. Most of the content in segment 5 (and in segment 6) applies to any user of CSLA .NET – Silverlight, WPF, ASP.NET, Windows Forms, etc. Yes, there’s some Silverlight/XAML specific data binding discussion, but most of the video is focused on business class implementation.

If you are not a Silverlight developer, would you be interested in purchasing these two video segments even if some of the content didn’t apply to you? Let me know what you think, thanks!

Tuesday, June 02, 2009 7:50:02 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Monday, May 04, 2009

The 4th video in the CSLA .NET for Silverlight video series is now available. This is 65 minutes of in-depth content covering the creation of 2-, 3- and 4-tier applications using CSLA .NET for Silverlight.

If you’d like to get a better idea of the structure, style and quality of the video series you can download a FREE promotional montage. This promotional video includes lecture and coding content, providing an example of everything you’ll see in the full video.

The N-Tier Architecture segment covers a lot of ground, including these topics:

  1. How to share code files and objects between a Silverlight client and .NET server
  2. How to have server-only and client-only sections in your business layer
  3. How to configure an ASP.NET server for the Silverlight data portal
  4. How to configure the Silverlight client to use a remote data portal
  5. How to use the MobileFactory attribute to create an observer object to validate inbound client requests on the web server
  6. How to set up the web server to act as a "bridge", routing all client calls to a real application server behind a second firewall

Purchase the video series at http://store.lhotka.net

Download the content from http://download.lhotka.net/default.aspx?t=slvid01

Buy before June 1 to take advantage of a special early adopter offer: $100 savings off the regular purchase price. That's a 33% savings!

Monday, May 04, 2009 9:04:11 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Friday, April 17, 2009

I have the first three segments of the CSLA .NET for Silverlight video series available now, and so I'm extending a special pre-purchase offer to anyone who wants to get access to the content as it becomes available.

Buy now and save $100 off the regular purchase price. This special offer gives you immediate access to the first three video segments, and will give you access to the remaining video segments as they become available. You can be among the first to have access to this great content!

You can get an idea of the video style with this promo:

Here is a summary of all seven video segments:

Introduction
In this video you will become familiar with the CSLA .NET framework's vision, goals and overall scope. You will be introduced to the various architectures supported by CSLA .NET for Silverlight, and the requirements necessary to build Silverlight and CSLA .NET for Silverlight applications.

The Basics
This video details the basic steps of creating a CSLA .NET business object that interacts with a server-side web service to get its data. The process of using data binding to connect the object to the Silverlight UI is also covered. At the end of this video you will understand all the basic steps and coding structures necessary to build a simple CSLA .NET for Silverlight application.

Client-only Architectures
This video covers the various client-only scenarios supported by CSLA .NET for Silverlight, including true client-only applications and “edge” applications that interact with remote services. This video builds on The Basics to dive deeper into the various options for building client-only applications.

N-tier Architectures - coming soon
In this video you will learn how to build 2-, 3- and 4-tier applications using CSLA .NET for Silverlight. CSLA .NET allows your UI, business object and data access code to remain the same in all these configurations, but there are numerous configuration options and choices you can make to optimize how your application works in each of these scenarios.

Business Object Types - coming soon
In this video you will learn how to implement each of the business object stereotypes supported by CSLA .NET. These include editable objects, lists of objects, read-only objects, read-only lists, name/value lists, command objects and more. At the end of this video you will understand the purpose behind each stereotype, and the coding structure to use when building business objects for each stereotype.

N-tier Data Access - coming soon
This video details the various options supported by CSLA .NET for data access in n-tier scenarios. You will learn how to put data access code into your business class, or into a separate data access assembly, along with the pros and cons of each technique. You will also learn about the ObjectFactory attribute and base class, that can be used to create pluggable data access layers for an application.

Authentication and Authorization - coming soon
In this video you will learn about the various authentication and authorization techniques supported by CSLA .NET for Silverlight. Authentication options include Windows, ASP.NET Membership Provider and custom authentication. Authorization is the same as CSLA .NET for Windows, and includes per-property and per-type authorization, along with Silverlight UI controls to simplify the creation of your interface

Friday, April 17, 2009 9:03:51 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Tuesday, March 31, 2009

CSLA .NET 3.6.2 is now available for download.

This is the second point release of CSLA .NET 3.6, and it includes a number of bug fixes, but more importantly there are a number of new features and enhancements based on feedback from users of version 3.6 over the past four months.

Highlights include:

  • For both Windows and Silverlight
    • New methods on the ObjectFactory base class to better enable creation of a DAL object
    • Better support for lazy loaded fields, where an exception is thrown if the field is mis-used accidentally (thus reducing bugs)
    • ErrorDialog control for WPF and Silverlight to enable XAML-only handling of exceptions from CslaDataProvider
    • CslaDataProvider now has a Saved event to simplify some UI scenarios
    • RegisterProperty() now accepts a lambda expression to identify the property name, allowing the compiler to check the name, and avoiding the use of the string literal
    • MobileDictionary type, so you can create a dictionary that serializes between Silverlight and .NET
  • For Silverlight only
    • Better type name resolution, so you can now specify a type by "Namespace.Class, Assembly" without supplying the generic "Version=..." text
    • New InventoryDemo sample project (C# only right now - it is a work in progress)
    • Code snippets for async factory and data access methods
  •  

    On a related note, the first segment of my CSLA .NET for Silverlight video series is complete, and I’m nearly done with the web infrastructure for the download site. You can get a summary of the video series content on the CSLA .NET for Silverlight video download page.

    Once I get the store and download site complete, you’ll be able to purchase “early adopter'” access to the series – which means you’ll get access to each video segment as soon as it comes online. Look for this in the next couple weeks!

    Tuesday, March 31, 2009 3:59:43 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
     Wednesday, March 25, 2009

    Google tells me that issues with the Silverlight ComboBox control are widespread and well known. It also tells me that there are few solid solutions out there if you want data binding to work with the Silverlight ComboBox in a simple, reliable manner.

    Perhaps the best post on the topic is this one, but this particular code example doesn’t work in all cases (specifically not inside a DataTemplate, and as a form loads and gets async data).

    After wasting more time than I care to consider, I believe I have a more complete solution. Though it isn’t perfect either, it does appear to work nicely with CSLA .NET NameValueListBase objects, and inside DataTemplate elements, which is really what I was after.

    As others have pointed out, the solution is to subclass ComboBox and add SelectedValue and ValueMemberPath properties to the control. The trick is to catch all the edge cases where these new properties, and the pre-existing SelectedItem and Items properties, might change. I may not have them all either, but I think I handle most of them :)

    To use the new control, you need to bring in the namespace containing the control, and then use XAML like this:

    <this:ComboBox Name="ProductCategoryComboBox"
                   ItemsSource="{Binding Source={StaticResource ProductCategories},Path=Data}"
                   SelectedValue="{Binding Path=CategoryId, Mode=TwoWay}"
                   ValueMemberPath="Key"
                   DisplayMemberPath="Value"/>

    At least in my code, you must set the ValueMemberPath, though I’m sure the code could be enhanced to avoid that requirement. The bigger thing is that the SelectedValue binding must have Mode=TwoWay or the binding won’t work reliably. Even if you are using the ComboBox for display-only purposes, the Mode must be TwoWay.

    Also I should point out that this XAML is using the CslaDataProvider control to get the data for the ItemsSource property. You could use other techniques as well, but I like the data provider model because it shifts all the work into XAML, so there’s no code required in the presentation layer. The ProductCategories resource is a CslaDataProvider control that retrieves a NameValueListBase object containing a list of items with Key and Value properties.

    Here’s the control code:

    public class ComboBox : System.Windows.Controls.ComboBox
    {
      public ComboBox()
      {
        this.Loaded += new RoutedEventHandler(ComboBox_Loaded);
        this.SelectionChanged += new SelectionChangedEventHandler(ComboBox_SelectionChanged);
      }

      void ComboBox_Loaded(object sender, RoutedEventArgs e)
      {
        SetSelectionFromValue();
      }

      private object _selection;

      void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
      {
        if (e.AddedItems.Count > 0)
        {
          _selection = e.AddedItems[0];
          SelectedValue = GetMemberValue(_selection);
        }
        else
        {
          _selection = null;
          SelectedValue = null;
        }
      }

      private object GetMemberValue(object item)
      {
        return item.GetType().GetProperty(ValueMemberPath).GetValue(item, null);
      }

      public static DependencyProperty ValueMemberPathProperty =
        DependencyProperty.Register("ValueMemberPath", typeof(string), typeof(InventoryDemo.ComboBox), null);

      public string ValueMemberPath
      {
        get
        {
          return ((string)(base.GetValue(ComboBox.ValueMemberPathProperty)));
        }
        set
        {
          base.SetValue(ComboBox.ValueMemberPathProperty, value);
        }
      }

      public static DependencyProperty SelectedValueProperty =
        DependencyProperty.Register("SelectedValue", typeof(object), typeof(InventoryDemo.ComboBox),
        new PropertyMetadata((o, e) =>
        {
          ((ComboBox)o).SetSelectionFromValue();
        }));

      public object SelectedValue
      {
        get
        {
          return ((object)(base.GetValue(ComboBox.SelectedValueProperty)));
        }
        set
        {
          base.SetValue(ComboBox.SelectedValueProperty, value);
        }
      }

      private void SetSelectionFromValue()
      {
        var value = SelectedValue;
        if (Items.Count > 0 && value != null)
        {
          var sel = (from item in Items
                     where GetMemberValue(item).Equals(value)
                     select item).Single();
          _selection = sel;
          SelectedItem = sel;
        }
      }

      protected override void OnItemsChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
      {
        base.OnItemsChanged(e);
        SetSelectionFromValue();
      }
    }

    It seems strange that the standard control doesn’t just do the right thing – but we must live in the world that is, not the world we would like to see…

    Wednesday, March 25, 2009 10:01:05 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
     Sunday, March 22, 2009

    I have made CSLA .NET 3.6.2 RC0 available for download.

    Version 3.6.2 includes a number of bug fixes, but more importantly includes a number of new features and enhancements based on feedback from users of version 3.6. Highlights include:

  • For both Windows and Silverlight
    • New methods on the ObjectFactory base class to better enable creation of a DAL object
    • Better support for lazy loaded fields, where an exception is thrown if the field is mis-used accidentally (thus reducing bugs)
    • ErrorDialog control for WPF and Silverlight to enable XAML-only handling of exceptions from CslaDataProvider
    • CslaDataProvider now has a Saved event to simplify some UI scenarios
    • RegisterProperty() now accepts a lambda expression to identify the property name, allowing the compiler to check the name, and avoiding the use of the string literal
    • MobileDictionary type, so you can create a dictionary that serializes between Silverlight and .NET
  • For Silverlight only
    • Better type name resolution, so you can now specify a type by "Namespace.Class, Assembly" without supplying the generic "Version=..." text
    • New InventoryDemo sample project (C# only right now - it is a work in progress)
    • Code snippets for async factory and data access methods

    Hopefully this is the final test release of 3.6.2, and I am planning for a final release on March 30 or 31 (before April Fool’s Day :) ). If you are using 3.6.0 or 3.6.1, please download and test this release and let me know if you encounter any issues.

  • Sunday, March 22, 2009 5:33:41 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

    Many people have asked me for the status of a CSLA .NET for Silverlight ebook. I may yet write such an ebook, but I am trying something new and different first – a 7 part video series covering CSLA .NET for Silverlight.

    Each video will be roughly 40 minutes in length, and the topics include:

    1. Introduction to CSLA .NET for Silverlight
    2. Creating a basic Silverlight and CSLA .NET for Silverlight application
    3. Implementing client-only architectures (calling remote services)
    4. Implementing n-tier archtiectures (using a remote data portal)
    5. Implementation of all CSLA .NET business object stereotypes
    6. Data Access in n-tier applications
    7. Authentication and authorization in CSLA .NET for Silverlight

    This totals to nearly 5 hours of content, with a mix of lecture and demo (though heavy on the demo).

    My current plan is to sell the videos through my online store, allowing purchasers to download the videos so they can be watched offline. The files will be quite large, but once downloaded, you’ll be able to watch them offline and I think that’s preferable to a streaming approach (though I’m open to feedback – would streaming be better?).

    While allowing downloads of the files may invite piracy, I’ll take that risk. I’m sure my ebooks have suffered from some piracy (some people are simply immoral), but I strongly believe that most counter-measures are easily defeated by the criminals and they absolutely complicate the lives of honest customers. The videos will cost more than the ebooks, as I’m basing my pricing on comparable video training, but I am hopeful that this won’t make the piracy issue worse. Unlike stealing from a “big publisher”, a lot of piracy and lack of actual sales just means I won’t be able to afford to create more videos or other content – the linkage between the criminal and me is direct – so I’m hopeful that the “casual pirate” will at least think twice before stealing from the guy who created the framework they are trying to learn :)

    As always though, I believe that most people are basically decent, and that this video series will have very real, tangible value to users of CSLA .NET for Silverlight (and CSLA .NET in general to some degree).

    To create the video series, I’ve hired a video producer and they’ll be doing the editing and production work. They also did all the lighting and camera work to film the live lecture parts of each segment, and what I’ve seen so far looks and sounds very nice! I’m using Camtasia to record the demo parts of each segment, and they’ll merge the lecture and demo content together to create each final segment. The live lecture parts were filmed in one of Magenic’s conference rooms, and I’m pretty pleased with the visual layout (it is somewhat like being in a classroom or at a conference).

    My current train of thought is to offer early adopters a discount, allowing you to download the segments as they become available. I think a discount is warranted, as the segments will be completed over a period of a few weeks, so there’s an element of "paying for future content” involved for any early adopters.

    Watch for the announcement of availability in the next very few short weeks!

    Sunday, March 22, 2009 5:33:34 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
     Friday, March 13, 2009

    I recently did a webcast on CSLA .NET 3.6 through Mike Benkovich’s Benkotips website.

    You can see all Mike’s webcasts, or you can go directly to the CSLA .NET webcast recording.

    This webcast is an overview of CSLA .NET, and includes about 35 minutes of demo where I walk through a CSLA .NET for Silverlight application.

    Friday, March 13, 2009 2:07:58 PM (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]  | 
     Monday, March 02, 2009

    I have put a new 3.6.2 release online for Windows and Silverlight. I am considering this a beta release, and am now moving toward final release of 3.6.2.

    Version 3.6.2 contains important bug fixes, and several enhancements to existing features based on feedback from people working with 3.6.1 so far. Highlights of the enhancements include:

    • For both Windows and Silverlight
      • New methods on the ObjectFactory base class to better enable creation of a DAL object
      • Better support for lazy loaded fields, where an exception is thrown if the field is mis-used accidentally (thus reducing bugs)
      • ErrorDialog control for WPF and Silverlight to enable XAML-only handling of exceptions from CslaDataProvider
      • CslaDataProvider now has a Saved event to simplify some UI scenarios
      • RegisterProperty() now accepts a lambda expression to identify the property name, allowing the compiler to check the name, and avoiding the use of the string literal
      • MobileDictionary type, so you can create a dictionary that serializes between Silverlight and .NET
    • For Silverlight only
      • Better type name resolution, so you can now specify a type by "Namespace.Class, Assembly" without supplying the generic "Version=..." text
      • New InventoryDemo sample project (C# only right now - it is a work in progress)
      • Code snippets for async factory and data access methods

    At this point 3.6.2 is feature-complete and is in test mode. Only bug fixes will be added at this point, with the plan being to release in the next couple weeks.

    Monday, March 02, 2009 5:02:52 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
     Thursday, February 19, 2009

    Setting up any type of n-tier solution requires the creation of numerous projects in the solution, along with appropriate references, configuration and so forth. Doing this with a Silverlight application is complicated slightly because Silverlight and .NET projects are slightly different (since they use different compilers, runtimes, etc). And sharing code between Silverlight and .NET projects complicates things a bit more, because the same physical code files are typically shared between two different projects in the solution.

    CSLA .NET for Silverlight makes it relatively easy to create powerful n-tier applications that do share some code between the Silverlight client and the .NET server(s). Even though CSLA .NET does solve a whole host of issues for you, the reality is that the solution still needs to be set up correctly.

    Here are the basic steps required to set up an n-tier CSLA .NET for Silverlight solution:

    1. Create a new Silverlight application project
      1. Have Visual Studio create a web application for the Silverlight project
    2. Add a new Silverlight Class Library project (this is your business library)
    3. Add a new .NET Class Library project (this is your business library)
    4. Use the Project Properties windows to set the Silverlight and .NET Class Library projects to use the same namespace and assembly name
      image
      image
    5. Remove the Class1 files from the Silverlight and .NET Class Library projects
    6. (optional) Add a .NET Class Library project to contain the data access code
    7. Set up references
      1. The Silverlight application should reference Csla.dll (for Silverlight) and the Silverlight Class Library
      2. The Silverlight Class Library (business) should reference Csla.dll (for Silverlight)
      3. The ASP.NET Web application should reference Csla.dll (for .NET), the .NET Class Library (business) and the .NET Class Library (data)
      4. The .NET Class Library (data) should reference Csla.dll (for .NET) and the .NET Class Library (business)
      5. The .NET Class Library (business) should reference Csla.dll (for .NET)
        image
    8. Add your business classes to the .NET Class Library (business)
      1. Link them to the Silverlight Class Library (business)
      2. Use compiler directives (#if SILVERLIGHT) or partial classes to create Silverlight-only or .NET-only code in each Class Library
    9. Configure the data portal
      1. Add a WcfPortal.svc file to the ASP.NET web application to define an endpoint for the Silverlight data portal
      2. Add a <system.serviceModel> element to web.config in the ASP.NET web application to configure the endpoint for the Silverlight data portal
      3. Add any connection string or other configuration values needed on the server to the web.config file
      4. Add a ServiceReferences.ClientConfig file to the Silverlight application and make sure it has an endpoint named BasicHttpBinding_IWcfPortal pointing to the server

    This isn’t the simplest or most complex option for creating a CSLA .NET for Silverlight solution. You could use CSLA .NET for Silverlight to create a client-only application (that’s the simplest), or a 4-tier application where there is not only a web server in the DMZ, but also a separate application server behind a second firewall. I do think that the model I’ve shown in this blog post is probably the most common scenario however, which is why this is the one I chose to outline.

    Thursday, February 19, 2009 4:24:58 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
     Thursday, February 05, 2009

    I have run across a couple really interesting items in the Silverlight area recently, and I’d like to call some attention to both of them.

    First is a tool that compresses xap files called XapOptimizer. Right now you can try it online – upload your xap, then download a compressed result. I’ve done this with a couple of my xap files and the size difference is quite remarkable. I assume it will be a product you can work into your build script at some point.

    Second is something totally different: a browsable pattern library of UI patterns. This is really interesting, and potentially very useful, because it pulls together real-world examples showing various implementations of the patterns, as well as providing some good motivation and explanation about each. What’s even better, is that this is written in Silverlight. But the really impressive part of this is the effort that must have gone into collecting and organizing all the data for the patterns.

    Thursday, February 05, 2009 9:16:16 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

    I think Silverlight represents the likely future of computing for most of us. And by “us”, I mean both Windows and web developers on the Microsoft platform (and maybe beyond).

    I think we’re at a point of convergence, where two industry trends are coming together in a way that makes Silverlight the most compelling answer for a lot of development scenarios. These trends are the continued abstraction away from the hardware, and now the operating system; and the likelihood that the web as we know it is nearing the end of its life, so we’re looking for the next big thing in that space.

    Arguably, Silverlight’s primary competitor is WPF. But I don’t think WPF is the long-term winner. Another obvious competitor is Flash/Flex/Air, and that could be serious except for the fact that Silverlight lets existing .NET developers (and there are a lot of us) leverage our existing skills, while Adobe means starting over. And another competitor is Gears, which may be valid, time will tell (as long as I don’t have to do Javascript), but also means starting over and discarding all the .NET skills we’ve accumulated. And Gears, to me, represents the last gasping attempt to salvage the web as we know it – and I suspect that’s a lost cause.

    Part of the appeal of Silverlight, and the reason it almost instantly gains traction in any conversation with my clients, is that it is independent of Windows. They like the idea that it works across Windows versions without worrying that Microsoft will fix some Windows thing and break their app.

    Some of them, especially those that deal with the government, really like that it works on the Mac as well as Windows. They have cross-platform requirements mandated by either the market or by law, and Silverlight gives them the option of using .NET (which they love) to run apps on the Mac.

    Another part of the appeal of Silverlight, across the board from what I can see, is that people don't trust ClickOnce. But they do trust the browser as a deployment vehicle. I suspect this goes back, somewhat, to Silverlight being independent of Windows, while ClickOnce is more vulnerable to the OS itself. Our overall experience with ClickOnce is that it works great 99% of the time. And then 1% of the time it fails for no reason anyone can figure out. Same target machines, same configuration, but it just doesn't quite work. Maybe, over time, we'll find out Silverlight is also unreliable in this manner - but early indications are that this is not the case.

    If you look at the theme here, it is about escaping the OS and all its complexity. And that's not entirely surprising.

    We build the first OSes to abstract the hardware. And they evolved over decades until they were terribly complex, and somewhat intertwined with the hardware (driver issues are the major failure point for Windows).

    So we built runtimes to abstract the OS (starting perhaps with Smalltalk, then VB, the JDK and now .NET). And they evolved over the past couple decades until they are becoming terribly complex, and somewhat intertwined with the OS (installing/upgrading .NET usually requires a reboot of Windows).

    It appears to me that we're now building smaller, decoupled runtimes that are a bit less complex, and that are intentionally decoupled from the OS, and are largely self-contained. It is just the next step in the evolution - though I suspect it does mean Windows (or any other OS) becomes substantially less relevant to most people.

    By itself, I'm not sure that a runtime that is less coupled to the OS would be enough to drive Silverlight’s future. But there's another dynamic here too: the aging of the web, and the search for "what's next".

    I was subscribed to the Usenet newsgroups in the early 90's, when they were discussing the future of the global network. When WAIS, Gopher and HTTP were competing (Gopher came from Minnesota after all : ) ). And HTTP/HTML won, because they really were the superior document viewing technology. A global version of lex; something that should have filled the role of PDF.

    But as we got into the mid-90's, people started bastardizing and hacking this technology. Warping it into something far different from its original intent. And that's OK - but it is important to realize this was done ad-hoc, with little or no pre-planning or thought of proper architecture.

    I know, I sound like a CS purist, but really the web, as we know it, is a stack of horrible hacks, all leaned up against each other like the world's biggest and most expensive house of cards. In short, the technology of the web is a mess. Just witness the insanity around browser versions,  the standards compliance farce, and the ridiculously inefficient ways we waste time/money building a web app that runs on more than one version of even one browser.

    Yes, the web has transformed the world. And it revealed some very good patterns for software and usability. But it became mainstream over 10 years ago, and most technologies fade gracefully away at the 10 year mark. So it is time for the web (as we know it) to die.

    The question then, is what comes next? Do browsers become the new standards-based OS? Or do we extend the runtime concept into the web, as a long-term replacement.

    Google is betting on the former, with Gears and Chrome. They clearly hope/expect that the browser itself will be the next OS - the thing that makes Windows and Mac OSes irrelevant. Adobe is betting on the latter. They clearly hope Flash/Flex/Air will be the runtime that makes both the browser and the OS irrelevant.

    Microsoft is playing a smart game, imo. Silverlight (with Mesh and Azure) represents a strategy very similar to Adobe's (but bigger), where a runtime may well make the browser and the Windows/Mac/Linux desktop irrelevant. At the same time, they've got WPF as a fall-back in case the core OS does remain important to the average consumer.

    So I think these two dynamics - the desire by our customers to escape the shackles of the OS (not just Windows - the OS in general), coupled with the fact that the industry is looking for the next step in the evolution of the web itself - work together to make this the perfect time for Silverlight to be the hot technology.

    And I do think this works against WPF, because it neither helps us escape the OS, nor does it represent the future of the web. And it works against Adobe, because their vision isn’t big enough, nor their established developer base large enough. And against Google, because they are still trying to shape the stack of hacks that is the browser into something reliable, and I suspect that’s simply unrealistic.

    In short, I think Silverlight offers the power needed for smart client business apps, with the best deployment and navigation characteristics of the web. Sure, it needs to continue to grow and evolve (the search issue needs addressing for example), but I really think Silverlight represents the future of development for most of us.

    Thursday, February 05, 2009 4:15:47 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

    It has been a month and a half since the release of CSLA .NET 3.6, which was the first release of a major .NET development framework to include Silverlight support.csla_logo1_72

    Today I am releasing version 3.6.1 for Windows and for Silverlight. This point release addresses several bugs and issues with 3.6.0, and should include no breaking changes. I recommend that all 3.6 users upgrade to 3.6.1.

    You can review the CSLA .NET for Windows change log, and the CSLA .NET for Silverlight change log to get an overview of the fixes and changes.

    Some enhancements of note on the Windows side include:

    • The use of “_forceInit” to trigger static field initialization is no longer required
    • Add methods to the ObjectFactory base class to make it easier to build a DAL using ObjectFactory
    • Allow resetting the proxy type used by the data portal, and allow setting the proxy type through code, to make it easier to change the data portal configuration at runtime

    Some enhancements of note on the Silverlight side include:

    • The use of “_forceInit” to trigger static field initialization is no longer required if your PropertyInfo<T> fields are declared public in scope
    • The data portal WcfProxy now has better support for various configuration and subclassing options
    • MobileFormatter now supports the DateTimeOffset type

    Though 3.6.1 includes these enhancements, the primary focus is on addressing a few bugs and issues that have been discovered in 3.6.0. Whether you need these enhancements or not, you will benefit from the bug fixes.

     

    On a related note, I have refreshed the pre-release of 3.5.3, which includes some important bug fixes for the 3.5.2 version. If you are using 3.5.2, I strongly suggest you evaluate 3.5.3 to see if it addresses any issues you are facing. Version 3.5.3 is a “floating test release”, which means it is stable, but will continue to be a catch-all for reported bugs over the next few weeks. You should strongly consider using 3.5.3 if you are facing any of the bug fixes it contains.

    As Microsoft rolls out .NET 3.5 SP1 via Windows Update, it is my intent to stop supporting the 3.5.x version, as all 3.5 users should be able to move to 3.6.x. That’ll get me down to dealing with just four versions:

    1. 3.6.x for Windows
    2. 3.6.x for Silverlight
    3. 3.0.x C#
    4. 3.0.x VB

    I expect 3.5.3 to be the final release of the 3.5 code line, and I expect that’ll happen sometime in March.

    Thank you for using CSLA .NET, see you on the forum!

    Thursday, February 05, 2009 1:40:25 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]  | 

    I just ran into an odd “feature” of Silverlight data binding, that I assume must actually be a bug.

    I have an object with a string property that has a public get, but private set:

    public string Name
    {
      get { return GetProperty(NameProperty); }
      private set { SetProperty(NameProperty, value); }
    }

    You would think that no code outside the business class could call the set block, because it is private. Certainly in .NET this would appear as a read-only property to any code outside the class.

    But in Silverlight, data binding is perfectly capable of calling this code. Worse, the reflection PropertyInfo object for this property returns true for CanWrite, so this appears as a read-write property to any code.

    I don’t think the problem is in the C# compiler, because if I write code that tries to set the property I get a compile-time error saying that’s not allowed.

    Also, it isn’t a problem with reflection, because trying to set the value using the SetValue() method of a PropertyInfo object fails with the expected MethodAccessException (Silverlight reflection doesn’t allow you to manipulate private members). This, in particular, is weird, because if CanWrite returns true it should be safe to write to a property…

    Update: I just checked .NET (being the suspicious sort) and it turns out that CanWrite returns true for a read-only set block in .NET too. And of course reflection won't set the property due to the scope issue, just like SL. But WPF data binding also doesn't call the private set block, where Silverlight somehow cheats and does call it - so at least the scope of the issue is narrowed a bit.

    Which begs the question then: how is data binding bypassing the normal property scope protections so it can manipulate a private member? With the next question being how can I do it too? :) 

    Seriously, this is the first time I’ve found where Microsoft has code in Silverlight that totally bypasses the otherwise strict rules, and it is a bit worrisome (and a pain in the @$$).

    Anyway, the workaround at the moment is to use the old-fashioned approach and create a separate mutator method:

    public string Name
    {
      get { return GetProperty(NameProperty); }
    }

    private void SetName(string value)
    {
      SetProperty(NameProperty, value);
    }

    This works, because when there’s no set block at all the property is actually read-only to everyone, inside and outside the class. Kind of inconvenient for the other code inside the business class that wants to set the property, because that code must use this non-standard mutator method – but at least it works…

    Wednesday, January 28, 2009 3:35:02 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
     Wednesday, December 17, 2008

    csla_logo1_42

    csla-lt_logo_42

    I have released version 3.6 of CSLA .NET for Windows and CSLA .NET for Silverlight.

    This is a major update to CSLA .NET, because it supports Silverlight, but also because there are substantial enhancements to the Windows/.NET version.

    To my knowledge, this is also the first release of a major development framework targeting the Silverlight platform.

    Here are some highlights:

    • Share more than 90% of your business object code between Windows and Silverlight
    • Powerful new UI controls for WPF, Silverlight and Windows Forms
    • Asynchronous data portal, to enable object persistence on a background thread (required in Silverlight, optional in Windows)
    • Asynchronous validation rules
    • Enhanced indexing in LINQ to CSLA
    • Numerous performance enhancements

    This version of CSLA .NET for Windows is covered in my new Expert C# 2008 Business Objects book (Expert VB 2008 Business Objects is planned for February 2009).

    At this time there is no book covering CSLA .NET for Silverlight. However, most business object code (other than data access) is the same for Windows and Silverlight, so you will find the Expert C# 2008 Business Objects book very valuable for Silverlight as well. I am in the process of creating a series of training videos around CSLA .NET for Silverlight, watch for those in early 2009.

    Version 3.6 marks the first time major development was done by a team of people. My employer, Magenic, has been a patron of CSLA .NET since the year 2000, but with this version they provided me with a development team and that is what enabled such a major version to be created in such a relatively short period of time. You can see a full list of contributors, but I specifically want to thank Sergey Barskiy, Justin Chase and Nermin Dibek because they are the primary contributors to 3.6. I seriously couldn't have asked for a better team!

    This is also the first version where the framework code is only in C#. The framework can be used from any .NET language, including VB, C# and others, but the actual framework code is in C#.

    There is a community effort underway to bring the VB codebase in sync with version 3.6, but at this time that code will not build. In any case, the official version of the framework is C#, and that is the version I recommend using for any production work.

    In some ways version 3.6 is one of the largest release of the CSLA .NET framework ever. If you are a Windows/.NET developer this is a natural progression from previous versions of the framework, providing better features and capabilities. If you are a Silverlight developer the value of CSLA .NET is even greater, because it provides an incredible array of features and productivity you won't find anywhere else today.

    As always, if you are a new or existing CSLA .NET user, please join in the discussion on the CSLA .NET online forum.

    Wednesday, December 17, 2008 4:13:21 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
     Friday, December 05, 2008

    CSLA .NET for Windows and CSLA .NET for Silverlight version 3.6 RC1 are now available for download.

    The Expert C# 2008 Business Objects book went to the printer on November 24 and should be available very soon.

    I'm working to have a final release of 3.6 as quickly as possible. The RC1 release includes a small number of bug fixes based on issues reported through the CSLA .NET forum. Barring any show-stopping bug reports over the next few days, I expect to release version 3.6 on December 15.

    If you intend to use version 3.6, please download this release candidate and let me know if you encounter any issues. Thank you!

    Friday, December 05, 2008 10:30:44 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
     Wednesday, November 05, 2008

    Magenic is sponsoring a webcast about CSLA .NET for Silverlight on November 13. The presenter is my colleague, Sergey Barskiy. Sergey is one of the lead developers on the CSLA .NET 3.6 project, and this should be a very educational webcast.

    Wednesday, November 05, 2008 1:31:21 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]  | 
    Thursday, October 23, 2008 7:10:47 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
     Tuesday, October 21, 2008

    I have released Beta 2 of CSLA .NET 3.6, with support for Windows (download) and Silverlight 2.0 (download).

    This is an incremental release. Very few issues have been reported or found with Beta 1a, which gives me hope that we're still on track for a final release in the very near future. A lot of hard work by Sergey, Justin, Nermin and other Magenic colleagues have really paid off in the early stability of this version.

    CSLA .NET for Silverlight does include one feature change. The Navigator control is now capable of handling a "cold start" scenario, where the user navigates directly to the Silverlight app, specifying a bookmark on the URL. The Navigator control will now immediately help your app navigate to the correct state so the user effectively returns to the page/control/view they'd bookmarked in the first place.

    CSLA .NET for Windows also includes one feature change. Nermin is working hard on integrated Visual Studio file and project templates, and an installer project for the templates (and possibly all of CSLA .NET). This work is not yet complete, but Beta 2 has a much more complete set of behaviors than Beta 1.

    We believe that this Beta 2 release is very stable. Please download and use it - on either Windows or Silverlight. If you have questions/comments or find issues, please post in the forum.

    Also, check out my DotNet Rocks interview about CSLA .NET for Silverlight.

    Finally, for those wondering about the status of the Expert C# 2008 Business Objects book, it is still on track for a December release. Watch www.apress.com, as they tell me that they'll be offering an "alpha release" program where you can pre-purchase the book and get early access to chapters in PDF form, and get the paper book when it comes out.

    We are also on track for Expert VB 2008 Business Objects, probably in the February or March timeframe. This is dependent on the 3.6 VB conversion project, which has four volunteers and is moving along pretty well. I feel pretty confident that this will all come together so the framework and book will both be available to the VB community.

    Code well, have fun!

    Tuesday, October 21, 2008 7:29:29 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
     Thursday, October 02, 2008

    The next release of CSLA .NET for Silverlight will return to using the async WcfProxy in the data portal instead of the SynchronizedWcfProxy that restricts the data portal to allow only one concurrent call at a time. The WcfProxy allows parallel calls from the client to the server through the data portal. The change is already in svn for those that are using live code.

    The reason we created SynchronizedWcfProxy originally was due to a bug in Silverlight 2.0 Beta 2, where in some cases you'd get a 404 error with overlapping WCF calls to the same server. This was wreaking havoc with our unit tests, which have a lot of parallel WCF calls.

    It appears that the issue is resolved in Silverlight RC0, which is great news.

    However, we didn't know right away, because we were still getting sporadic 404 errors. With some research, and help from Eugene Osovetsky and his colleagues at Microsoft, we figured out the remaining issue.

    Part of the problem is described by Eugene's post on dealing with faults and exceptions in Silverlight. This was masking the underlying issue we faced.

    The underlying issue is that we were testing using the ASP.NET Development Web server (often called Cassini). Cassini has some well-known limitations, among them that it doesn't work well when a custom .NET principal is used in your web server code. This particular issue appears as a SerializationException as Cassini attempts to transfer the principal from one thread to another. This issue doesn't occur with IIS, because IIS doesn't switch threads like Cassini does.

    Several of our unit tests for CSLA use custom principals, because we have tests for the various authentication modes supported by CSLA .NET for Silverlight - including the use of a custom principal object. These tests would sporadically fail on Cassini, but only under load. Apparently the problem would only manifest if we were able to get Cassini to recycle an existing thread off the thread pool.

    In Eugene's post he suggests that the solution to dealing with faults/exceptions is to wrap your code in a try..catch block and return any exception information as part of your service contract. The CSLA data portal has always done this, and so we were initially puzzled by the continuing 404 errors. However, it turns out that Cassini was failing before any of our code ran. Thanks to this, we couldn't wrap a try..catch around the code, because it wasn't our code...

    This gave us another clue though. It turns out that the issue we faced was that a request would put a custom principal on the server thread. That principal was never removed from the thread, and if that thread got recycled (by random chance) we'd get the SerializationException. The solution is to ensure that the thread principal is set to null as each server request completes. That way a recycled thread never has a custom principal.

    Again, not an issue that affects IIS, but by figuring this out we're now able to use Cassini too, which is far more convenient.

    I post all this, because if you encounter 404 errors in Silverlight 2, you should first follow Eugene's advice and return error details as part of your service contract (which can really alter your service design!). And if you do that and still have trouble, look to deeper issues with the web host or network stack, they can be devious...

    Thursday, October 02, 2008 6:16:01 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
     Friday, September 26, 2008

    CSLA .NET version 3.6 is a framework for creating business applications using object-oriented design concepts, in a distributed computing environment. CSLA .NET for Windows and CSLA .NET for Silverlight share many common features and capabilities, though they support different platforms. The commonality between the two framework implementations allows sharing of business object code between .NET and Silverlight, while the differences allow you to exploit the power of the two different platforms.

    CSLA .NET version 3.6 is the latest evolution in the CSLA .NET framework, which has been around since 2001. Over the past eight years the framework has grown and changed in many ways, and is now one of the most widely used open source development frameworks for the .NET platform.It is covered under a very liberal license and has a vibrant, helpful and friendly community.

    The primary goal of CSLA .NET is to enable you to build a rich, powerful and flexible business layer for your application.

    image

    This business layer is composed of business domain objects that encapsulate your business logic (calculations, algorithmic processing, validation and authorization). These objects should be designed based on the business use cases for your application domain. With some reasonable care, it is possible to create a single set of business objects that work within both the .NET and Silverlight environments.

    In some cases your Silverlight business objects may contain the exact same object code used for CSLA .NET for Windows applications, though in most cases there will be some small variation of code. In most cases more than 90% of your object code will be shared between .NET and Silverlight, with less than 10% of the code being different. The differences are primarily due to the asynchronous nature of Silverlight programming, and the more synchronous nature of traditional .NET programming. If you are willing to apply the same asynchronous designs to your .NET implementation you can achieve 99% or 100% code sharing between the two platforms.

    CSLA .NET Core Features

    Regardless of platform, CSLA .NET is designed to do two things. First and foremost, it is designed to support you as you create a powerful business layer based on rich business domain objects. Second, it is designed to enable a distributed application architecture centered on a concept called mobile objects.

    To support the creation of rich domain objects, CSLA .NET includes subsystems that supply commonly required functionality, including:

    • Full support for data binding (WPF, Silverlight, Windows Forms and Web Forms)
    • Object status tracking (is object new, changed, marked for deletion, etc.)
    • Standardized business and validation rule processing
    • Standardized authorization at the object and property levels
    • Integration with, and simplification of, standard .NET authentication models
    • Undo capabilities to support implementation of Cancel buttons and complex layered UIs
    • Standardized interaction with a data access layer or ORM
    • Enhanced support for LINQ queries against your business objects
    • Numerous general productivity features, useful in many business application scenarios
    • Asynchronous data access and asynchronous validation rules

    My Expert 2008 Business Objects book (published by Apress) covers these subsystems in detail.

    These subsystems are exposed through a set of base classes from which you inherit to create your business objects. These base classes enable a set of object stereotypes:

    • Editable root (single or collection) - an object that has read-write properties, and which can be directly retrieved and stored in a database
    • Editable child (single or collection) - an object that has read-write properties, and which is retrieved and stored in a database as part of some editable root
    • Dynamic list - a collection that contains editable root objects, integrating with data grid controls to auto-update each object when the user leaves a row in the grid (not applicable to ASP.NET interfaces)
    • Read-only root (single or collection) - an object that has read-only properties, and which can be directly retrieved from a database
    • Read-only child (single or collection) - an object that has read-only properties, and which is retrieved from a database as part of some read-only root
    • Name/value list - a read-only root collection that contains only name/value pairs for use in populating combobox or listbox controls
    • Command - an object that executes code on the client and/or the server; often used to execute database code or server-side workflows

    The end result of building your business objects using CSLA .NET is that your objects are created in a consistent, standardized manner. So not only do your objects automatically gain substantial benefit from all of these subsystems, but your overall maintainability is radically improved thanks to the consistent architecture, design and coding of your application.

    The concept of mobile objects is a technique that supports the use of rich business domain objects in distributed application environments. Specifically, the idea is that your business objects are mobile, able to move physically from one computer to another to take advantage of the resources available on each computer.

    CSLA .NET includes a component called the data portal which is responsible for providing the mobile object functionality. Using the data portal, your business objects may come into existence on an application server so they can efficiently interact with your data access layer (and database). The objects may then physically move across the network to the client workstation (web server, Windows client or Silverlight client) where they can efficiently interact with the user by being data bound directly to the UI. Once the user is done interacting with the object, the object may then move back to the application server so it can interact with the data access layer to update the database.

    Mobile objects are an incredibly powerful technique for exploiting the power of object-oriented design and programming in distributed environments. The CSLA .NET data portal abstracts the complexity of this concept. The result is that your application can switch between 1-tier, 2-tier, 3-tier and even 4-tier models with no change to code - the change is purely one of configuration.

    CSLA .NET for Windows

    CSLA .NET for Windows allows you to easily build WPF, ASP.NET (Web Forms, AJAX and MVC) and Windows Forms user interfaces on top of your business objects. It also supports WCF service, Windows Workflow and asmx web services interfaces. Technically you could create all of these interfaces on top of the same set of business objects, though most applications require only one or two types of interface (Web Forms and WCF services for example).

    CSLA .NET includes some UI controls in each major UI technology. These controls help minimize UI code and maximize productivity.

    In WPF the following controls are provided:

    • CslaDataProvider - a WPF data provider that enables the use of commanding to implement Save, Cancel, Add New and Remove Item functionality in the UI
    • PropertyStatus - like the Windows Forms ErrorProvider, but manages validation, authorization and busy notification for each control
    • ObjectStatus - enables data binding to the business object's status properties (IsValid, IsNew, etc.)
    • Authorizer - container-based implementation that enables/disables controls based on the business object's authorization rules

    In Web Forms the following controls are provided:

    • CslaDataSource - a Web Forms data source control that supports data binding to business objects
    • DataMapper - a component that simplifies the copying of form post values into your business objects

    In Windows Forms the following controls are provided:

    • BindingSourceRefresh - work around for a data binding refresh issue in Windows Forms
    • CslaActionExtender - automate object management behind buttons such as Save and Cancel
    • ReadWriteAuthorization - automatically enable/disable detail controls based on the object's authorization rules

    CSLA .NET also includes functionality to assist in the creation of services and workflow activities.

    For WCF and asmx services the following component is provided:

    • DataMapper - a component that simplifies the copying of data between your business objects and data contract objects

    For WCF services, there is another component:

    • PrincipalCache - a component that temporarily caches .NET principal objects for use when implementing custom authentication/authorization in a WCF service

    For Windows Workflow the following component is provided:

    • WorkflowManager - simplifies launching, suspending and resuming a workflow instance

    CSLA .NET for Windows provides a great deal of flexibility in terms of data access. CSLA .NET is not a data access layer or an object-relational mapping (ORM) tool. However, CSLA .NET does provide a level of formalization around how your application interacts with your data access layer or ORM. This formalized flexibility allows you to use a wide range of data access technologies, including raw ADO.NET, DataSets, LINQ to SQL, ADO.NET Entity Framework, NHibernate, Paul Wilson's ORM mapper and many other technologies.

    CSLA .NET for Silverlight

    CSLA .NET for Silverlight allows you to easily build Silverlight 2.0 user interfaces on top of your business objects. By fully supporting Silverlight data binding, along with extra controls provided by CSLA .NET, you can create Silverlight forms with nearly no UI code. Just like with CSLA .NET for Windows, most of your code is encapsulated in your business objects, maintaining clean separation between the presentation and business behaviors.

    Because Silverlight doesn't provide all the rich data binding features found in WPF or Windows Forms, CSLA .NET for Silverlight provides a set of Silverlight UI controls and features to provide a high level of parity with the functionality in WPF. Not only are you able to build a Silverlight interface on your business objects, but CSLA simplifies the creation of very rich, interactive business interfaces over those objects. For example, Silverlight doesn't include WPF commanding, and so CSLA .NET includes replacement functionality so you can hook up common UI functionality to your objects without resorting to code behind each form. The controls provided by CSLA .NET include:

    • CslaDataProvider - a Silverlight equivalent to the WPF data provider
    • InvokeMethod - a Silverlight equivalent to WPF commanding
    • PropertyStatus - a Silverlight equivalent to WPF validation or the Windows Forms ErrorProvider (though far superior to both)
    • ObjectStatus - a control that uses the visual state manager to automatically change the UI based on the state of your business object
    • BusyAnimation - a control that displays a busy animation; can be bound to your object to automatically show that your object is performing an asynchronous operation
    • Data grid columns - custom data grid column types that incorporate the PropertyStatus control to show validation, authorization and busy status for each cell

    CSLA .NET for Silverlight enables a data access model where your business objects invoke remote services to retrieve or update data. You can use this model to implement client/server or service-oriented application designs. For example, you might use ADO.NET Data Services to expose data services from a server, and use CSLA .NET for Silverlight to create business objects and a Silverlight UI to interact with those data services.

    If you have a CSLA .NET for Windows server, you can take advantage of some advanced CSLA .NET capabilities. Specifically, your CSLA .NET for Silverlight application can interact with the CSLA .NET for Windows server, enabling 2-, 3- and 4-tier physical deployments of your application. In this model, your .NET business objects (perhaps already supporting a Web Forms UI) are effectively extended directly into the Silverlight client. The standard object persistence models supported by CSLA .NET are now automatically used to support the Silverlight client, providing an incredibly high level of code and functionality reuse across the .NET and Silverlight platforms.

    CSLA .NET Deployment Models and Mobile Objects

    The CSLA .NET data portal enables the use of mobile object concepts in your application. This is largely transparent to your code, and the code you do write to interact with the data portal is very standardized. The benefit of using the data portal is flexibility; you can switch your application from a physical 1-tier deployment to a 3-tier or even 4-tier deployment purely by changing configuration - no coding changes are required.

    CSLA .NET for Windows supports 1-, 2- and 3-tier physical deployments.

    image image image

    Again, it is possible to switch between these physical models purely by changing configuration. Your UI code, business object code and data access code remains entirely intact across all three deployment models.

    In the 3-tier model, the business logic layer (the assembly(ies) containing your business object code) is deployed to both the client and application server. Your business objects literally move between those two machines through the data portal.

    The data portal uses standard .NET technologies such as WCF to manage the network communication. It is implemented using powerful design patterns such as channel adapter, provider and message router.

    CSLA .NET for Silverlight supports 1-, 2-, 3- and 4-tier physical deployments. The 1-, 2- and 3-tier models employ the same architecture as CSLA .NET for Windows. The 4-tier model is a little different.

     image

    In the case of CSLA .NET for Silverlight's 3- and 4-tier models, the data portal is more advanced because your business objects literally move between the Silverlight client and the .NET server(s). This means your objects are moving between different platforms, as well as different machines. This is usually entirely transparent to your code, so the resulting functionality and your code is the same as in a pure .NET application.

    It is important to realize that in the 3- and 4-tier deployment models, for both .NET and Silverlight, your business code and business objects are fully functional on each machine. This means you have the flexibility to run logic on the client, the server or both as required to meet your applications needs.

    Standardized Data Access

    CSLA .NET is not a data access technology or an object-relational mapping (ORM) tool. However, the data portal (which implements the mobile object concept) does impose a level of standardization and structure around how your objects interact with your data access layer or ORM. This standardization remains very flexible, and you are free to use nearly any data access technology you choose, including (but not limited to):

    • Raw ADO.NET (connections, data readers, etc.)
    • DataSet and TableAdapter objects
    • LINQ to SQL
    • LINQ to XML
    • ADO.NET Entity Framework
    • NHibernate and other third-party ORM tools
    • Simple file I/O
    • Remote XML or JSON services

    The data portal supports two models: data portal managed, and object factory.

    In the data portal managed model, the data portal manages the creation and state of your business objects, and invokes methods on your object to perform persistence. So in this model, your business objects are responsible for interacting with your data access layer or ORM, and the data portal helps ensure your object state (new, dirty, etc.) is properly managed.

    In the object factory model, the data portal creates a factory object that is responsible for the creation and state of your business objects. You must supply this factory object. The data portal invokes methods on your factory object to perform persistence. In this model your factory objects are responsible for interacting with (or implementing) your data access layer or ORM, and for managing your business object's state (new, dirty, etc).

    The data portal managed model is ideal when using a data access layer built using raw ADO.NET, simple file I/O or other relatively direct techniques. It is the simpler of the models, because the data portal provides a lot of automatic management of your business objects.

    The object factory model is ideal when using an ORM or a more sophisticated data access layer. It is more complex, and requires more coding on your part, but is far more flexible. It is also implementing using an open architecture, which enables some test driven development (TDD) scenarios that are (arguably) more difficult to achieve using the data portal managed model.

    Summary

    CSLA .NET is a powerful, time-tested framework that supports the creation of an object-oriented business layer for distributed application development. It helps you encapsulate your business logic in a set of rich business domain objects, and provides your objects with powerful features around data binding, business logic, validation and authorization.

    Starting with version 3.6, CSLA .NET supports all common interface types on the .NET platform, and provides seamless support for the new Silverlight 2.0 platform as well.

    Friday, September 26, 2008 10:47:15 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

    Version 3.6 Beta 1 of CSLA .NET for Windows and CSLA .NET for Silverlight is now available.

    The new Silverlight version requires Silverlight 2.0 RC0.

    Our focus in the last couple pre-releases has been stability, and this is true for Beta 1 as well. There are no new features in this release, just some fixes for reported issues, and of course making sure the code works with Silverlight RC0.

    Please report any issues you find on the forums at http://forums.lhotka.net, thank you!

    Friday, September 26, 2008 1:33:09 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
     Friday, September 19, 2008

    I have put a new pre-release of CSLA .NET for Windows and CSLA .NET for Silverlight (both version 3.6) online for download:

    This is a pretty major update to the last pre-release, and I believe we're very near feature complete and are pretty stable at this point. I think the next release will be Beta 1 if we hold to the current plan.

    Read the change logs to see what's new, and check out the list later in the post for highlights.

    Check out the samples download for Silverlight, and also many of the subfolders in the Silveright test download. Combined, they provide a wealth of examples on how to use the many data portal configurations, the really cool UI components and the flexible authentication options.

    Also, the ProjectTracker code for .NET is nearly final. I have about 1.5 chapters left on the 2008 book (first draft), which means only the WCF service interface is likely to change much at this point. The WPF and Web Forms interfaces got a lot of focus due to chapters covering them. Sadly Windows Forms has no chapter, and so it is lagging a bit (and it could use some help, because there are cool new WinForms controls too!!).

    For CSLA .NET for Windows users, here's a quick overview of what 3.6 adds to 3.5.1:

    • ObjectContextManager to manage Entity Framework contexts
    • TransactionManager to manage ADO.NET transaction objects
    • PropertyStatus control for WPF to provide visual cues for validation and authorization on bound properties
    • ObjectStatus improvements for WPF to provide bindable properties for authorization (so you can enable/disable/alter your UI through XAML)
    • BusyAnimation control for WPF that you can bind to the CslaDataProvider or business object IsBusy property to automatically show when some background task is running
    • Async data portal for parity with Silverlight, not real useful in WPF with a data provider, but still kind of neat
    • Async validation rules for parity with Silverlight (because any rule using the data portal is, by definition, async)
    • MembershipIdentity class to make it very easy to authenticate against the ASP.NET membership provider from a smart client app, or web app (or Silverlight app)
    • The data portal no longer requires your principal subclass BusinessPrincipalBase, allowing for more flexibility
    • The data portal will invoke an "authorization provider" on every server call, allowing you to do high level authorization on each call
    • ApplicationContext.User now just works in WPF - it detects WPF and works differently to deal with the WPF issues with principal objects
    • WcfProxy for data portal is now far more configurable - using a subclass you can entirely alter the channel factory and WCF proxy objects
    • DataMapper and UndoableBase now use dynamic method invocation instead of reflection to provide superior performance
    • The data portal now supports the ObjectFactory attribute, providing an entirely new model for object persistence (different from the DataPortal_XYZ model)

    This is just the high level list - there are other small things changed in various places to make things easier. And for all that, there are only two breaking changes from 3.5.1!!

    • Removed an ambiguous overload of the PropertyInfo<T> constructor
    • Renamed GetProperty<P,F> to GetPropertyConvert<P,F> (and same for Set/Load/ReadProperty)

    And just think - all this stuff is in the CSLA .NET for Silverlight version too, plus other Silverlight-specific features!

    Friday, September 19, 2008 9:30:05 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
     Wednesday, September 03, 2008

    As part of the CSLA Light project we created a unit testing engine for Silverlight and donated it to the community as UnitDriven.

    We now have our first community contribution to this open-source project, in the form of a really nice visual change. Here's the author's blog post on the topic:

    http://staxmanade.blogspot.com/2008/08/unitdrivens-ui-gets-minor-makeover.html

    Thank you Staxmanade! This is a really nice visual upgrade, and more importantly a major usability upgrade. I love it!

    The next release of the CSLA Light unit tests will be linked to the new version of UnitDriven, and having used it for just a day or so, I can say it is a big help.

    Wednesday, September 03, 2008 8:34:23 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
     Monday, September 01, 2008

    I have put an updated pre-release online for download of both CSLA .NET 3.6 and CSLA Light 3.6.

    We're now at the point of focusing primarily on stabilization and limiting new features. Changes at this point will be due to our testing and usage, and feedback we recieve from the community.

    This pre-release should be reasonably stable, on both the .NET and Silverlight platforms. Please give them a try and post in the forum with any issues you encounter. Thank you!

    Monday, September 01, 2008 7:41:08 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
     Wednesday, August 13, 2008

    WPF has this cool concept called a data provider control. CSLA .NET includes a custom data provider control that enables nearly codeless forms (if you don't count XAML as code), by supporting the following functions purely through XAML:

    1. Create/Fetch an object
    2. Save an object
    3. Cancel changes to an object
    4. Add a new item to a list (if the object is a collection)
    5. Remove an item from a list (if the object is a collection)

    Silverlight doesn't have a data provider concept, nor does it have commanding. Which means that you need to write code behind the form for all of those actions.

    So in CSLA Light we're investigating the possibility of some sort of data provider control to fill in this gap. The idea is that you'd be able to declare a CslaDataProvider as a resource on your form and use it as a data source, and as a handler for the save/cancel/add/remove operations.

    This also means we need a way, through XAML, to route things like a button's Click event to methods on CslaDataProvider (because there's no commanding in Silverlight).

    At a prototype level what we've got is something like this. The CslaDataProvider goes in the Resources section just like it would in WPF:

    <UserControl.Resources>
      <csla:CslaDataProvider x:Key="MyData"
                                         ManageObjectLifetime="True" />
    </UserControl.Resources>

    Some WPF concepts don't make sense. For example, IsAsynchronous is useless because in Silverlight it will be asynchronous. Others, like IsInitialLoadEnabled might make sense, we're not entirely sure yet.

    Your page XAML then uses this as a data source. But where WPF does some magic behind the scenes for data providers, Silverlight doesn't know about data providers. So you have to deal with this yourself when setting the DataContext:

    <Grid x:Name="LayoutRoot" DataContext="{Binding Source={StaticResource MyData}, Path=Data}">

    The DataContext is set to use the Data property of the data provider, because that's where the actual business object is found. In WPF this indirection is hidden automatically, but in Silverlight you have to do it yourself.

    In the Form_Loaded() method in code behind you call your business object's factory method. But rather than handling the async callback yourself, you allow the data provider to handle it:

    private void Form_Loaded(...)
    {
      var dp = (CslaDataProvider)this.Resources["MyData"];
      CustomerEdit.GetCustomer(123, dp.FetchCompleted);
    }

    I hope to eliminate even this bit of code behind (at least for parameterless create/fetch scenarios), but the current prototype does require it. The CslaDataProvider exposes a set of async handlers for create and fetch operations.

    When the async request completes, the CslaDataProvider object's Data property changes to reflect the new business object. That causes a PropertyChanged event, which in turn causes data binding to refresh the UI so the user sees the data.

    That gets us pretty close to the WPF data provider capability of creating or retrieving an object. But the Csla.Wpf.CslaDataProvider goes further, and so the plan is for the Csla.Silverlight.CslaDataProvider to also go further.

    The data provider object has methods like Save() and Cancel() that can be called to save the object or cancel changes. The trick then, is how to get UI elements, like a button, to call those methods when Silverlight has no commanding or relative binding.

    At the moment we're addressing this with an InvokeMethod object that exposes some attached properties. So you can create a Button like this:

    <Button csla:InvokeMethod.Resource="{StaticResource MyData}"
                 csla:InvokeMethod.MethodName="Save"
                 csla:InvokeMethod.TriggerEvent="Click"
                 Content="Save" />

    This tells the InvokeMethod object to listen for a Click event from the Button. When it gets a Click event, it invokes the Save() method on the MyData resource. Any RoutedEventHandler or EventHander event can be handled, which should cover nearly all events from any type of UI control. The Button control's Click event, for example, is a RoutedEventHandler, as are most Silverlight control events.

    (this is only possible btw, thanks to the relaxed delegate support in the current versions of C# and VB)

    The same technique will work to call Cancel(), and presumably AddNewItem() and RemoveItem() at some point (though with RemoveItem() we'll also need a way to pass in a parameter value to specify the item to be removed).

    The result is that we're pretty close, at least in concept, to the WPF data provider model, and we avoid the need to write code behind the form for common events like save, cancel, add new and remove.

    Wednesday, August 13, 2008 11:03:32 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
     Tuesday, August 12, 2008

    In Part 1 of this series I discussed the overall architecture and structure of a CSLA Light application. In Part 2 I walked through the creation of a simple editable root business object that supports both the 3-tier and 4-tier mobile object models. In Part 3 I discussed the creation of the Silverlight UI.

    In this post I will discuss the configuration of the web/app server and the data portal.

    All Silverlight applications require a web server, because the Silverlight runtime is hosted in a web page, and the user has to get the web page from a web server (I'm sure there are exceptions to this rule - but in practicality, nearly all Silverlight apps will be downloaded from a web server).

    When using CSLA Light in a 3- or 4-tier client/server model, the CSLA Light client application will communicate with a .NET application server. That application server might be the same server from which the Silverlight app was downloaded, or a different server. It might be hosted in ASP.NET or WAS or a custom Windows Service.

    The CSLA Light data portal uses WCF as its network transport, and so the only requirement is that the server be reachable from the client using the Silverlight WCF implementation.

    CSLA .NET 3.6 includes a special data portal host designed to work with a CSLA Light client. Remember that the CSLA Light data portal is not only going across the network, but it is communicating between the .NET and Silverlight platforms. So while this data portal is functionally similar to the .NET data portal, it has to do some extra work thanks to the cross-platform nature of the scenario.

    Configuring the Server

    The simplest server configuration is to put the data portal host in the same virtual root as the Silverlight application itself, and that's what I've done in this example.

    When the Silverlight application was created, Visual Studio automatically created a host web application project. What I've done is added a WcfPortal.svc file, some web.config entries and a reference to Csla.dll to this project:

    image

    The WcfPortal.svc file is a typical WCF service file:

    <% @ServiceHost Service="Csla.Server.Hosts.Silverlight.WcfPortal" %>

    It references the WcfPortal class that contains the data portal host designed to work with CSLA Light. Notice that it comes from the Csla.Server.Hosts.Silverlight namespace.

    The web project references Csla.dll, and of course also references Library.dll from the Library.Server project. Remember that Library.Server is a .NET Class Library project containing all the business classes, while Library.Client is a Silverlight Class Library project. Since the web server is running .NET, it needs to reference the .NET assembly.

    Finally, the web.config file contains the WCF configuration necessary for the WcfPortal to be available to clients:

    <system.serviceModel>
        <behaviors>
            <serviceBehaviors>
                <behavior name="WcfPortalBehavior">
                    <serviceMetadata httpGetEnabled="true"/>
                    <serviceDebug includeExceptionDetailInFaults="true"/>
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <services>
            <service behaviorConfiguration="WcfPortalBehavior"
                         name="Csla.Server.Hosts.Silverlight.WcfPortal">
                <endpoint address=""
                                binding="basicHttpBinding"
                                contract="Csla.Server.Hosts.Silverlight.IWcfPortal">
                    <identity>
                        <dns value="localhost"/>
                    </identity>
                </endpoint>
            </service>
        </services>
    </system.serviceModel>

    This is pretty standard WCF configuration, defining an endpoint for the IWcfPortal interface from Csla.Server.Hosts.Silverlight. Notice that the name of the service (Csla.Server.Hosts.Silverlight.WcfPortal) matches the name of the service specified in the svc file.

    At this point the app server is configured and ready to go.

    Configuring the Client

    In Silverlight, WCF gets its configuration from a file called ServiceReferences.ClientConfig. In Beta 2 I've found that WCF doesn't consistently read this file, but it does work in the sample app I'm discussing here, and I assume Microsoft will fix whatever is causing the file to sometimes be ignored.

    The config file looks like this:

    <configuration>
        <system.serviceModel>
            <bindings>
                <basicHttpBinding>
                    <binding name="BasicHttpBinding_IWcfPortal"
                                  maxBufferSize="65536"
                                  maxReceivedMessageSize="65536"
                                  receiveTimeout="10" sendTimeout="10">
                    </binding>
                </basicHttpBinding>
            </bindings>
            <client>
                <endpoint 
                    address="http://localhost:1406/SimpleAppWeb/WcfPortal.svc
                    binding="basicHttpBinding"
                    bindingConfiguration="BasicHttpBinding_IWcfPortal"
                    contract="Csla.WcfPortal.IWcfPortal"
                    name="BasicHttpBinding_IWcfPortal" />
            </client>
        </system.serviceModel>
    </configuration>

    Again, pretty standard-looking WCF configuration like you'd probably find in an app.config file. It sets up a client endpoint for IWcfPortal, and provides the URL address to the server.

    You can optionally override the configuration in your code by setting two static properties:

    Csla.DataPortalClient.WcfProxy.DefaultUrl = "http://localhost/root/WcfPortal.svc"
    Csla.DataPortalClient.WcfProxy.DefaultBinding = myBinding

    I've been using the config file approach for the most part, but there are certainly scenarios where you might need to switch to different app server addresses in a more dynamic manner.

    Finally, your application can specify whether the data portal should run in local or remote mode by setting a property:

    Csla.DataPortal.ProxyTypeName = "Csla.DataPortalClient.WcfProxy, Csla"

    By default the data portal is configured for remote mode, using WCF, and so the sample app doesn't do any configuration of the ProxyTypeName. But if you did want to run the data portal in local mode, you'd set the ProxyTypeName to "Local":

    Csla.DataPortal.ProxyTypeName = "Local"

    Then the DataPortal_XYZ methods would run on the Silverlight client and the data portal won't interact with an app server at all. That is particularly useful if you want to directly call remote services from your Silverlight client, and the primary scenario in our design is to support the use of .NET Data Services (code name Astoria) - but that is a topic for another sample app.

    In this sample app the only configuration required is in ServiceReferences.ClientConfig. The data portal defaults to the correct settings to use the values in this file to communicate with a CSLA .NET application server.

    As you can see, configuring the application server and client to use the CSLA Light data portal is not difficult. The data portal relies on standard WCF configuration on both ends of the network connection, allowing you to exploit the power and flexibility of WCF to access the mobile object capabilities provided by the data portal.

    Tuesday, August 12, 2008 9:05:57 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
     Monday, August 11, 2008

    In Part 1 of this series I discussed the overall architecture and structure of a CSLA Light application. In Part 2 I walked through the creation of a simple editable root business object that supports both the 3-tier and 4-tier mobile object models.

    In this post I want to cover the Silverlight UI. Following the theme of this walkthrough, the UI will be very simple so I can illustrate the basic requirements and concepts.

    image

    At this point in time we're working on UI support for authorization, and I'll discuss it when we have something to show.

    UI XAML

    The XAML for the UI is not complex, but does have some interesting differences from typical WPF XAML:

    <UserControl x:Class="SimpleApp.Page"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
        xmlns:csla="clr-namespace:Csla.Wpf;assembly=Csla"
        Width="800" Height="600" Loaded="UserControl_Loaded">
      <Grid x:Name="LayoutRoot" Background="Beige">
        <StackPanel Margin="5,5,5,5">
          <StackPanel Orientation="Horizontal" Margin="5,5,5,5">
            <TextBlock Width="100" Text="Id" />
            <TextBox Width="150" Text="{Binding Id, Mode=TwoWay}" />
            <csla:PropertyStatus Property="Name" Source="{Binding}" />
          </StackPanel>
          <StackPanel Orientation="Horizontal" Margin="5,5,5,5">
            <TextBlock Width="100" Text="Name" />
            <TextBox Width="150" Text="{Binding Name, Mode=TwoWay}" />
          </StackPanel>
          <StackPanel Orientation="Horizontal" Margin="5,5,5,5">
            <TextBlock Width="100" Text="Status" />
            <TextBlock Width="150" Text="{Binding Status}" />
          </StackPanel>
          <StackPanel Orientation="Horizontal" Margin="5,5,5,5">
            <Button Width="50" HorizontalAlignment="Left" Margin="5,5,5,5"
                  Click="Button_Click" Content="Save" />
            <Button Width="50" HorizontalAlignment="Left" Margin="5,5,5,5"
                  Click="Delete_Click" Content="Delete" />
          </StackPanel>
        </StackPanel>
      </Grid>
    </UserControl>

    The primary difference is that the Mode=TwoWay expression is required to get two-way data binding. In WPF the default is two-way, and in Silverlight it appears to be one-way.

    Also, in WPF I would have created a Style for the StackPanel controls to pull the Margin property into a Resources block. While I was able to get a Style working for a TextBlock or TextBox, it would not work for StackPanel. Could be something I did, or a bug or missing feature in Silverlight... Certainly the XAML to do that from WPF doesn't work in Silverlight.

    In WPF I probably would have used a CslaDataProvider control as my binding source. The WPF data provider control model is really nice, and I use it all the time. Unfortunately Silverlight doesn't have a data provider concept, and so obviously that's not here.

    Notice the PropertyStatus control from CSLA .NET. It is in the Csla.Wpf namespace, but will be moving to Csla.Silverlight. PropertyStatus handles both validation and authorization on a per-control basis, and is responsible for the error icon and tooltip in the UI. It also shows warning and information severity broken rules, and so is more comprehensive than the ErrorProvider in Windows Forms or the error support in WPF.

    Creating or Retrieving the Object

    When this form is loaded, the business object is either created or retrieved:

    Private Sub UserControl_Loaded( _
        ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)

      'Library.CustomerEdit.BeginGetCustomer(123, AddressOf BindCustomer)
      Library.CustomerEdit.BeginNewCustomer( _
         Csla.DataPortal.ProxyModes.Auto, AddressOf BindCustomer)

    End Sub

    Remember from Part 2 that the BeginNewCustomer() factory creates a new object, while the BeginGetCustomer() retrieves an existing object (or at least mocks that behavior). I've commented out the BeginGetCustomer() call, so the code shown here is creating a new object.

    Don't mind the ProxyModes.Auto parameter to BeginNewCustomer(). This is something I'm working on to allow a factory method to force the data portal to run in local mode, and will probably be the topic of a future blog post. The Auto setting indicates that the data portal should use its default behavior.

    In either case, the factory methods accept a delegate reference that points to a callback handler. These factories are asynchronous, so the code you see here merely starts the process. You need to implement a callback handler that is invoked when the asynchronous operation is complete. That looks like this:

    Private Sub BindCustomer( _
      ByVal sender As Object, ByVal e As Csla.DataPortalResult(Of Library.CustomerEdit))

      Me.LayoutRoot.DataContext = e.Object

    End Sub

    In C# you could shorten this code by using an anonymous delegate or multi-line lambda instead of creating a totally separate method to handle the callback. Having tried all three approaches, I must say that I still prefer the approach you see here, even in C#, because I find it easier to read the code. Obviously you may find one of the other approaches easier to read - personal preference at work.

    The important thing to remember is that BindCustomer() is called by the data portal when the asynchronous operation is complete. In other words, while the object was being created/retrieved on the server, the user was still able to interact with the UI and the browser. Then, when the server is done with its work, this BindCustomer() method is invoked (much like an event being raised) so you can process the result.

    The DataPortalResult parameter has a couple important properties: Object and Error. The Object property contains a reference to the business object that was created/retrieved. The Error property contains a reference to any exception that may have occurred during the asynchronous operation.

    Please note that the BindCustomer() callback occurs on the UI thread. Behind the scenes the data portal is using WCF, and WCF callbacks in Silverlight always occur on the UI thread. This is really nice, because it means that the developer doesn't have to worry about marshalling the call to the UI thread like they would in WPF.

    In the end, all this method does is to take the business object that was just returned from the data portal, and uses it to set the DataContext for the top-level Grid control in the UI. That causes all the detail controls contained in that Grid control to bind to the object according to the binding expressions in the XAML.

    Saving the Object

    When the Save button is clicked, the object is either inserted or updated into the database. As with CSLA .NET objects, CSLA Light objects keep track of whether they are new or old, and so the UI developer doesn't need to worry about whether the save is an insert or update - that's automatically handled by the data portal.

    Also, like in CSLA .NET, the object keeps track of whether it has been changed. So clicking the Save button when the object has not been changed will result in nothing happening - the object automatically detects that it hasn't been changed and doesn't really invoke the server to do a meaningless update operation.

    In WPF, with CSLA .NET, the Save button probably would have no code, but would work using the concept of commanding and the CslaDataProvider. Unfortunately commanding doesn't exist in Silverlight, nor do data providers. So in Silverlight the Save button behavior is implemented in old-fashioned code-behind event handlers.

    The following code handles the Save button's Click event:

    Private Sub Button_Click( _
      ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)

      Dim cust = CType(Me.LayoutRoot.DataContext, Library.CustomerEdit)
      cust.BeginSave(AddressOf BindSaveResult)

    End Sub

    First, the business object is retrieved from the form's DataContext, and the object is cast into the right type.

    Then the BeginSave() method is called to start the save process. Again, all server communication must be asynchronous in Silverlight and so the data portal is asynchronous. This means the save operation is asynchronous as well, and so a callback delegate is passed as a parameter.

    Remember that the Click event handler exits immediately and the user can interact with the UI and browser while the save operation is occurring on the server. The UI will probably need to take steps to disable important buttons and controls to prevent the user from interacting with the object (or flooding the server with repeated save requests or something) while the asynchronous operation is executing.

    That BindSaveResult() method will be invoked when the asynchronous operation is complete:

    Private Sub BindSaveResult( _
      ByVal sender As Object, ByVal e As Csla.Core.SavedEventArgs)

      Me.LayoutRoot.DataContext = e.NewObject

    End Sub

    Just like in CSLA .NET, the data portal in CSLA Light returns a new object as a result of the save operation. This means that the UI must be rebound to use the new object when the operation is complete.

    Deleting the Object

    When the Delete button is clicked, the object is deleted from the database. CSLA Light supports both immediate and deferred deletion. In this sample app I'm illustrating deferred deletion, where the object has been retrieved, it is marked for deletion and then saved. Here's the Click handler behind the button:

    Private Sub Delete_Click( _
      ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)

      Dim cust = CType(Me.LayoutRoot.DataContext, Library.CustomerEdit)
      cust.Delete()
      cust.BeginSave(AddressOf BindSaveResult)

    End Sub

    The code is much like that for the Save button, but in this case the Delete() method is called on the object before it is saved. This marks the object to be deleted, so the data portal automatically routes the call to DataPortal_DeleteSelf() so that occurs.

    The resulting object (which is now considered a "new" object) is bound to the UI in the same BindSaveResult() method I discussed earlier.

    Summary

    In this post I have walked through the basic creation of a Silverlight UI that binds to a business object. The object is created or retrieved through the data portal, and then is inserted, updated or deleted through the data portal.

    It is probably worth noting that CSLA .NET 3.6 will also include the same asynchronous data portal concepts shown here, and so the same basic code can be written behind a WPF, Windows Forms or even Web Forms UI.

    Monday, August 11, 2008 11:50:41 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
     Sunday, August 03, 2008

    I've put another prerelease of CSLA Light (CSLA for Silverlight) and CSLA .NET 3.6 online at www.lhotka.net/cslalight/download.aspx.

    1. Check out the new identity base classes in Csla.Security and Csla.Silverlight.Security - they are pretty darn cool!
    2. Check out the new Validator UI control - I think that is really cool!! It won't keep that name, because we're merging the Authorizer functionality directly into that control, so the result will be a consolidated control that does both things - we don't have a name for it yet...
    3. I'm pretty sure the ClientContext and GlobalContext work right, but the unit tests don't show that - so I'd recommend viewing that functionality with suspicion.
    4. I know some of the security tests don't work. Authentication is still evolving and some of the test apps are lagging a bit behind.

    Please remember, these are very early preview builds. They are not stable. They are not complete. They may or may not work for you. They are not supported.

    We have found, in testing, that Silverlight Beta 2 is not entirely stable. And that WCF in Silverlight is particularly unstable. If you run the unit tests in Silverlight you'll probably find what we find - that they randomly fail sometimes. They'll run. They'll fail. Then they'll run again. With no discernable pattern. Quite frustrating, but I guess this is the nature of working on a beta platform.

    I have also put the sample app I've been blogging about at http://www.lhotka.net/files/cslalight/SimpleCslaLightAppvb-080803.zip. This sample app shows all the things I've talked about in my Part 1 and Part 2 posts, and I'll be coming out with more posts in the series in the next few days.

    Sunday, August 03, 2008 10:47:53 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
     Monday, July 28, 2008

    In Part 1 I discussed the high level architectural options offered by CSLA Light. In Part 2 I'll start walking through the implementation of the 3-tier mobile object model (which pretty much also covers the 4-tier mobile object model as well).

    I'll start with the center of the application: the business layer. As I discussed in Part 1, the business layer spans Silverlight and .NET and defines mobile objects that are capable of moving between the Silverlight client and the .NET web/app server.

    (CSLA Light supports both C# and VB - and probably most other languages too - so the fact that this particular demo is in VB shouldn't be taken as an indication that anything only works with VB. Rather, I consciously switch between VB and C# for each demo I write, and it is VB's turn.)

    This is intended to be as simple a demo as I can create, and still show something useful. To that end, the demo has exactly one object, with three properties.

    Library.Client Setup

    The Library.Client project is a Silverlight Class Library. This means it compiles for the Silverlight runtime and can only contain code that will run on the Silverlight client.

    It is important to realize that when objects serialize and deserialize, they must have the exact same type name. This includes the assembly name, namespace and type name. The standard .NET way to represent an assembly qualified type name is something like:

    "MyNamespace.MyType, MyAssembly"

    Since the business objects in Library.Client must be compatible with those in Library.Server, both assemblies must compile to the same assembly name, and must use the same namespaces.

    To accomplish this, the project's properties must be changed so the Assembly name and Root namespace do not include the ".Client" part of the name:

    image

    I've changed them both to "Library", so this will compile to Library.dll and the root namespace is Library.

    Library.Server Setup

    The same changes to the Assembly name and Root namespace are made to the .NET Class Library project, Library.Server:

    image

    This project also builds a Library.dll with a root namespace of Library.

    If you sign either project, you must sign both projects, and you must use the same key. That way they end up with the same effective assembly name, even though they are on different runtimes.

    The end result is that a class in one project is serializable into and out of a class in the other project.

    CustomerEdit Class Declaration

    The CustomerEdit class exists in both the Library.Client and Library.Server projects, so the code is compiled into both runtimes. This means CustomerEdit can serialize and move between the Silverlight and .NET runtimes.

    The class declaration should be pretty familiar to any CSLA .NET developer:

    Imports Csla
    Imports Csla.Serialization

    <Serializable()> _
    Public Class CustomerEdit
      Inherits BusinessBase(Of CustomerEdit)

    The only odd or new thing here might be the inclusion of the Csla.Serialization namespace. Silverlight has no concept of a Serializable attribute, so CSLA Light supplies one (along with NonSerialized). So in CSLA .NET this namespace exists, but is essentially empty, while in CSLA Light the namespace includes definitions for the attributes "missing" from Silverlight. The end result is that a Serializable class in .NET can compile in Silverlight.

    Property Declarations

    The property declarations are standard CSLA .NET 3.5 fare:

    Private Shared IdProperty As PropertyInfo(Of Integer) = _
      RegisterProperty(New PropertyInfo(Of Integer)("Id"))
    ''' <Summary>
    ''' Gets and sets the Id value.
    ''' </Summary>
    Public Property Id() As Integer
      Get
        Return GetProperty(IdProperty)
      End Get
      Set(ByVal value As Integer)
        SetProperty(IdProperty, value)
      End Set
    End Property

    Private Shared NameProperty As PropertyInfo(Of String) = _
      RegisterProperty(New PropertyInfo(Of String)("Name"))
    ''' <Summary>
    ''' Gets and sets the Name value.
    ''' </Summary>
    Public Property Name() As String
      Get
        Return GetProperty(NameProperty)
      End Get
      Set(ByVal value As String)
        SetProperty(NameProperty, value)
      End Set
    End Property

    Private Shared StatusProperty As PropertyInfo(Of String) = _
      RegisterProperty(New PropertyInfo(Of String)("Status"))
    ''' <Summary>
    ''' Gets and sets the Status value.
    ''' </Summary>
    Public Property Status() As String
      Get
        Return GetProperty(StatusProperty)
      End Get
      Set(ByVal value As String)
        SetProperty(StatusProperty, value)
      End Set
    End Property

    This code compiles in both CSLA Light and CSLA .NET. Notice that I'm using managed backing fields. This allows the CSLA Light serialization to automatically serialize the field values to/from the .NET server.

    You can use private backing fields if you choose. If you do use private backing fields, then you'll need to override OnGetState() and OnSetState() and get/set each private field value into the serialization stream. This process is much like the old PropertyBag concept from VB6, and is necessary because Silverlight's support for reflection is insufficient to automate the process.

    By using managed backing fields, I avoid having to do that manual work, but I want to be clear that you ultimately get to choose between the two approaches.

    Silverlight vs .NET Code

    The rest of this post will cover code that is either Silverlight-only or .NET-only. In this sample I've chosen to use compiler directives to separate the code, even though it is all in one file. You can certainly use partial classes instead, and based on this forum thread that might be the preferred approach.

    But in this sample, you'll find the following basic structure:

    #If Silverlight Then
      ' Silverlight-only code
    #Else
      ' .NET-only code
    #End If

    Compiler directives or partial classes work fine and achieve the same end result.

    Silverlight Factory Methods

    Now we're at a point where the Silverlight and .NET code may diverge. In Silverlight, any server communication must be asynchronous. This means that the CSLA Light data portal is asynchronous, and thus your factory methods must also be asynchronous.

    We've added asynchronous capabilities to the CSLA .NET data portal as well, so you can use this same async factory approach there as well, but typically I don't think that makes a lot of sense.

    In any case, the factory methods are designed to be called by the Silverlight UI, and they look like this:

    Public Shared Sub BeginNewCustomer( _
        ByVal proxyMode As DataPortal.ProxyModes, _
        ByVal callback As EventHandler(Of DataPortalResult(Of CustomerEdit)))
      Dim dp As New DataPortal(Of CustomerEdit)(proxyMode)
      AddHandler dp.CreateCompleted, callback
      dp.BeginCreate()
    End Sub

    Public Shared Sub BeginGetCustomer( _
        ByVal id As Integer, _
        ByVal callback As EventHandler(Of DataPortalResult(Of CustomerEdit)))
      Dim dp As New DataPortal(Of CustomerEdit)
      AddHandler dp.FetchCompleted, callback
      dp.BeginFetch(New SingleCriteria(Of CustomerEdit, Integer)(id))
    End Sub

    In both the create and fetch scenarios the steps are:

    1. Create an instance of the data portal (optionally forcing it to run in local mode)
    2. Add a handler for the async completed event
    3. Call the data portal method to begin the async operation

    For this example, I'm requiring that the UI developer pass in the event handler method. In VB this is done with the AddressOf command, and in C# it is a delegate, an anonymous delegate or a multi-line lambda. I'll get to the UI code in a future blog post.

    When the data portal is in remote mode, it communicates with a web server running a special CSLA .NET data portal host that is compatible with CSLA Light. I'll get into the server configuration in a later blog post.

    The result is that a BeginCreate() or BeginFetch() call results in the data portal using WCF to call the server. When the call gets to the .NET server, it follows much of my discussion in this blog post. A few things have changed in terms of how a factory object is created, but that's a topic for a different sample app.

    In this sample app, the client-side data portal calls are routed directly to server-side DataPortal_XYZ methods. These are normal CSLA .NET DataPortal_XYZ methods, and are entirely unaffected by the fact that the client is Silverlight.

    Silverlight Constructor

    The one other bit of important code in the Silverlight-only area is a Public constructor:

    Public Sub New()
      ' required by MobileFormatter
    End Sub

    The serializer used by CSLA Light is the MobileFormatter, and in Silverlight this serializer requires a Public default constructor on any object it deserializes. This is because Silverlight doesn't allow the use of reflection to create an object with a non-Public constructor like you can in .NET.

    This is unfortunate, because a UI developer might accidentally try to use the New keyword to create an instance of the object, like:

    Dim cust As New CustomerEdit

    While this would compile, it won't really work - not as expected anyway. The UI developer really needs to call one of the factory methods shown earlier to create or retrieve the object successfully. This is why CSLA .NET constructors are typically non-Public, to act as a reminder to the UI developer to use the factory methods. In Silverlight you'll just have to use code reviews to ensure that the UI code is correct.

    .NET Constructor

    Now let's shift to the .NET-only code. In the .NET-only code there's also a definition of a default constructor, but this one is Private:

    Private Sub New()
      ' require use of factory methods
    End Sub

    This is standard CSLA .NET coding style, using a non-Public constructor to force the UI developer to use the factory methods. In .NET the MobileFormatter does the same thing as the BinaryFormatter or NetDataContractSerializer, and it creates an instance of the object even though it has a non-Public constructor.

    .NET DataPortal_XYZ Methods

    To keep this sample as easy as possible, the DataPortal_XYZ methods don't actually call a data access layer or talk to a database. They merely set a property on the object to indicate which of the methods was invoked, and where it ran (on Silverlight or on .NET):

    Protected Overrides Sub DataPortal_Create()
      LoadProperty(StatusProperty, _
           "Created " & ApplicationContext.ExecutionLocation.ToString)
      MyBase.DataPortal_Create()
    End Sub

    Private Overloads Sub DataPortal_Fetch( _
            ByVal criteria As SingleCriteria(Of CustomerEdit, Integer))
      LoadProperty(StatusProperty, _
            "Retrieved " & ApplicationContext.ExecutionLocation.ToString)
      LoadProperty(IdProperty, criteria.Value)
      LoadProperty(NameProperty, "Test " & criteria.Value)
    End Sub

    Protected Overrides Sub DataPortal_Insert()
      LoadProperty(StatusProperty, _
          "Inserted " & ApplicationContext.ExecutionLocation.ToString)
    End Sub

    Protected Overrides Sub DataPortal_Update()
      LoadProperty(StatusProperty, _
            "Updated " & ApplicationContext.ExecutionLocation.ToString)
    End Sub

    Protected Overrides Sub DataPortal_DeleteSelf()
      LoadProperty(StatusProperty, _
           "Deleted " & ApplicationContext.ExecutionLocation.ToString)
    End Sub

    There's nothing special about these methods. You could write this code in CSLA .NET 3.5 for a pure .NET application and it would work just fine. Sure, it is simplistic, in that I'm just loading some hard-coded values into the object's properties, but you should be able to imagine these methods calling your data access layer and getting back a DataReader, DTO, entity object or whatever you are using; and then loading the object's property values from that data source.

    Summary

    What I hope you take away from this post is that you can take an existing CSLA .NET 3.5 class (that uses managed backing fields), and get it running in CSLA Light too with very little effort. In fact, all you need to do is:

    1. Add an #If Silverlight compiler directive
    2. Put the Silverlight-only factory methods and Public constructor in the Silverlight area
    3. Put your existing .NET-only factory methods and non-Public constructor in the .NET area
    4. Put your existing DataPortal_XYZ methods in the .NET area
    5. Link the file into a Silverlight Class Library

    In future posts I'll cover the Silverlight UI and the CSLA Light data portal configuration, including the CSLA .NET data portal server.

    Monday, July 28, 2008 5:47:05 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

    In preparation for the next public release of CSLA Light (CSLA .NET for Silverlight), I'm going to do a series of posts describing the basic process of creating a CSLA Light application. This first post will provide a high-level overview of the project structure and some concepts.

    First, it is important to realize that CSLA Light will support three primary physical architectures: a 3-tier (or SOA) model, a 3-tier mobile objects model and a 4-tier mobile objects model. At all times CSLA Light follows the same n-layer logical architecture of CSLA .NET, where the application has the following layers:

    1. Presentation/UI
    2. Business
    3. Data Access
    4. Data Storage

    The primary goal of CSLA Light and CSLA .NET is to support the creation of the Business layer in such a way that the interface points to the Presentation/UI layer and to the Data Access layer are clearly defined.

    To a small degree, CSLA Light will assist in the creation of the Presentation/UI layer by providing some custom Silverlight controls that solve common issues and reduce UI code.

    Like CSLA .NET, CSLA Light is not an ORM and does not really care how you talk to your database. It simply defines a set of CRUD operators - locations where you should invoke your Data Access layer to retrieve and update data.

    3-Tier or SOA Model

    If you use CSLA Light in a 3-tier (or SOA) model, your physical tiers are:

    1. Silverlight
    2. Service
    3. Database

    You can treat these as tiers, or as separate applications where you use SOA concepts for communication between the applications. That's really up to you. In this case the focus of CSLA Light is entirely on the Silverlight tier. In that Silverlight tier, you'll have the following logical layers:

    1. Presentation/UI
    2. Business
    3. Data Access/Service Facade

    To do this, you configure the CSLA Light data portal to run in local mode and it calls the DataPortal_XYZ methods right there in the Silverlight client tier. You implement the DataPortal_XYZ methods to invoke remote services in the Service tier. CSLA Light doesn't care what those services look like or how they are implemented. They could be asmx, WCF, RSS, JSON, RESTful, SOAP-based - it just doesn't matter. If you can call it from Silverlight, you can use it.

    The CSLA Light data portal is designed to be asynchronous, because any calls to remote services in Silverlight will be an asynchronous operation. In other words, the data portal is designed to support you as you call these remote services asynchronously.

    The only requirement is that by the time your async DataPortal_XYZ method completes, that the object's data be created, retrieved, updated or deleted.

    This is the simplest of the CSLA Light architectures (assuming the services and database already exist) because you just create one project, a Silverlight Application, and all your code goes into that project. Or perhaps you create two projects, a Silverlight Application for the UI and a Silverlight Class Library for your business objects, but even that is pretty straightforward.

    3-Tier Mobile Objects Model

    If you use CSLA Light in a 3-tier mobile objects model, your physical tiers are:

    1. Silverlight
    2. Data portal server
    3. Database

    This is more like a traditional CSLA .NET model, because the data portal is used to communicate between the Business layer on the Silverlight tier and the Business layer on the Data portal server tier. Your business objects literally move back and forth between those two tiers - just like they do between the client and server tiers in a CSLA .NET 3-tier model.

    One interesting bit of information here though, is that your business objects are not just moving between tiers, but they are moving between platforms. On Silverlight they are CSLA Light objects in the Silverlight runtime, and on the Data portal server they are CSLA .NET objects in the .NET runtime. The CSLA Light data portal makes this possible, and the result is really very cool, because most of your business object code is written one time and yet runs in both locations!

    The Data Access layer only exists on the Data portal server, in .NET. So the Silverlight tier relies on the data portal, and the .NET server, for all create, fetch, update and delete behaviors. Also, that data access code is not even deployed to the client.

    However, the client does have most business and validation and authorization logic. So the user experience is rich, interactive and immediate - just like a WPF or Windows Forms user experience.

    This architecture is a little more complex, and requires that you create several projects. The following figure shows a simple solution with the required projects:

    image

    Here's an explanation of the projects:

    • SimpleAppWeb: web app hosting the Silverlight xap file and the data portal service
    • Library.Client: Silverlight Class Library containing business classes
    • Library.Server: .NET Class Library containing business classes
    • SimpleApp: Silverlight Application containing the Silverlight UI application

    The big thing to notice here, is that the CustomerEdit.vb class exists in both Library.Client and Library.Server. In Library.Server it is a linked file, meaning that the project merely links to the file that exists in Library.Client. You can tell this by the different icon glyph in Solution Explorer.

    The reason for this is that CustomerEdit.vb contains code for a business object that moves between the Silverlight client and the .NET server. It contains code that compiles in both environments.

    You can then use compiler directives or partial classes to implement code in that class that is Silverlight-only or .NET-only. I started a thread on the forum about which is better - people seem to prefer partial classes, though compiler directives is certainly a clean solution as well.

    4-Tier Mobile Objects Model

    If you use CSLA Light in a 4-tier mobile objects model, your physical tiers are:

    1. Silverlight
    2. Data portal server (web)
    3. Data portal server (application)
    4. Database

    From a Silverlight perspective this is exactly the same as the 3-tier model. The difference is purely in how the CSLA .NET data portal is configured on the web server (#2). In this case, the CSLA .NET data portal is configured to be in remote mode, so all data portal calls on machine 2 are relayed to machine 3.

    This is totally normal CSLA .NET behavior, and doesn't change how anything else works. But it can be a useful physical architecture in the case that the web server (#2) that is exposed to the Internet so the Silverlight client can interact with it, is not allowed to talk to the database. In other words, you could have an external firewall between 1 and 2, and then an internal firewall between 2 and 3. So machine 2 is in a DMZ, and machine 3 is the only one allowed to talk to the database.

    What I'm describing is a pretty standard web deployment model for CSLA .NET - but with a CSLA Light client out there, instead of a simple web page.

    As I continue this series I'll dig into the code of this simple application, showing how to create the business class, configure the data portal and set up the Silverlight UI project.

    Monday, July 28, 2008 10:26:08 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
     Thursday, July 17, 2008

    If you've tried to do any unit testing in Silverlight, you may have run into an interesting issue. Many times, unit tests expect exceptions. Tests are written to ensure that an exception occurs as expected. That's a standard concept in most unit testing frameworks for .NET.

    In Silverlight, there's an "expected CLR behavior" where the debugger will break on exceptions that are actually handled by user code - treating them like they aren't handled. See this thread for some more detail:

    http://silverlight.net/forums/p/20678/72377.aspx#72377

    The result of this, is that you have to employ some ugly workarounds, or you need to press F5 for each of your tests where you expect an exception.

    We're running into this issue in a big way with CSLA Light (CSLA .NET for Silverlight), because we're creating lots and lots of unit tests, and a fair number of them are testing to make sure exceptions occur when we expect them.

    Of course our unit testing framework (UnitDriven) uses reflection to run each test method - just like MSTest or nunit - and so even though we are handling the exception in user code the debugger insists on breaking in the test methods themselves where the exceptions occur.

    Again, there are workarounds. They prevent you from using the debugger to walk through your tests - but at least they exist. The whole thing is really sad though - given that this is apparently intended behavior.

    Thursday, July 17, 2008 10:44:51 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
     Tuesday, July 15, 2008

    I have put a very early preview release of CSLA Light and CSLA .NET 3.6 online at www.lhotka.net/cslalight/download.aspx.

    There is no sample app at this point, so you'll have to look at the unit tests in cslalighttest and cslatest to figure out how to use the various features.

    Obviously this is very early code, but it is healthy to release early and often, so here we go :)

    One side-effect of our work with CSLA Light is that we discovered that testing asynchronous methods is really hard with nunit and MSTest, and impossible with the Silverlight unit test framework provided by Microsoft. And yet in Silverlight, async methods are commonly required, and for parity a number of async features are now also in CSLA .NET. And we need to have unit tests for them.

    To address this issue, we ended up creating our own Silverlight unit testing framework, and an add-on framework for nunit or MSTest. This allows us to write a common set of test code that runs in both Silverlight and .NET so we can test both, and establish that we have parity between them.

    Earier today, Justin split this testing framework out of CSLA and we put it up on CodePlex, calling it UnitDriven. The CSLA Light project and Magenic are donating the code to the community as an open-source project, because it can be used to build async unit tests for any app, not just for CSLA Light.

    Tuesday, July 15, 2008 6:40:52 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
     Monday, July 14, 2008

    While most people use CSLA .NET because it provides support for data binding, validation, business rules and authorization, I personally think the coolest part of the framework is its support for mobile objects. This support is provided by the data portal, which provides both an abstract persistence model for business objects, as well as an implementation of mobile objects with location and network transparency.

    CSLA Light will also include a data portal that works in a manner similar to the one in CSLA .NET. In fact, the two are complimentary - the CSLA Light data portal talks to the CSLA .NET data portal, because the client is running Silverlight and the server is running .NET. This occurs when the CSLA Light data portal is running in "remote" mode - meaning it is talking to a remote data portal server.

    The CSLA Light data portal can also run in "local" mode, which means that the "data access" code runs on the Silverlight client. In reality, this probably means that your client-side code is directly calling some external service - an asmx web service, a WCF service, ADO.NET data services, etc. So the fact is that the data access is still on some server somewhere, but you aren't using the data portal to get from the client to that server.

    As in .NET, when using the data portal in local mode things are pretty simple. A call to the data portal to fetch an object simply results in a call to a DataPortal_Fetch() method in your object, and the object is running on the client in Silverlight. What you do in that DataPortal_Fetch() method is entirely up to you, as long as the object is populated with data by the time the call completes.

    When you use the remote data portal there are more options. Things are somewhat different from the existing .NET data portal. The following figure will help explain.

    image

    The CSLA Light data portal interacts with a server (probably a web server, though it could be a Windows Server 2008 running WAS) through WCF. That server is running CSLA .NET 3.6, which includes data portal support to listen for CSLA Light data portal requests. Objects are serialized to/from CSLA Light using the MobileFormatter, which is a serializer included in both CSLA Light and CSLA .NET that provides a subset of the functionality provided by the BinaryFormatter (or NetDataContractSerializer), targeted at the CSLA scenario.

    On the web server, CSLA .NET 3.6 receives the inbound client request. Any objects sent from the client to the server are deserialized (including any criteria objects or business objects). At this point there are two ways the process will work.

    The default option is that the call from the client is "echoed" into the standard CSLA .NET data portal. In other words, if the client calls Fetch() on the data portal, that call is relayed into the standard data portal as a Fetch() request. This means that the .NET data portal applies its normal process and runs in local or remote mode and ultimately creates an instance of your business object and calls its DataPortal_Fetch() method. Remember that this is all happening in .NET on the server(s). The resulting business object is then returned through the .NET data portal to the web server, and from there through the Silverlight data portal to the client.

    So by default, the .NET data portal running on the web server (in the diagram) is a pass-through from Silverlight into .NET. The end result is that the Silverlight data portal works just like the .NET data portal does today.

    While the default is good and easy, it may not always be ideal. You may not trust the code running in Silverlight on the client. You may be concerned that the code has been compromised, that somehow a malicious user cracked into the Silverlight runtime, mucked around with your code and bypassed your logic. Thus far no one has established that this can be done, but I can understand the concern.

    In that case, another option is that the business class (on the .NET side) can have a MobileFactory attribute attached:

    [MobileFactory("MyLibrary.CustomerFactory,MyLibrary", "Create", "Fetch", "Update", "Delete")]
    public class Customer : BusinessBase<Customer>

    If this attribute is applied, the .NET data portal will create an instance of the type specified in the attribute, and will call methods on that factory object instead of on the business object. In other words, a call that would have gone to DataPortal_Fetch() will now go to a method matching the third parameter of the attribute - in this example a method called Fetch().

    The factory object is responsible for creating, initializing and returning the object from create/fetch/update operations. Delete returns nothing. How the factory object does this is up to the factory author - you. I suspect a very common implementation will be for the factory method to do extra business checks (validation/authorization) to decide if the client call is valid, and if it is valid then the factory will just echo the call into the .NET data portal. So you might write something like this in a factory:

    public object Fetch(SingleCriteria<Customer, int> criteria)
    {
      // do extra validation/authorization checks here
      if (allChecksPassed)
        return DataPortal.Fetch(criteria);
      else
        throw new Exception("Bad client request");
    }

    A colleague of mine at Magenic, Nermin Dibek, suggested an interesting enhancement to this MobileFactory model, which I'll include in the implementation. As a configuration option, you can specify a "factory of factories" object. The default behavior is to take the type name in the first parameter and use it to create an instance of the factory object. But if you'd like, you can create your own "factory creator" object that takes that first parameter and uses it however you'd like to create an instance of the factory. This would allow you to substitute MyTestLibrary for MyLibrary when you wanted to use a set of test factories instead of the production versions, and that sort of thing.

    It is my intent to extend this MobileFactory concept into the .NET data portal itself (in CSLA .NET 3.6), so in a pure-.NET scenario you'd have comparable options, like this figure:

    image

    The data portal would default to its existing behavior, which would be unchanged. However, you'd be able to apply an ObjectFactory attribute to your business classes to indicate that the data portal should route its calls to your factory object rather than to the DataPortal_XYZ methods.

    The only catch here, is that your factory objects then assume responsibility for managing the status values (IsNew, IsDirty, etc) of the object (and its child objects, etc). The data portal essentially steps out of the picture entirely - leaving you to do all the work of creating and manipulating the business object as necessary. However, this does open up some interesting alternatives for persisting objects even though the solution is less automated than the current implementation.

    The CSLA Light part of what I've discussed here is in the current 3.6 code in Subversion (svn://svn.lhotka.net/csla/branches/cslacs36 and svn://svn.lhotka.net/csla/trunk/cslalightcs). The ObjectFactory support for CSLA .NET itself will probably happen in a few weeks.

    Monday, July 14, 2008 9:41:52 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
     Tuesday, June 24, 2008

    With serialization largely out of the way - or at least under control - as described in a recent blog post, we've been able to put some focus on a couple other key areas.

    N-Level Undo

    The n-level undo functionality in CSLA .NET relies on reflection against private fields. Obviously that's not possible in Silverlight. Fortunately the serialization scheme we're using means that there's already a mechanism for trapping the values stored in the field manager. And there's the OnGetState()/OnSetState() methods that allow a business developer to trap/restore values in their private fields (if they choose). So UndoableBase had to be altered to use these techniques rather than using reflection. The end result is the same, which is what really matters.

    We opted not to replicate IEditableObject into CSLA Light. It is a .NET interface used by Windows Forms data binding, and is the source of never-ending pain thanks to all the edge cases and idiosyncrasies around this, seemingly simple, interface. Of course the interface isn't used by Silverlight (or WPF), and so isn't necessary. The effect of this choice is to simplify quite a bit of the n-level undo code, while at the same time preserving the shape of the pre-existing public interface for all objects. In other words, BeginEdit(), CancelEdit() and ApplyEdit() work as expected, but you can't use IEditableObject to get at its versions of those methods.

    Justin just ran into a strange issue with BusinessListBase, where an attempt to iterate through the items in the list caused a strange runtime exception from somewhere deep in the bowels of the Silverlight runtime. It appears there's some issue with a subclass of a collection iterating through its own items in a foreach loop. A for loop works fine however, so we have a workaround.

    Ultimately however, the ability to easily implement a Cancel button, including when using modal dialogs (which can be simulated in Silverlight) is supported

    Data Portal

    The data portal is coming along pretty well too. It supports a provider model, conceptually similar to the data portal in .NET. And we currently have two providers: local and WCF.

    One issue we're facing here is that Silverlight has no configuration subsystem comparable to System.Configuration. So there's no easy way to get configuration data from an "app.config" file or equivalent. At the moment I've come up with a code-based configuration scheme - but (unless Microsoft puts out a solution soon) we'll probably end up creating some embedded resource-based configuration subsystem of our own.

    The data portal itself is asynchronous. This changes the way the UI code interacts with the data portal when compared to .NET code. Rather than just calling DataPortal.Fetch() to get an object, in Silverlight the UI must call a BeginFetch() method to start the process and handle a completed event to process any results when they return.

    This means the UI code looks something like this:

    var dp = new DataPortal<MockEditableRoot>();
    dp.FetchCompleted += new EventHandler<DataPortalResult<MockEditableRoot>>(dp_FetchCompleted);
    dp.BeginFetch();

    This code starts the process, and the dp_FetchCompleted is invoked (on the UI thread) when the call is complete:

    private void dp_FetchCompleted(object sender, DataPortalResult<MockEditableRoot> e)
    {
      this.DataContext = e.Object;
    }

    Alternately you can wrap this code into a factory method and completed event provided by the business class. That is a little closer to the typical CSLA .NET model - but is still async, and the UI still must handle the result in a callback event handler.

    Local Data Portal

    When using the data portal in local mode, it calls DataPortal_XYZ methods, much like the .NET data portal. There are a couple interesting differences however. The first being that the DataPortal_XYZ methods must be public in scope. Remember, no private reflection, so only public methods can be called.

    I debated about using an interface-based approach, but decided against it for a couple reasons. First, it would be dissimilar to the existing .NET approach. Second, it would mean that your DataPortal_XYZ methods couldn't be strongly typed - they'd have to accept parameters of type object and you'd have to cast them to something meaningful.

    The second difference flows from the fact that most server-related activities in Silverlight are asynchronous. Most DataPortal_XYZ methods, therefore, will be invoking async server calls and getting the results from a callback event. So all DataPortal_XYZ methods are provided a delegate they can use to do a callback to indicate completion. In a simple (synchronous) example it looks like this:

    public void DataPortal_Insert(
      Csla.DataPortalClient.LocalProxy<MockEditableRoot>.CompletedHandler handler)
    {
      LoadProperty<string>(DataPortalMethodProperty, "insert");
      handler(this, null);
    }

    The DataPortal_Insert() method accepts a CompletedHandler parameter it can use to indicate completion. The call to handler() is the completion call, and the first parameter is the resulting business object, while the second is an Exception object if you want to indicate failure.

    In an asynchronous example things are a bit more complex. And the async scenario is the most common. Typically when using a "local" data portal you'd be doing so because you want to call some web service or data service from Silverlight. And since all the server call technologies in Silverlight are async, your DataPortal_XYZ method will almost certainly be invoking some async service. So more normal code might look like this:

    public void DataPortal_Insert(
      Csla.DataPortalClient.LocalProxy<MockEditableRoot>.CompletedHandler handler)
    {
      var svc = new Csla.Testing.Business.TestService.TestServiceClient();
      svc.InsertDataCompleted +=
        new EventHandler<Csla.Testing.Business.TestService.InsertDataCompletedEventArgs>
          (svc_InsertDataCompleted);
      svc.InsertData(GetProperty<string>(DataPortalMethodProperty), handler);
    }

    void svc_InsertDataCompleted(
      object sender, Csla.Testing.Business.TestService.InsertDataCompletedEventArgs e)
    {
      var handler = (Csla.DataPortalClient.LocalProxy<MockEditableRoot>.CompletedHandler)e.UserState;
      handler((MockEditableRoot)e.Result, e.Error);
    }

    This looks a bit odd, but after you do a bit of Silverlight programming this pattern becomes second nature.

    The DataPortal_XYZ method sets up and starts the call - passing parameters to the service, and one parameter that is "user state", which is extra (doesn't go to the server, but stays on the client). Notice that before making the InsertDataAsync() call, which is the call to the service, the code hooks the InsertDataCompleted event - this is the event that will be raised (on the UI thread) when the service call completes.

    The svc_InsertDataCompleted() method is the event handler. This is where you write the code to handle the results from the service call. When using the data portal, this is where you call back into CSLA to indicate that the call is complete. Ultimately CSLA will return the result to the UI code, but this mechanism allows CSLA to do any extra processing between the DP_XYZ call and the UI so it can manage the state of your business object.

    You can also shrink this by using a lambda:

    public void DataPortal_Insert(
      Csla.DataPortalClient.LocalProxy<MockEditableRoot>.CompletedHandler handler)
    {
      var svc = new Csla.Testing.Business.TestService.TestServiceClient();
      svc.InsertDataCompleted += (o, e) => { handler((MockEditableRoot)e.Result, e.Error); };
      svc.InsertDataAsync(GetProperty<string>(DataPortalMethodProperty));
    }

    That eliminates the need for a separate event handler method and simplifies the code.

    Remote Data Portal

    The remote data portal option works very much like the normal .NET data portal, and is generally simpler to use that the local data portal. When the data portal is configured to use the WcfProxy, it will use WCF to communicate with a CSLA .NET data portal on the web/app server.

    In this scenario you need a web or app server that is hosting a CSLA .NET data portal - the .NET end of the CSLA Light data portal. The CSLA Light code running on the Silverlight client will call the CSLA .NET code running on the app server.

    When using a remote data portal, the Silverlight business object will not include any DataPortal_XYZ methods. The DataPortal_XYZ methods will only be implemented in the .NET code, and will only exist on the server. The client-side code will still call the data portal, but the call will be automatically routed through WCF to the app server.

    This is exactly the same kind of behavior you'd get from the existing .NET data portal - you can choose to use a local or remote data portal, but the business object and UI code are the same either way (with the exception that a local data portal requires implementation of DataPortal_XYZ methods).

    On the app server, which is running CSLA .NET, requests will come in from the Silverlight client. These requests can be handled in one of two ways.

    The default is for the client call to be routed into the CSLA .NET data portal, and the rest of the processing is normal CSLA .NET processing. In other words, a Silverlight Fetch() call results in a DataPortal.Fetch() call on the app server, which runs the DataPortal_Fetch() method just like it always has. The result of the data portal call on the app server is then returned to the Silverlight client.

    I call that the "pass-through" mode because the server-side data portal just passes the client call through to the "real" data portal. And this is a great option for when you trust the client that is running the Silverlight app, because it requires the least amount of code and provides the simplest solution.

    But if you don't trust the Silverlight client. If you are worried that someone will break into the Silverlight runtime and somehow put bad data into your object's fields (perhaps bypassing your business logic, etc), then extra precautions are required. To address that concern, the server-side data portal can optionally invoke an "observer" or "factory" (I'm still debating the name of this thing).

    To do this, on your server-side business object code (in the server-only partial class) you use the MobileFactory attribute to specify the type name of the factory object, and the method names to be called for create, fetch, update and delete operations (the only operations the data portal supports).

    [MobileFactory("MyProject.MyFactory, MyProject", "Create", "Fetch", "Update", "Delete")]
    public partial class MockEditableRoot

    Then you must implement the factory class:

    public class MyFactory
    {
      public object Create(object criteria)
      {
        // create, initialize and return new object here
      }

      public object Fetch(object criteria)
      {
        // create, load and return object here 
      }

      public object Update(object inbound)
      {
        // insert, update or delete object here
        // return resulting object
      }

      public void Delete(object criteria)
      {
        // delete object here 
      }
    }

    The criteria or business object from the client does materialize on the server. Of course on the server it materializes within code you control, and so you can safely interact with the object from within the methods of this factory. Here, you can force re-running of the validation rules, apply extra authorization rules or other processing you see fit - all on the app server. Only if you are happy with the object would you then invoke the "real" data portal to actually allow the persistence to occur.

    Tuesday, June 24, 2008 10:24:09 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
     Monday, June 23, 2008

    A couple people have suggested that I might be abandoning VB. Not so!

    My first love was Pascal - VAX Pascal actually, which was more like Modula II in many ways. What an awesome language!

    My next love was VAX Basic. Now that VB has structured exception handling in .NET, it has finally caught up to where VAX Basic was in the early 90's. No kidding.

    Of course after VAX Basic came VB.

    And after VB came .NET. I love .NET. I love .NET with VB and C#. C# is just VB with semi-colons, but VB is just C# without semi-colons too. I gave up on the silly language war thing a couple years ago, and am happy to let either or both language live or die by the hand of its users. The language thing was distracting me from truly enjoying .NET.

    When it comes to writing books, it is really important to remember that they fund CSLA .NET. As much as I love what I do, I've got kids that will go to college in the (scarily near) future, so I can't work for free. So when I write a book, I can't ignore that C# books outsell VB books around 3:1 (it used to be 2:1, but the market has continued to shift). I still think it is worth writing a VB edition to get that 25% of the market, but you must admit that it makes a lot of sense to go for the 75% first!

    It takes several weeks to port a book from one language to the other. The current plan for Expert 2008 Business Objects in C# is October (though I fear that may slip), and with the conversion time and publication schedule constraints, that pushes the VB edition into early 2009. Apress just hasn't put the VB book on their public release list yet, but that doesn't mean I don't plan to do that edition.

    When it comes to CSLA Light, I'm doing it in C# because of the 3:1 split, and so again am focusing on C# first.

    Whether I do a VB version of the framework or not depends on whether I decide to write a book on the creation and design of CSLA Light. I may or may not. If I don't write a book on the design of the actual framework, I won't port (and then maintain) the framework into a second language.

    It is a ridiculous amount of work to maintain CSLA .NET twice, and I really don't like the idea of maintaining CSLA Light twice too. You have no idea how much writing, testing and debugging everything twice slows down progress (and eliminates fun). As wonderful as Instant C# and Instant VB are, the dual effort is a continually increasing barrier to progress.

    I might write an ebook on using CSLA Light, in which case I'd leave the framework in C#, but create reference apps in both VB and C# so I can do both editions of the ebook. I think this is the most likely scenario. Certainly VB-compatibility has shaped a couple CSLA Light design decisions already - I won't allow a design that precludes the use of VB to build a CSLA Light app.

    (The lack of multi-line lambdas and/or anonymous delegates in VB is a real barrier though... Worse even, than the poor way C# handles implementation of interfaces...)

    In the end though, like all of us, I need to be where the market is vibrant. Where I can make money from my hard work. Just now, there's more money to be had from C# content and so that takes priority. But there are a lot of people using VB, and (assuming the sales ratio doesn't slip further) in my view it is worth producing content in the VB space as well.

    Monday, June 23, 2008 9:18:31 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
     Saturday, June 14, 2008

    We're nearly done with the final serialization implementation. At this point it is possible to clone objects on Silverlight and on .NET using the same MobileFormatter. By extension, this means that objects can be cloned from Silverlight to .NET and visa versa, though we don't have tests for that yet. (and there's a bunch of cleanup and detail work to be done for completeness - but the core engine is there and working)

    The approach we've taken is automatic for managed backing fields in a subclass of BusinessBase or ReadOnlyBase. It is also automatic for BusinessListBase, ReadOnlyListBase, etc. It is not automatic for custom criteria classes, but is automatic for SingleCriteria.

    The approach does allow for serialization of private backing fields, as long as you override a couple methods in your business class to get/set the field values. This is quite comparable to the PropertyBag scheme from VB6, and is conceptually similar to implementing ISerializable (though not the same due to some required features that aren't in Silverlight - there's a reason Microsoft didn't implement something like the BinaryFormatter).

    What this means is that when using only managed backing fields, you have to do no work at all. Your objects will just serialize. If you are using one or more private backing fields you need to do something like this:

    namespace MyApp
    {
      [Serializable]
      public class CustomerEdit : BusinessBase<CustomerEdit>
      {
        protected override void OnGetState(SerializationInfo info)
        {
          base.GetState(info);
          info.AddValue("MyApp.CustomerEdit._id", _id);
          info.AddValue("MyApp.CustomerEdit._name", _name);
        }

        protected override void OnSetState(SerializationInfo info)
        {
          base.SetState(info);
          _id = info.GetValue<int>("MyApp.CustomerEdit._id";
          _name = info.GetValue<string>("MyApp.CustomerEdit._name");
        }
      }
    }

    Assuming, of course, that you have two private backing fields, _id and _name. The one important restriction is that the types of all fields must be primitive types, or types that can be coerced using Csla.Utilities.CoerceValue() (which means the value can be converted to/from a string as required by the DataContractSerializer).

    Of course if you have a field value that can't be automatically converted to/from a string, you can do the conversion yourself in the OnGetState/OnSetState methods.

    This will get a little more complex when we implement UndoableBase (which is the next item on the list), because your overrides must differentiate between "NonSerialized" and "NotUndoable" fields - by hand of course. I expect the final result will look more like this:

    namespace MyApp
    {
      [Serializable]
      public class CustomerEdit : BusinessBase<CustomerEdit>
      {
        protected override void OnGetState(SerializationInfo info, StateModes mode)
        {
          base.GetState(info);
          if (mode == StateModes.Serialization)
            info.AddValue("MyApp.CustomerEdit._id", _id);
          info.AddValue("MyApp.CustomerEdit._name", _name);
        }

        protected override void OnSetState(SerializationInfo info, StateModes mode)
        {
          base.SetState(info);
          if (mode == StateModes.Serialization)
            _id = info.GetValue<int>("MyApp.CustomerEdit._id";
          _name = info.GetValue<string>("MyApp.CustomerEdit._name");
        }
      }
    }

    The StateModes enum will have two values: Serialization and Undo. This will allow you to exclude certain fields that are serialization-only or perhaps undo-only. I think this is an edge case for the most part, but the option will be there.

    Child objects in CSLA .NET 3.5 and later should always be kept in managed backing fields, and so will be handled automatically. If you have a pressing need to store a child object reference in a private backing field, there are also OnGetChildren() and OnSetChildren() methods you can override. The code is slightly more complex, but is very prescriptive (you either do it right or it won't work :) ) - but I see this as an edge case too, and so I'm not worried if it is a little more complex.

    On the whole I'm pretty pleased with this approach. It automates as many cases as can be automated without using reflection, but provides a great deal of extensibility and flexibility for those who don't want to use managed backing fields.

    Saturday, June 14, 2008 8:58:12 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
     Tuesday, June 10, 2008

    I've been prototyping various aspects of CSLA Light (CSLA for Silverlight) for some time now. Enough to be confident that a decent subset of CSLA functionality will work just fine in Silverlight - which is very exciting!

    The primary area of my focus is serialization of object graphs, and I've blogged about this before. This one issue is directly on the critical path, because a resolution is required for the data portal, object cloning and n-level undo.

    And I've come to a final decision regarding object serialization: I'm not going to try and use reflection. Silverlight turns out to have some reasonable support for reflection - enough for Microsoft to create a subset of the WCF DataContractSerializer. Unfortunately it isn't enough to create something like the BinaryFormatter or NetDataContractSerializer, primarily due to the limitations around reflecting against non-public fields.

    One option I considered is to say that only business objects with public read-write properties are allowed. But that's a major constraint on OO design, and still doesn't resolve issues around calling a property setter to load values into the object - because object setters typically invoke authorization and validation logic.

    Another option I considered is to actually use reflection. I discussed this in a previous blog post - because you can make it work as long as you insert about a dozen lines of code into every class you write. But I've decided this is too onerous and bug-prone. So while reflection could be made to work, I think the cost is too high.

    Another option is to require that the business developer create a DTO (data transfer object) for each business object type. And all field values would be stored in this DTO rather than in normal fields. While this is a workable solution, it imposes a coding burden not unlike that of using the struct concepts from my CSLA Classic days in the 1990's. I'm not eager to repeat that model...

    Yet another option is to rely on the concept of managed backing fields that I introduced in CSLA .NET 3.5. In CSLA .NET 3.5 I introduced the idea that you could choose not to declare backing fields for your properties, and that you could allow CSLA to manage the values for you in something called the FieldManager. Conceptually this is similar to the concept of a DependencyProperty introduced by Microsoft for WF and WPF.

    The reason I introduced managed backing fields is that I didn't expect Silverlight to have reflection against private fields at all. I was excited when it turned out to have a level of reflection, but now that I've done all this research and prototyping, I've decided it isn't useful in the end. So I'm returning to my original plan - using managed backing fields to avoid the use of reflection when serializing business objects.

    The idea is relatively simple. The FieldManager stores the property values in a dictionary (it is actually a bit more complex than that for performance reasons, but conceptually it is a dictionary). Because of this, it is entirely possible to write code to loop through the values in the field manager and to copy them into a well-defined data contract (DTO). In fact, it is possible to define one DTO that can handle any BusinessBase-derived object, and other for any BusinessListBase-derived object and so forth. Basically one DTO per CSLA base class.

    The MobileFormatter (the serializer I'm creating) can simply call Serialize() and Deserialize() methods on the CSLA base classes (defined by an IMobileObject interface that is implemented by BusinessBase, etc.) and the base class can get/set its data into/out of the DTO supplied by the MobileFormatter.

    In the end, the MobileFormatter will have one DTO for each business object in the object graph, all in a single list of DTOs. The DataContractSerializer can then be used to convert that list of DTOs into an XML byte stream, as shown here:

    image

    The XML byte stream can later be deserialized into a list of DTOs, and then into a clone of the original object graph, as shown here:

    image

    Notice that the object graph shape is preserved (something the DataContractSerializer in Silverlight can't do at all), and that the object graph is truly cloned.

    This decision does impose an important constraint on business objects created for CSLA Light, in that they must use managed backing fields. Private backing fields will not be supported. I prefer not to impose constraints, but this one seems reasonable because the alternatives are all worse than this particular constraint.

    My goal is to allow you to write your properties, validation rules, business rules and authorization rules exactly one time, and to have that code run on both the Silverlight client and on your web/app server. To have that code compile into the Silverlight runtime and the .NET runtime. To have CSLA .NET and CSLA Light provide the same set of public and protected members so you get the same CSLA services in both environments.

    By restricting CSLA Light to only support managed backing fields, I can accomplish that goal without imposing requirements for extra coding behind every business object, or the insertion of arcane reflection code into every business class.

    Tuesday, June 10, 2008 8:01:50 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
     Wednesday, April 23, 2008

    I spent some time over the past few days using my prototype Silverlight serializer to build a prototype Silverlight data portal. It is still fairly far from complete, but at least I've proved out the basic concept and uncovered some interesting side-effects of living in Silverlight.

    The good news is that the basic concept of the data portal works. Defining objects that physically move between the Silverlight client and a .NET web server is practical, and works in a manner similar to the pure .NET data portal.

    The bad news is that it can't work exactly like the pure .NET data portal, and the technique does require some manual effort when creating the business assemblies (yes, plural).

    The approach I'm taking involves having two business assemblies (VS projects) that share many of the same code files. Suppose you want to have a Person object move between the client and server. You need Person in a Silverlight class library and in a .NET class library. This means two projects are required, even if they have the same code file.

    Visual Studio makes this reasonable, because you can create the file in one project (say the Silverlight class library) and then Add Existing Item and use the Link feature to get that same file included into a .NET class library project.

    I also make the class be a partial class, so I can add extra code to the .NET class library implementation. The result is:

    BusinessLibrary.Client (Silverlight class library)
      -> Person.cs

    BusinessLibrary.Server (.NET class library)
      -> Person.cs (linked from BusinessLibrary.Client)
      -> Person.Server.cs

    One key thing is that both projects build a file called BusinessLibrary.dll. Also, because Person.cs is a shared file, it obviously has the same namespace. This is all very important, because the serializer requires that the fully qualified type name ("namespace.type,assembly") be the same on client and server. In my case it is "BusinessLibrary.Person,BusinessLibrary".

    The Person.Server.cs file contains the server-only parts of the Person class - it is just the rest of the partial class. The only catch here is that it can not define any fields because that would obviously confuse the serializer since those fields wouldn't exist on the client. Well, actually it could define fields as long as they were marked as NonSerialized.

    Of course you could also have a partial Person.Client.cs in the Silverlight class library - though I haven't found a need for that just yet.

    One thing I'm debating is whether the .NET side of the data portal should just directly delegate Silverlight calls into the "real" data portal - effectively acting as a passive router between Silverlight and the .NET objects. OR the .NET side of the data portal could invoke specific methods (like Silverlight_Create(), Silverlight_Update(), etc) so the business developer can include code to decide whether the calls should be processed on the server at all.

    The first approach is simple, and certainly makes for a compelling story because it works very much like CSLA today. The Silverlight client gets/updates objects in a very direct manner.

    The second approach is a little more complex, but might be better because I'm not sure you should blindly trust anything coming from the Silverlight client. You can make a good argument that Silverlight is always outside the trust boundary of your server application, so blindly passing calls from the client through the data portal may not be advisable.

    Either way, what's really cool is that the original .NET data portal remains fully intact. This means that the following two physical deployment scenarios are available:

    Silverlight -> Web server -> database
    Silverlight -> Web server -> App server -> database

    Whether the web/app server is in 2- or 3-tier configuration is just a matter of how the original .NET data portal (running on the web server) is configured. I think that's awesome, as it easily enables two very common web server configurations.

    The big difference in how the Silverlight data portal works as compared to the .NET data portal is on the client. In Silverlight you should never block the main UI thread, which means calls to the server should be asynchronous. Which means the UI code can't just do this:

    var person = Person.GetPerson(123);

    That sort of synchronous call would block the UI thread and lock the browser. Instead, my current approach requires the UI developer to write code like this:

    var dp = new Csla.DataPortal();
    dp.FetchCompleted +=
      new EventHandler<Csla.DataPortalResult<Person>>(dp_FetchCompleted);
    dp.BeginFetch<Person>(new SingleCriteria<int>(123));

    with a dp_FetchCompleted() method like:

    private void dp_FetchCompleted(object sender, Csla.DataPortalResult<Person> e)
    {
      if (e.Error != null)
        // e.Error is an exception - deal with the issue
      else
        // e.Object is your result - use it
    }

    So the UI code is more cumbersome than in .NET, but it follows the basic service-calling technique used in any current Silverlight code, and I don't think it is too bad. It isn't clear how to make this any simpler really.

    Wednesday, April 23, 2008 8:08:36 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
     Sunday, April 13, 2008

    Silverlight 2.0 doesn't have an equivalent to the BinaryFormatter or NetDataContractSerializer. This makes some things quite challenging - in my case building CSLA Light. CSLA .NET requires high-fidelity serialization both for implementation of the Clone() operation and within the data portal.

    I've been working on building a Silverlight-compatible equivalent to the BinaryFormatter/NDCS. It turns out to be quite hard due to the limitations of the Silverlight sandbox.

    For example, Silverlight does have reflection, even against private fields. However, you can only get or set a private field with code inside the same class as the field declaration. You can't get/set a field from another object, or even from a base class or subclass. The reflection call must be in the same class!

    At this point I have a prototype serializer that works in some limited scenarios. It is a starting point. Some aspects aren't ideal, but may just be the way they are to get around how Silverlight works. Still, the end result is relatively cool.

    To use the serializer:

    1. Build the Csla project (it is a Silverlight Class Library) and reference it from your Silverlight application
    2. In your business class, add a using/Imports statement for Csla.Serialization
    3. Add the Serializable attribute to your class
    4. You class must also either inherit from MobileObject or implement the IMobileObject interface (I recommend using inheritance, as otherwise you'll have to write a lot of nasty code)
    5. You must override GetValue() and SetValue() in your class - these methods are called by the MobileFormatter so you can reflect against your private fields. See the example below to see how this works
    6. You can now use the MobileFormatter much like you would the BinaryFormatter. See the example below

    The MobileFormatter is far from complete. But it can serialize/deserialize fields of an object that contain primitive types (anything that works with Convert.ChangeType()). And it handles references to other serializable objects, both single objects and lists of serializable objects (if they implement IMobileObject or inherit from MobileList<T> ).

    I'm pretty sure it can't handle arrays, nor can it handle any list type other than (effectively) List<T>. I'm not sure what it will do with enums or other types - just haven't gotten that far yet.

    Here's a serializable object:

    using System;
    using Csla.Serialization;

    namespace SilverlightApplication1
    {
      [Serializable]
      public class Person : MobileObject
      {
        #region Serialization

        protected override object GetValue(System.Reflection.FieldInfo field)
        {
          if (field.DeclaringType == typeof(Person))
            return field.GetValue(this);
          else
            return base.GetValue(field);
        }

        protected override void SetValue(System.Reflection.FieldInfo field, object value)
        {
          if (field.DeclaringType == typeof(Person))
            field.SetValue(this, value);
          else
            base.SetValue(field, value);
        }

        #endregion

        public string Name { get; set; }

        [NonSerialized]
        private DateTime _birthdate;
        public DateTime BirthDate
        {
          get { return _birthDate; }
          set { _birthdate = value; }
        } 
      }
    }

    And here's how to serialize/deserialize the object:

    var p = new Person();

    var formatter = new Csla.Serialization.MobileFormatter();
    var buffer = new System.IO.MemoryStream();
    formatter.Serialize(buffer, p);

    buffer.Position = 0;
    var copyOfP = (Person)formatter.Deserialize(buffer);

    Though it is unfortunate that every business class must implement GetValue() and SetValue(), I think that is a relatively small price to pay to get nearly the same capability as we have in .NET with the BinaryFormatter in terms of cloning objects, and more importantly in terms of serializing them across the network with full fidelity.

    Sunday, April 13, 2008 7:42:40 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]  | 
    On this page....
    Silverlight is “dead”
    Implementing an async rule in CSLA 4 version 4.5
    CSLA data portal changes in version 4.5
    CSLA 4 version 4.3 release
    CSLA 4 version 4.3 beta available
    CSLA 4 version 4.3.0 alpha available
    Improving CSLA 4 MobileFormatter behavior
    Silverlight 6 doesn’t matter
    Windows 8 blog summary
    Windows 8 Development Platform Clarified
    Migrating smart clients to WinRT
    Using the TriggerAction control
    WPF vs Silverlight, really?
    Silverlight and the PDC
    CSLA 4 version 4.1 beta release
    Unit testing for Windows Phone 7
    CSLA .NET and MVVM video series
    MSDN Bytes interview on WP7
    CSLA 4 MVVM video series pre-release offer
    Lazy loading children in CSLA 4 and Silverlight
    Silverlight 4 VisualStateManager Valid issue
    Basic XAML Framework on CodePlex
    CSLA 4 and MVVM video series
    A “computer free” future?
    Visual Studio 2010 launch demos
    Silverlight 4 RC RichTextBox changes
    New Chicago Silverlight User Group
    Running CSLA .NET 3.8.2 under .NET 4 and Silverlight 4
    Setting focus in XAML with no code
    Will the real data object stand up?
    Magenic Studios Silverlight/WPF Contest
    Applying MVVM in the VS10 XAML designer
    CSLA .NET 3.8.2 released
    All about the “M”
    StatLight
    It is only 8, how can it be legacy???
    CSLA .NET 3.8 Beta 2 MVVM support
    Leveraging data annotation attributes in CSLA .NET
    CSLA .NET updates: 3.7.1 Beta 3 and 3.8.0 Alpha 2
    More Silverlight MVVM fun
    Silverlight triggers
    Streamlining Csla.Silverlight.InvokeMethod
    Silverlight element binding issue
    Adding DataContextChanged in Silverlight
    Initial thoughts on MVVM
    CSLA .NET 3.7 released with Silverlight 3 support
    Silverlight 3 and CSLA .NET 3.7
    OS evolution
    CSLA .NET for Silverlight video series is complete
    CSLA .NET for Silverlight: N-Tier Data Access video available
    CSLA .NET for Silverlight video segment 5 available
    CSLA .NET for Silverlight video segment 4 (N-tier) online
    CSLA .NET for Silverlight video series pre-purchase offer
    CSLA .NET 3.6.2 is now available
    Silverlight ComboBox control and data binding
    CSLA .NET 3.6.2 Release Candidate available
    CSLA .NET for Silverlight video training series
    CSLA .NET 3.6 webcast on Benkotips
    Working with WPF or Silverlight? You need this patch.
    CSLA .NET 3.6.2 beta release
    Setting up a basic n-tier CSLA .NET for Silverlight project
    Silverlight online goodies
    Why Silverlight is the future
    CSLA .NET 3.6.1 Released (for Windows and Silverlight)
    Life changing tip for XAML editing in Visual Studio
    Interesting Silverlight data binding “feature”
    CSLA .NET 3.6 for Windows and for Silverlight is released!
    CSLA .NET 3.6 RC1 available
    CSLA .NET for Silverlight webcast on 11/13
    Thoughts on PDC 2008
    Is Silverlight ready for business apps?
    Article about CSLA .NET for Silverlight online
    CSLA .NET 3.6 for Windows and Silverlight Beta 2 release
    Silverlight data portal, async calls and 404 errors
    Overview of CSLA .NET 3.6 for Windows and Silverlight
    CSLA .NET 3.6 for Windows and for Silverlight Beta 1 released
    CSLA .NET 3.6 (Silverlight and Windows) pre-release (080919)
    UnitDriven visual enhancement
    CSLA Light and CSLA .NET 3.6 Labor Day pre-release
    CSLA Light data provider
    Using CSLA Light Part 4
    Using CSLA Light Part 3
    CSLA Light Prerelease 2 available
    Using CSLA Light Part 2
    Using CSLA Light, Part 1
    Serious challenge for unit testing in Silverlight
    CSLA Light preview release
    CSLA Light data portal options
    CSLA Light data portal and n-level undo
    Expert 2008 Business Objects, CSLA Light, C# and VB
    CSLA Light serialization implementation
    CSLA Light object serialization
    Prototype Silverlight data portal
    Silverlight serializer
    Thoughts on MIX 08
    Search
    Archives
    Feed your aggregator (RSS 2.0)
    October, 2014 (1)
    August, 2014 (2)
    July, 2014 (3)
    June, 2014 (4)
    May, 2014 (2)
    April, 2014 (6)
    March, 2014 (4)
    February, 2014 (4)
    January, 2014 (2)
    December, 2013 (3)
    October, 2013 (3)
    August, 2013 (5)
    July, 2013 (2)
    May, 2013 (3)
    April, 2013 (2)
    March, 2013 (3)
    February, 2013 (7)
    January, 2013 (4)
    December, 2012 (3)
    November, 2012 (3)
    October, 2012 (7)
    September, 2012 (1)
    August, 2012 (4)
    July, 2012 (3)
    June, 2012 (5)
    May, 2012 (4)
    April, 2012 (6)
    March, 2012 (10)
    February, 2012 (2)
    January, 2012 (2)
    December, 2011 (4)
    November, 2011 (6)
    October, 2011 (14)
    September, 2011 (5)
    August, 2011 (3)
    June, 2011 (2)
    May, 2011 (1)
    April, 2011 (3)
    March, 2011 (6)
    February, 2011 (3)
    January, 2011 (6)
    December, 2010 (3)
    November, 2010 (8)
    October, 2010 (6)
    September, 2010 (6)
    August, 2010 (7)
    July, 2010 (8)
    June, 2010 (6)
    May, 2010 (8)
    April, 2010 (13)
    March, 2010 (7)
    February, 2010 (5)
    January, 2010 (9)
    December, 2009 (6)
    November, 2009 (8)
    October, 2009 (11)
    September, 2009 (5)
    August, 2009 (5)
    July, 2009 (10)
    June, 2009 (5)
    May, 2009 (7)
    April, 2009 (7)
    March, 2009 (11)
    February, 2009 (6)
    January, 2009 (9)
    December, 2008 (5)
    November, 2008 (4)
    October, 2008 (7)
    September, 2008 (8)
    August, 2008 (11)
    July, 2008 (11)
    June, 2008 (10)
    May, 2008 (6)
    April, 2008 (8)
    March, 2008 (9)
    February, 2008 (6)
    January, 2008 (6)
    December, 2007 (6)
    November, 2007 (9)
    October, 2007 (7)
    September, 2007 (5)
    August, 2007 (8)
    July, 2007 (6)
    June, 2007 (8)
    May, 2007 (7)
    April, 2007 (9)
    March, 2007 (8)
    February, 2007 (5)
    January, 2007 (9)
    December, 2006 (4)
    November, 2006 (3)
    October, 2006 (4)
    September, 2006 (9)
    August, 2006 (4)
    July, 2006 (9)
    June, 2006 (4)
    May, 2006 (10)
    April, 2006 (4)
    March, 2006 (11)
    February, 2006 (3)
    January, 2006 (13)
    December, 2005 (6)
    November, 2005 (7)
    October, 2005 (4)
    September, 2005 (9)
    August, 2005 (6)
    July, 2005 (7)
    June, 2005 (5)
    May, 2005 (4)
    April, 2005 (7)
    March, 2005 (16)
    February, 2005 (17)
    January, 2005 (17)
    December, 2004 (13)
    November, 2004 (7)
    October, 2004 (14)
    September, 2004 (11)
    August, 2004 (7)
    July, 2004 (3)
    June, 2004 (6)
    May, 2004 (3)
    April, 2004 (2)
    March, 2004 (1)
    February, 2004 (5)
    Categories
    About

    Powered by: newtelligence dasBlog 2.0.7226.0

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

    © Copyright 2014, Marimer LLC

    Send mail to the author(s) E-mail



    Sign In