Rockford Lhotka's Blog

Home | | CSLA .NET

 Friday, October 24, 2014

CSLA .NET predates the MVVM pattern by around a decade. All that time I've been telling people they should create an object model that matches the problem domain. Lots of people told me I was talking about "old fashioned OO" or otherwise dismissed what I was saying. They preferred to think of their 'model' as simple data container objects.

At some point most of them eventually realized that they needed something that actually matched the problem domain, and that their 'model' couldn't do it while still being simple data containers.

So they invented a new concept called a 'viewmodel' that (when done right) does match the problem domain - just like the UI always matches the problem domain.

At this point if you are a CSLA user you encounter an interesting situation, where you've been creating domain objects maybe for a decade longer than MVVM has existed, but MVVM is now the POTY (pattern of the year) and so you feel like you need to use it. Everyone wants the POTY after all :)

I spent a lot of time thinking about this and eventually decided that creating a viewmodel that echoes all your domain object's properties is just a lot of busy-work that has huge cost in development and testing. So it is _far_ better for your 'viewmodel' to just expose your preexisting CSLA domain objects to the UI, because THAT IS WHAT THEY ARE DESIGNED FOR.

Now it turns out that the MVVM pattern does have one thing CSLA doesn't have: the concept that the viewmodel implements UI-specific verbs (methods).

A good CSLA model is UI-neutral and so doesn't include methods for things like navigation or displaying error messages. A good viewmodel _does_ have methods that do those things through the use of an MVVM framework so those methods aren't implemented in a way that tightly couples the viewmodel to the UI technology.

Given that, combining CSLA with MVVM means that you need a viewmodel that exposes your CSLA domain objects to the UI, and that implements UI-specific methods to manage user interaction.

In the simple case what you need is a viewmodel class that exposes a single Model property, and then you can implement your UI handler methods. That's what ViewModelBase does for you.

In a lot of more complex scenarios you'll need a viewmodel that exposes multiple CSLA model objects - in which case you can learn from the way ViewModelBase is implemented and leverage that knowledge to create your own viewmodels. In any case though, the viewmodels implement properties to expose the CSLA domain objects to the UI and also implement methods that handle UI-specific requirements. The viewmodels shouldn’t be echoing the existing CSLA domain properties to the UI, because that’s just a waste of time, effort, and money.

Friday, October 24, 2014 12:21:06 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Tuesday, July 01, 2014

There’s been a lot of exciting change in cross-platform development for C# developers over the past few months. Microsoft introduced the Universal Apps concept for WinRT (Windows 8 and Windows Phone 8.1), and Xamarin introduced Xamarin.Forms (Windows Phone 8, Android, and iOS).

Beneath the Universal App support in Visual Studio 2013 is a broader concept called a Shared Project. With the Shared Project Reference Manager add-in for VS13 you can reference these shared projects from any project, not just Universal App projects.

As a result, you can build a solution like this one:


This solution includes a Xamarin.Forms MobileApp, a Microsoft Universal App (based on the Hub control), a Windows Forms app, and a WPF app. All of these apps use non-UI code from the NonUICode.Shared project.

In fact, the Android, iOS, WinPhone, Windows, and WindowsPhone UI projects have basically no code at all. In the MobileApp all the UI code is in the MobileApp1.Shared project. In the WinRTApp all the UI code is in the HubApp1.Shared project.

The Windows Forms and WPF apps each have their own UI code. Windows Forms is its own thing, and although WPF uses XAML, it is an older dialect that doesn’t share enough in common with WinRT or Xamarin.Forms for sharing.

None of the UI projects contain any business logic or logic to call services. All that code is in the NonUICode.Shared project so it can be maintained just one time. The service calls use HttpClient, which is reasonably common across all the UI platforms, and for the few differences I’m using #if statements to accommodate the per-platform code. For example, here’s a bit of code from a shared viewmodel class: 

    public async Task SaveData()
      if (this.IsDataLoaded)
        var webClient = new HttpClient();
        var data = JsonConvert.SerializeObject(this.Speaker);
#if ANDROID || __ANDROID__ || __IOS__
        var content = new StringContent(data, System.Text.Encoding.UTF8, "application/json");
        var content = new HttpStringContent(data);
        var urlString = apiSpeakerUrl + @"/" + this.Speaker.Id.ToString();
        var response = await webClient.PutAsync(new Uri(urlString), content);
        if (!response.IsSuccessStatusCode)
          throw new Exception("SaveData failed");

The overall result is that with reasonable effort you can create an app that spans every type of smart client technology available today; from Windows Forms up to iOS. These apps can share all your business and service client code, and can often share a lot of UI code.

(fwiw, if you build your business logic with CSLA .NET it is a lot easier to create and maintain the shared business and service client code than if you try to build that code by hand)

CSLA .NET | WinRT | WP8 | Xamarin
Tuesday, July 01, 2014 3:32:53 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [3]  | 
 Wednesday, June 18, 2014

csla win8_full This release adds the following key features:

  1. Support for iOS
  2. Support for WinRT on Windows Phone 8.1
  3. Support for Universal Apps that target WinRT on Windows 8.1 and Windows Phone 8.1
  4. A new HttpProxy/Host data portal channel that doesn't rely on WCF
  5. A new BrokeredProxy/Host data portal channel that allows a WinRT (Win8) app to call a local data portal running in full .NET

Here is the version 4.5.600 change log.

You can download the msi installer from the release page, or better yet add references to the framework via NuGet.

Version 4.5.600 includes support for iOS (via Xamarin) and for WinRT on Windows Phone 8.1 in the WinRT.Phone project. This also means you can use the new Universal solution/project type to build WinRT apps for Windows 8.1 and Windows Phone 8.1.

This prerelease also includes the new HttpProxy/Host and BrokeredProxy/Host data portal channels.

The Http data portal channel allows you to host the data portal server directly in ASP.NET MVC 4 or MVC 5 without the need for WCF. It relies only on the HttpClient library to invoke the server, so the client has no dependency on WCF - important for the new Windows Phone 8.1 programming model where WCF doesn't exist.

The Brokered data portal channel allows you to host the data portal server in .NET as a brokered assembly, thus available to a WinRT client app. This means you can build a WinRT app that makes data portal calls, where the "server-side" code is also running on the client device, but has access to full .NET. This will only work on Intel-based devices where full .NET assemblies can be deployed. It will only work with side-loaded apps, not apps from the Windows Store.

CSLA .NET | WinRT | WP8 | Xamarin
Wednesday, June 18, 2014 2:34:52 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Monday, April 28, 2014

As well all know, portable class libraries are pretty cool, but are restricted by the “lowest common denominator” effect.

For example, CSLA .NET supports the use of DataAnnotations along with the richer CSLA rules engine.

In trying to create one of the new “Universal PCL” assemblies to support WinRT on Win8 and WP8 I ran into the fact that WP8 doesn’t support DataAnnotations.

“No problem” I thought, “we already have our own implementation for WP8 Silverlight, for Android, and for iOS. I’ll just use that code.”

Which worked insofar as that I have a Universal PCL Csla.dll that builds.

But it doesn’t work because I can’t actually use that Csla.dll from WinRT on Win8 because that WinRT already has DataAnnotations and so there are type collisions.

As a result it isn’t clear to me that I can actually create a Universal PCL for CSLA – at least not one that supports DataAnnotations across all platforms like I’m able to do if I create one assembly per target platform (like I’ve been doing since 2007 with Silverlight 2).

I guess this makes sense. The guidance around creating a PCL is that you have code that is simple enough that it doesn’t include any platform-specific implementations that would be solved easily using #if directives. The internal implementation of some parts of CSLA is far from simple, and we do use #if directives to optimize for and/or leverage features of each of the 9 platforms currently supported by CSLA (yes, we really provide business code portability across NINE different platforms).

My personal feeling is that I’d rather support all 9 platforms as efficiently as possible, rather than compromise one or more of them just to use a fancy and optional new concept like the Universal PCL.

(of course if Microsoft and Xamarin add DataAnnotations to Windows Phone 8.1, Android, and iOS then I wouldn’t need to implement it in CSLA and that would also solve this problem – so maybe someday :) )

Monday, April 28, 2014 2:07:47 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [2]  | 
 Monday, March 17, 2014

I just created a release of CSLA 4 version 4.5.580-Beta with preliminary support for iOS via the Xamarin tools.

You can get it via nuget (easiest), or from the release page on GitHub.

This is an exciting pre-release because it now means you can reuse the same business logic code across all modern app client platforms and the desktop and the cloud. This is a “who’s who” list of supported platforms:

  • iOS
    • iPad
    • iPhone
  • Android
    • Phones
    • Tablets
  • Windows
    • WinRT (Windows 8)
    • WPF
    • Silverlight
    • Windows Forms
  • Windows Phone
  • Cloud and servers
    • Windows Azure
    • Windows Server
    • ASP.NET (MVC and Web Forms)
    • WCF
    • Web API
  • Linux
  • OS X

CSLA .NET allows you to easily create reusable business logic (authorization, validation, calculations, etc.) and to share a common app server with simple network configuration. I don’t know of any other open source C# framework that makes it possible for you to reuse the exact same business logic across all these different platforms.

Because the iOS support is new we are asking for your help. If you have the Xamarin tools for iOS please help us out by building some business code using CSLA and let us know if you find any issues (either on the forum at or via the CSLA GitHub page.

Monday, March 17, 2014 10:42:21 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [2]  | 
 Tuesday, January 07, 2014

CSLA 4 version 4.5.500 is officially released and is available via nuget or from

This version includes some major new capabilities, including:

  • Support for Windows Runtime 8.1, including substantial updates to the Csla.Xaml namespace and controls
  • Support for Android via Xamarin using the latest version of Xamarin tools
  • Support for EF6
  • Support for ASP.NET MVC 5
  • Improved support for using IoC containers in the server-side data portal
  • The installer now includes a .chm file for the Csla.dll assembly

This version also includes a number of bug fixes and minor feature enhancements.

CSLA 4 allows you to create a powerful object-oriented business layer that encapsulates all your business logic. That business logic can then be reused across multiple UI technologies and platforms, including:

  • Windows 8 (WinRT)
  • WPF
  • ASP.NET (MVC, Web Forms, and Web API)
  • WCF
  • Android (via Xamarin)
  • Windows Forms
  • Windows Phone 8
  • Silverlight 5

The ability to literally write one set of business logic code that can be reused across all these UI and platform technologies is extremely powerful, and provides you with flexibility to support multiple client platforms, or to move from one technology to another over time without having to rewrite your entire application.

Tuesday, January 07, 2014 1:37:34 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Tuesday, March 19, 2013

The final release of CSLA 4 version 4.5.20 is now available for download

It is also available via NuGet.

CSLA .NET is a software development framework that helps you build a powerful, maintainable business logic layer for WinRT (Windows 8), WPF, Web, service-oriented, Windows Phone, Silverlight, and workflow applications.

This new release adds support for Windows Phone 8 to the existing support for .NET 4, .NET 4.5, Windows Runtime (WinRT), and Silverlight 5.

It also includes some important bug fixes, and relatively minor enhancements in other areas of the framework. So if you are using any previous version of 4.5 you really should upgrade to this new release to realize these benefits.

One other note: this release uses a new WIX-based installer, and so it shouldn’t have the issues people encountered with the InstallShield-based installer used in the previous release. As always, I generally recommend using NuGet to include the assemblies in your projects, as that’s the simplest and most reliable approach.

Tuesday, March 19, 2013 9:56:18 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [2]  | 
 Wednesday, February 20, 2013

First: CSLA .NET has moved to GitHub and has a new home page:

Second, the most recent beta version 4.5.12, is now available for download and through nuget. There are a couple bug fixes, and some server-side data portal enhancements to better support the use of IoC containers for creating business objects when using the encapsulated data portal model.

In summary, you can create an implementation of Csla.Server.IDataPortalInterceptor where you can implement code that runs at the very start and very end of every single data portal call. Then you can create an implementation of Csla.Server.IDataPortalActivator where you can assume responsibility for creating an instance of the requested business type, and for initializing the object instance (thus supporting property injection).

Along with this, the data portal now allows you to use interfaces instead of concrete types (assuming you've supplied an IDataPortalActivator of course):

var obj = Csla.DataPortal.FetchAsync<IPersonEdit>();

In this example, the 'obj' reference might be any type that implements IPersonEdit, and the actual concrete type is determined by your IDataPortalActivator implementation. The default implementation is to create an instance of the supplied type, so the supplied type must be a concrete type. As a result, no existing code is affected by this change.

Wednesday, February 20, 2013 5:30:19 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [1]  | 
 Thursday, February 14, 2013

In a recent email thread I ended up writing a lengthy bit of content summarizing some of my thoughts around the idea of automatically projecting js code into an HTML 5 (h5js) browser app.

Another participant in the thread mentioned that he’s a strong proponent of separation of concerns, and in particular keeping the “model” separate from data access. In his context the “model” is basically a set of data container or DTO objects. My response:


I agree about separation of concerns at the lower levels.

I am a firm believer in domain focused business objects though. In the use of “real” OOD, which largely eliminates the need for add-on hacks like a viewmodel.

In other words, apps should have clearly defined logical layers. I use this model:

Interface control
Data access
Data storage

This model works for pretty much everything: web apps, smart client apps, service apps, workflow tasks (apps), etc.

The key is that the business layer consists of honest-to-god real life business domain objects. These are designed using OOD so they reflect the requirements of the user scenario, not the database design.

If you have data-centric objects, they’ll live in the Data access layer. And that’s pretty common when using any ORM or something like EF, where the tools help you create data-centric types. That’s very useful – then all you need to do is use object:object mapping (OOM) to get the data from the data-centric objects into the more meaningful business domain objects.

At no point should any layer talk to the database other than the Data access layer. And at no point should the Interface/Interface control layers interact with anything except the Business layer.

Given all that, the question with smart client web apps (as I’ve taken to calling these weird h5js/.NET hybrids) is whether you are using a service-oriented architecture or an n-tier architecture. This choice must be made _first_ because it impacts every other decision.

The service-oriented approach says you are creating a system composed of multiple apps. In our discussion this would be the smart client h5js app and the server-side service app. SOA mandates that these apps don’t trust each other, and that they communicate through loosely coupled and clearly defined interface contracts. That allows the apps to version independently. And the lack of trust means that data flowing from the consuming app (h5js) to the service app isn’t trusted – which makes sense given how easy it is to hack anything running in the browser. In this world each app should (imo) consist of a series of layers such as those I mentioned earlier.

The n-tier approach says you are creating one app with multiple layers, and those layers might be deployed on different physical tiers. Because this is one app, the layers can and should have reasonable levels of trust between them. As a result you shouldn’t feel the need to re-run business logic just because the data flowed from one layer/tier to another (completely different from SOA).

N-tier can be challenging because you typically have to decide where to physically put the business layer: on the client to give the user a rich and interactive experience, or on the server for more control and easier maintenance. In the case of my CSLA .NET framework I embraced the concept of _mobile objects_ where the business layer literally runs on the client AND on the server, allowing you to easily run business logic where most appropriate. Sadly this requires that the same code can actually run on the client and server, which isn’t the case when the client and server are disparate platforms (e.g. h5js and .NET).

This idea of projecting server-side business domain objects into the client fits naturally into the n-tier world. This has been an area of deep discussion for months within the CSLA dev team – how to make it practical to translate the rich domain business behaviors into js without imposing a major burden of writing js alongside C#.

CSLA objects have a very rich set of rules and behaviors that ideally would be automatically projected into a js business layer for use by the smart client h5js Interface and Interface control layers. I love this idea – but the trick is to make it possible such that there’s not a major new burden for developers.

This idea of projecting server-side business domain objects into the client is a less natural fit for a service-oriented system, because there’s a clear and obvious level of coupling between the service app and the h5js app (given that parts of the h5js app literally generate based on the service app). I’m not sure this is a total roadblock, but you have to go into this recognizing that such an approach compromises the primary purpose of SOA, which is loose coupling between the apps in the system…

Thursday, February 14, 2013 10:39:23 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [8]  | 
 Wednesday, February 06, 2013

I have released a beta of CSLA .NET: version 4.5.11, working toward a final release in a few weeks.

CSLA .NET is an open source software development framework that helps you build a reusable, scalable, and maintainable object-oriented business layer for your applications.

This update includes a few interesting features/changes.

  1. Adds support for Windows Phone 8 (WP8) development on the Windows Phone Runtime (WinPRT) platform
  2. Simplifies support for ASP.NET MVC 3 and ASP.NET MVC 4, as well as ADO.NET EF 4 and 5 by splitting functionality into separate assemblies and nuget packages
  3. Changes the local data portal to have the same behavior as a remote data portal for async calls; specifically this means that the local data portal automatically shifts all async requests onto a background thread from the thread pool
  4. Transactional attribute now allows you to set the isolation level
  5. Various bug fixes

You can get this prerelease version from nuget in Visual Studio, or you can download the new Wix-based installer from the CSLA download page.

Wednesday, February 06, 2013 5:36:07 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [2]  | 
 Wednesday, October 24, 2012

I am pleased to announce the final release of CSLA 4 version 4.5 with support for the following platforms:

  • .NET 4.5
  • Windows Runtime (WinRT)
  • .NET 4
  • Silverlight 5

The new release is available via nuget and the CSLA download page.

This release includes a number of important features and changes, including:

  • Support for Windows Runtime (WinRT), so you can simply recompile your existing CSLA .NET business classes for WinRT with little or no changes required to migrate to the new platform
  • Support for the new async and await keywords in .NET 4.5 (and in .NET 4 and SL5 via the async targeting pack)
  • Enhancements to the business rules engine
  • Enhancements to Windows Forms support via the Csla.Windows namespace

The entire CSLA .NET dev team has put a lot of work into this release, and we hope you enjoy it and find it useful!

Wednesday, October 24, 2012 4:00:51 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Wednesday, October 17, 2012

CSLA 4 version 4.5 release candidate 1 is now online via installer and nuget.

This is a relatively minor update from the previous beta, with a small number of bug fixes. The big thing is that Tiago and Jonny put a lot of work into making sure the samples are all working with CSLA .NET 4.5.

My plan is to release version 4.5 by the middle of next week.

Wednesday, October 17, 2012 4:53:46 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 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)
    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);

  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"/>

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]  | 
 Thursday, October 04, 2012

I have put CSLA 4 version 4.5 beta 2 online as we continue toward the planned final release of version 4.5 on or before Oct 26.

Version 4.5.3 is available via nuget and from the CSLA download page.

The change log contains a list of all changes. Highlights include:

  1. Substantial changes to CslaActionExtender for Windows Forms
  2. Substantial (and some breaking) changes to pre- and post-processing methods around the data portal
  3. Added the ability to global implement pre- and post-processing handler to server-side data portal to enable logging/tracing and IoC scenarios

At this point we are feature complete, so any releases between now and final release will be bug fixes or stabilization.

Version 4.5 supports the following platforms:

  • .NET 4 (with async targeting pack)
  • Silverlight 5 (with async targeting pack)
  • .NET 4.5
  • WinRT

If you are using any of these platforms, please download and test this new release. Here are some notes regarding upgrading from version 4 to 4.5.

Thursday, October 04, 2012 8:13:38 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Monday, October 01, 2012

I just checked in a series of data portal enhancements that have been on the wish list for a while. Mostly focused on pre- and post-processing behaviors.

The big one is that you can now provide an IInterceptDataPortal provider on the server to get Initialize and Complete notifications for every data portal call, allowing for logging/tracing and IoC scenarios. The logging/tracing is probably obvious, because these methods get a lot of detail about each data portal server invocation and you can do what you’d like with that data. The IoC scenario may be less obvious, but the Initialize method should provide you with a consistent way to create or retrieve your server-side IoC container so it is available for the duration of the server-side processing. I suspect most people will put the container instance in Csla.Application.LocalContext to ensure it is easily and consistently available to all code regardless of runtime environment (ASP.NET, pure .NET, WinRT, Silverlight).

The existing pre- and post-processing calls now all get a lot more data than they did before, so they should be more useful by far. The primary focus was on the Invoke, InvokeComplete, and InvokeException methods in factory objects, where the previous implementation was poor. In that context I did make a breaking change, because those methods are now passed a Csla.DataPortalEventArgs value as a parameter, instead of the more limited DataPortalContext they got before.

While I was doing this change though, I also increased the amount of data provided to the pre and post-processing DataPortal_XYZ and Child_XYZ style methods. So everyone gets an upgrade Smile

Finally, the data portal no longer returns the business object to the client when an exception happens – at least by default. Up to this point the data portal has always returned the business object from the server to the client via the DataPortalException, but almost no one actually uses that value. By not returning it, we save a bunch of network traffic and improve performance. If you want the value, you can configure the data portal to use the older behavior. So this is a breaking change, but one with an easy workaround.

Monday, October 01, 2012 2:26:41 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Monday, September 24, 2012

CSLA 4 version 4.5.2 is now online. This is Beta 1 of the 4.5 release, and is the start of the beta process. I expect to release a number of betas in relatively short order between now and the end of October. My plan is to have a final release before Windows 8 GA.

You can get this beta release from nuget (show unreleased versions), or via the installer from the CSLA download page.

This release supports .NET 4, .NET 4.5, WinRT, and Silverlight 5.

This beta release is a major change over the previous preview releases.

  1. CSLA now fully supports the new WinRT platform for Windows 8 development.
  2. The data portal now supports async/await on the client and on the server. Additionally, the .NET, WinRT, and Silverlight data portal implementations are now the same. There is no longer a “Silverlight data portal”. To make this happen, the data portal pipeline underwent major changes. This includes a number of breaking changes.
  3. The MobileFormatter is now available for use by .NET applications (not just Silverlight and WinRT). This might allow .NET apps to run in partial trust, and certainly allows .NET apps to use the same data portal channel/endpoint  as a WinRT or Silverlight app.
  4. Jonny has done a lot of work on the business rules engine. There shouldn’t be any real breaking changes, but there are a lot of good new features.
  5. BusinessBase metastate properties (such as IsDirty) are now bindable – they raise PropertyChanged as you’d expect. This enables some XAML scenarios, but be careful because WinRT XAML doesn’t notice when the DataContext has changed, so you can run into some strange issues when saving an editable object in WinRT.
  6. Johann put a lot of work into the nuget release process, allowing us to use nuget for prereleases like this one, and to create a nuget package with code templates for use in your projects.
  7. We now support .NET 4.5 and 4.0 with CSLA 4.5, so you can use the same CSLA 4.5 on existing .NET 4 machines, on Windows Azure, and also use it on .NET 4.5 machines. A 4.5 client can talk to a .NET 4 server and visa versa.
  8. WinRT now includes language resources.
  9. A number of changes were made to the Windows Forms CslaActionExtender type.

Be aware that the .NET 4 and Silverlight 5 environments now require that you use the Async Targeting Pack from Microsoft (typically via nuget) so that CSLA and your code can use the async/await keywords and related functionality.

Be aware that the data portal has breaking changes, especially for Silverlight users. Some highlights of breaking changes:

  • The Enterprise Services, Remoting, and asmx data portal channels have been removed. If you need these wire transport technologies you can create your own proxy and host types based on the version 3.8 code (perhaps they’ll end up in CslaContrib at some point).
  • The namespaces for proxy and host types that included “Silverlight” in the namespace now use the term “Mobile” instead. For example, Csla.Server.Hosts.IWcfPortal is now Csla.Server.Hosts.Mobile.IWcfPortal.
  • The client-side ProxyMode concept is now eliminated entirely, and you should use the same RunLocal attribute in Silverlight as you do in .NET.
  • All client-side DataPortal_XYZ methods in Silverlight are now different, and no longer accept a callback handler parameter. Instead, code all client-side DataPortal_XYZ methods for Silverlight just as you would for .NET.

Please direct any comments, suggestions, bug reports, or other feedback to the CSLA forums.

Monday, September 24, 2012 2:16:59 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Wednesday, August 01, 2012

Check out the new logo graphics for CSLA 4 version 4.5!

Thank you to Sandra Fougerousse for creating these updated Windows 8 style logo graphics!

csla win8

For those who are wondering, I expect to put a beta of version 4.5 online shortly after August 15 (when Windows 8 and Visual Studio 2012 final bits are available). That will start the beta cycle, with a planned release of version 4.5 around the end of October (if not sooner). I’m very exited to get CSLA .NET for WinRT into the hands of app developers!

Wednesday, August 01, 2012 10:45:32 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [2]  | 
 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;
          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]  | 
 Thursday, June 07, 2012

I have put an early version of CSLA 4 version 4.5 (version 4.5.1) online. This is a stable alpha release that supports:

  • Microsoft .NET 4.5
  • WinRT Metro style apps on Windows 8
  • Silverlight 5

You can get it from the CSLA download page.

This version doesn’t currently support Windows Phone, mono, or Android because all work is being done using Visual Studio 2012. We’ll reintroduce support for those platforms as everything gets supported on VS12.

  • This 4.5 release has the same functionality as version 4.3.12, plus some functionality we’ve added only to 4.5. Most notably:
  • The .NET and WinRT data portal now supports the new async/await keywords through methods like CreateAsync and SaveAsync
        var obj = Csla.DataPortal.FetchAsync<CustomerEdit>(id);
  • The ViewModelBase class for WPF and WinRT now has an InitAsync method so you can await initialization of the viewmodel object
        var vm = await new MyViewModel().InitAsync();
  • Enhancements to business rule processing

See the 4.5 change log for more detail.

Because this is an alpha release, you should expect more changes as we improve support for .NET 4.5 (most notably ASP.NET Web Forms, MVC, and Web API), and for WinRT/Metro.

At the same time, this should be a reasonably stable release, especially on .NET where the platform is also stable. It is also reasonably stable on WinRT/Metro, though there are more changes involved there so there could be more bugs.

Please direct feedback to the CSLA forums.

Thursday, June 07, 2012 10:19:34 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

The final release of a CSLA 4 update is now available (version 4.3.12) .

You can get it from the CSLA download page or via nuget.

One cool thing with nuget, is that (thanks to work by Johann Hough) the debug symbols are now available on a symbol server. This means you can step through the CSLA code while debugging if desired (and if you deployed CSLA to your project via nuget).

This release is an update to the previous version 4.3 that includes several bug fixes and a few new features. Most notably:

  • Fixed a concurrency bug with the data portal
  • Fixed a XAML data binding bug with the PropertyInfo control
  • Substantial bug fixes and enhancements to the Windows Forms CslaActionExtender control
  • Better exception messages when methods/properties can’t be found

There are others as well – see the change log for details.

Thursday, June 07, 2012 4:09:41 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Tuesday, May 29, 2012

A beta release of a CSLA 4 version 4.3 update is now available (version 4.3.11) .

You can get it from the CSLA download page.

This is an update to the existing version 4.3 code that includes several bug fixes and a few new features. Most notably:

  • Fixed a concurrency bug with the data portal
  • Fixed a XAML data binding bug with the PropertyInfo control
  • Substantial bug fixes and enhancements to the Windows Forms CslaActionExtender control
  • Better exception messages when methods/properties can’t be found

There are others as well – see the change log for details.

I expect the beta period to last about two weeks, followed by a final release of this 4.3 update.

Tuesday, May 29, 2012 9:59:40 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Wednesday, March 21, 2012

I’ve been spending quite a bit of time working with WinRT over the past couple weeks. Specifically prepping for next week’s Visual Studio Live! and VS Connections conferences.

As part of this process, I have a super early version of CSLA 4 version 4.5 that builds and (mostly) runs on WinRT. I’d done a lot of the work months ago when the Windows 8 developer preview came out, so getting it to work on the consumer preview took only a couple hours.

The only new feature I’ve added so far is support for the new async and await keywords for WinRT data portal code. I still need to add async/await support for the .NET data portal. I might refine some of my implementation, but right now I can use async/await to call the data portal in WinRT, and that’s cool!

The primary observation I want to make right now though, is that business classes created using CSLA 4 that target Silverlight will now recompile for WinRT with no code changes required. I took the entire ProjectTracker business library project and just recompiled it for WinRT and it works – unchanged.

If you want direct reuse of your business logic from .NET/Silverlight to WinRT, you should consider using CSLA 4.

Because I did add the async/await data portal support, I chose to add async factory methods to my business classes, alongside the existing .NET and Silverlight factory methods. From a porting/reuse perspective this is not necessary, but in terms of writing new code for .NET 4.5 and/or WinRT I think we’ll all tend to write these async factory methods.

In short, I added code like this:

    public async static System.Threading.Tasks.Task<ProjectList> GetProjectListAsync()
      return await Csla.DataPortal.FetchAsync<ProjectTracker.Library.ProjectList>();

This allows the viewmodel or other presentation layer code to retrieve business objects like this:

var obj = await ProjectList.GetProjectListAsync();

No need for async callback handlers or the other messy goo from a typical WPF/Silverlight application. Of course WPF 4.5 will be able to use the await keyword too, so only SL/WP7 will still require the callback handler model when all is said and done.

Although these are early days, and I am still working through all the features of CSLA .NET to make sure they work on WinRT, it is nice to know that data binding, business/validation rules, and the data portal are all functional already. I expect to still do some work around authorization rules, and the local data portal implementation – but the vast majority of CSLA 4 functionality is already working just fine on WinRT and that makes me very happy!

Wednesday, March 21, 2012 8:49:28 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [7]  | 
 Wednesday, March 07, 2012

At a time when many organizations are moving from Windows XP or 2000 to Windows 7, the last thing a lot of people want to think about is Windows 8. At the same time, it is incredibly clear that the future of client computing is undergoing a major shift thanks to the rapid growth of iPad and other tablet devices. Windows 8 is not only the next desktop operating system from Microsoft, but it is also Microsoft’s answer to this substantial shift toward low-power touch-based client devices.

This change impacts not only the operating system, but the underlying application development model. The new Windows Runtime (WinRT) development platform represents an evolution for .NET developers, and a significant shift for non-.NET developers.

Realistically, enterprises should expect two things. First, the enterprise desktop/laptop platform will most likely continue its shift to Windows 7, and may remain on Windows 7 for many years. Second, the enterprise is already forced to deal with iPad and other tablet devices, and they’ll need to deal with (or embrace) Windows 8 tablets in the same way.

To the first point, I think it unlikely that most organizations will roll out Windows 8 on a broad scale to desktops or laptops. Most organizations are just now moving from XP/2000 to Windows 7, only because those ancient operating systems will soon be entirely unsupported. It is not realistic to think that organizations will immediately move from Windows 7 to Windows 8. It is more realistic to think that they’ll be on Windows 7 for 5-10 years, and will then move to “Windows 11” or something along that line.

As a result, organizations will be building and maintaining applications using Microsoft .NET (WPF, Silverlight, Windows Forms) for many years to come. There is no WinRT for Windows 7, so that new development platform will be off limits for mainstream enterprise application development targeting the desktop/laptop space in the foreseeable future.

To the second point, the reality that end users in organizations will acquire and use tablets on their own, if not supplied by the organization, is already happening. The flood gates are open, and organizations are now left to deal with the results. A chaotic landscape composed of iPads, random incompatible Android devices, and soon Windows 8 devices.

This is where things get interesting. Windows 8 on Intel devices can run the same .NET applications as a desktop or laptop. They can also run WinRT applications, which (when built using .NET) are extremely similar to Silverlight applications. Windows 8 on ARM devices will only run WinRT applications.

iPad and Android devices require completely different application development using tools unlike .NET. No code or functionality sharing between existing .NET desktop/laptop applications and these platforms is possible. Truly embracing these platforms means building up duplicate development staff for Objective C and Java, or switching entirely away from traditional smart client development to a pure HTML5 model. Sadly, HTML5 isn’t compatible across all these devices either, so even that isn’t an obvious solution.

In reality, it might be less expensive for organizations to buy employees Windows 8 tablets than to pay developers to re-implement applications across multiple platforms, and to then support those multiple implementations over time. In fact, I suspect it will almost always be cheaper to spring for a few Windows 8 tablets than to pay for duplicate software development and maintenance forever.

To achieve the broadest reach, Windows 8 apps should target WinRT. That allows the apps to run on Intel and ARM devices. As I mentioned earlier, when using .NET to build WinRT applications, the development model is very similar to Silverlight. This means that existing WPF and Silverlight developers will have a relatively easy time shifting to WinRT, and substantial amounts of Silverlight application code will often just work on WinRT.

Frameworks such as CSLA .NET provide even more cross-platform compatibility. For example, the business logic code for applications written using CSLA 4 that target Silverlight will just recompile for WinRT, usually with no changes required at all. The vast majority of business logic from WPF or Windows Forms applications written using CSLA 4 will also just recompile for WinRT.

In summary, Windows 8 represents a major factor in enterprise application development strategy. In the short term, it might offer a lower-cost way to get users onto tablets without the high cost of duplicate software development, or dealing with the cross-platform HTML5 issues. In the long term, WinRT appears to be Microsoft’s new strategic development platform, so organizations need to be considering how to move to this platform over a period of years.

Wednesday, March 07, 2012 1:36:50 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [6]  | 
 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 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:

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]  | 
 Wednesday, January 25, 2012

I am pleased to announce that the Using CSLA 4: Windows Phone ebook is now available for purchase.

If you purchased the Using CSLA 4 ebook series you already own the book, and can download it now.

This ebook (in PDF format) demonstrates how to create a Windows Phone 7 (WP7) application that uses a business layer created using CSLA 4. This ebook also demonstrates the use of the MVVM (Model-View-ViewModel) design pattern in a way that is very complementary to the capabilities provided by CSLA .NET business objects, resulting in an application that is easy to build and maintain with clear separation of concerns between the XAML-based view, the interface control code in the viewmodel and the model composed of CSLA-based business objects. This ebook also makes use of the open-source Bxf MVVM UI framework.

The ebook includes a sample application demonstrating the concepts and techniques discussed in the book.

Here’s the high level content outline:

  1. Introduction
  2. Windows Phone
    1. About Silverlight
    2. Windows Phone Application Model
    3. Silverlight Navigation
    4. ApplicationBar Control
    5. Overview of XAML
  3. MVVM Design Pattern and CSLA 4
    1. MVVM Design Pattern overview
    2. Bxf MVVM Framework
    3. Main Shell Implementation
    4. CSLA .NET Windows Phone features
  4. Business and Data Access Layers
    1. Responsibility-driven design
    2. Domain overview and implementation
  5. Application Implementation
    1. Windows Phone project setup
    2. Main shell implementation
    3. User scenarios
Books | CSLA .NET | WP7
Wednesday, January 25, 2012 5:35:03 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Thursday, December 01, 2011

CSLA 4 version 4.2 is now released and available for download.

The primary focus of this release is the introduction of support for mono (Mac, Linux), monotouch (iPhone, iPad), and mono for Android.

This version also supports Windows Phone “Mango” (SDK version 7.1).

You can now reuse your business code across .NET, Silverlight, Windows Phone, and these newly supported platforms as well. As demand grows to build applications that must work on various mobile devices, the ability to directly reuse your business classes is compelling!

Version 4.2 also includes a number of enhancements to the existing CSLA 4 rule engine, along with various other features and bug fixes. Check out the change log for more information.

Our next step is to provide support for Silverlight 5 in CSLA 4 version 4.3, followed by support for WinRT (Windows 8) in version 4.5. The expectation is that your existing CSLA-based business classes will continue to work in Silverlight 5 and WinRT, providing even more long-term reuse, maintainability, and cost-effective development.

Thursday, December 01, 2011 2:30:06 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]  | 
 Thursday, November 03, 2011

I have put the slides from my DevCon talks online:

The demos I used in these talks are all part of the CSLA 4 version 4.2 download, or the related Samples download. All are on the CSLA download page.

If you would like more information about CSLA .NET, visit the Frequently Asked Questions page, or look at the ebooks and videos available from my store.

Thursday, November 03, 2011 11:13:28 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Monday, October 31, 2011

CSLA 4 version 4.2 beta 2 is now available for download on the CSLA download page.

This beta update includes a small number of bug fixes, and some enhancements:

  1. The Windows Phone projects now build for WP 7.5 "Mango"
  2. Csla.Xaml.PropertyInfo can now be used in a control template
  3. MobileFormatter can now be used for undo/clone operations on .NET
  4. Samples are now built against the 4.2 assemblies
  5. Several WPF/SL samples now use PropertyInfo, and have been styled to look better (thanks Aaron!)

At this point I expect the 4.2 release to occur by the end of November. There may or may not be another beta release depending on your feedback with this beta.

Monday, October 31, 2011 11:32:45 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Friday, October 14, 2011

With all the new terminology and conceptual surface area that comes with the OS code-named “Windows 8”, I’ve been struggling to come up with clarity as I discuss the technology. In the absence of true clarity from Microsoft, we’re left to interpret that they’ve said and come up with our own consistent terminology.

Here’s my current thinking:

  • Windows 8 – the new operating system that runs in a “dual mode”: Desktop (Win32) and WinRT
  • Win32 – the OS API that supports today’s applications in Win8
  • WinRT – the new OS API that supports future applications
  • Metro – a user experience design language often used when building WinRT applications

If I’m right, this is important, because people will ultimately be building business applications on WinRT. Those apps may or may not be strictly “Metro”, but by running on WinRT they’ll gain the benefits of the new runtime API, services, and application model.

People talk about “Metro apps”, but even in the Microsoft samples there are apps running on WinRT that violate those standards left and right. So it is extremely clear that WinRT apps might or might not be “Metro”.

Additionally, it seems pretty reasonable to think about building Silverlight or WPF apps, even today, following the Metro standards. Some of that might require a lot of work (at least until third party control vendors create some new components for us), but it is surely possible.

So you could argue that "Metro apps” might transcend WinRT. In fact, Metro is also used to describe Windows Phone apps, and they are mostly written in Silverlight.

So I think there are “WinRT apps”, and this includes any/all apps written on the WinRT API.

Then there are “Metro apps” that are probably a WinRT app, that also follows the Metro user experience guidelines.

This terminology helps a lot when talking about .NET, present and future.

Right now, today, we have some flavors of .NET:

  • .NET Full profile
  • .NET Client profile
  • Silverlight
  • Windows Phone

It seems to me that Windows 8 just adds a new option:

  • .NET WinRT profile

As I think about the future of CSLA .NET, for example, this is how I approach the issue. We’ve already put in a lot of work to make the framework support the existing flavors of .NET (plus mono, mono for iOS, and mono for Android). Much of that effort lays the necessary groundwork for also supporting this new WinRT flavor of .NET.

Friday, October 14, 2011 9:04:37 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [9]  | 
 Wednesday, October 12, 2011

This past weekend Magenic hosted a CSLA .NET Code Mastery event. A full day of free training on CSLA 4. It was a great time, and we had a room full of wonderful attendees. The content from the event is now online:

Watch for more Magenic events in the future! (

Agenda from this past event:

1. CSLA .NET intro - Rocky Lhotka

Topic will give attendees a high level overview of CSLA as an application framework. Key moving parts of CSLA will be covered, along with answering the most important question: Why use CSLA? Roles of business objects, data portal, rules, authentication and authorization will be covered in principal.

2. Business object design - Eric Blackwell

Session will concentrate of best practices for designing business objects. Single responsibility principal and maintainability will be covered in light of using CSLA. Key aspects of good CSLA business layer will be covered in detail, including properties, rules, data portal, data access, business method and validation. Particular attention will be paid to structuring classes and relationship between classes. Designing based on use cases will be an important aspect of the session.

3. Business, validation, and authorization rules - Tim Price-Williams

This session will be a deep dive into the world or rules. Topics such as validation rules, user authentication and authorization will be covered. Distinction between validation and business rules be drawn. Important key scenarios will be covered, such as synchronous and asynchronous rules, client / server rules, object creation and save scenario from rules perspective. Custom and built-in rules be covered in detail. A pattern for typical business rule/methods will be illuminated.

4. Data portal and n-tier architecture - Rocky Lhotka

This topic will cover in details all possibilities that CSLA provides when abstracting communication channels between client and server components. Difference between local and remote data portal will be discussed. Various configuration patterns will be highlighted along with usage scenarios for each one. Multi-tier deployment as it relates to data portals will be covered, as well as using external data sources instead of CSLA data portal in client only scenarios.

5. Data access - Travis Brown

This session is all about data access technologies and how they relate to CSLA data portal access. The topic will include patterns for abstracting data access for business objects to promote maintainability. Discussion of Microsoft technologies for data access will take place as well.

6. XAML and MVVM - Sergey Barskiy

This session will concentrate on using CSLA as business layer in XAML based user interfaces. Taking Silverlight as an example, session will highlight how CSLA base classes can be used to facilitate communication between UI and business objects. Adaptability of CSLA business layer to seamlessly alter user interface based on rules be will covered. Patterns for wiring business objects for Silverlight environment will be part of the discussion.

7. ASP.NET MVC - Mitch Gordon

This session will concentrate on using CSLA as business layer in ASP.NET MVC based user interfaces. The discussion will include CSLA provided base classes that will allow developers write less code. The session will illuminate patters for maintaining authentication and authorization rules between server calls. Patterns for adapting UI based on user rights will be discussed.

Wednesday, October 12, 2011 7:38:17 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [6]  | 

There is no BackgroundWorker (BW) component in WinRT. Although that is arguably a good thing, I have CSLA .NET code that relies on this component. I can’t eliminate the BW from CSLA, because I need to continue to support .NET, Silverlight, and Windows Phone, even as I add support for WinRT.

Because .NET/SL/WP7 don’t (yet) have the async/await keywords, and WinRT doesn’t have BW, I need to come up with a solution that leaves existing code/behavior alone, and yet provides comparable behavior in WinRT.

To resolve this issue, I’ve created a BackgroundWorker type for WinRT. This type hasn’t gone through extensive testing, but it is a good start at least:

// <copyright file="BackgroundWorker.cs" company="Marimer LLC">
//     Copyright (c) Marimer LLC. All rights reserved.
//     Website:
// </copyright>
// <summary>Implementation of old BCL BackgroundWorker ported to WinRT.</summary>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Core;
using Windows.UI.Xaml;

namespace System.ComponentModel
  public class BackgroundWorker : DependencyObject
    private CoreDispatcher _dispatcher;

    public BackgroundWorker()
      _dispatcher = this.Dispatcher;

    public void CancelAsync()
      if (!WorkerSupportsCancellation)
        throw new NotSupportedException();
      CancellationPending = true;

    public bool CancellationPending { get; private set; }

    public event ProgressChangedEventHandler ProgressChanged;

    public void ReportProgress(int percentProgress)
      ReportProgress(percentProgress, null);

    public void ReportProgress(int percentProgress, object userState)
      if (ProgressChanged != null)
          (sender, args) =>
            ProgressChanged(this, new ProgressChangedEventArgs(percentProgress, userState));
          this, null);

    public bool WorkerReportsProgress { get; set; }
    public bool WorkerSupportsCancellation { get; set; }
    public bool IsBusy { get; set; }

    public event DoWorkEventHandler DoWork;
    public event RunWorkerCompletedEventHandler RunWorkerCompleted;
    protected virtual void OnRunWorkerCompleted(RunWorkerCompletedEventArgs e)
      if (RunWorkerCompleted != null)
        RunWorkerCompleted(this, e);

    public void RunWorkerAsync()

    public async void RunWorkerAsync(object userState)
      if (DoWork != null)
        CancellationPending = false;
        IsBusy = true;
          var args = new DoWorkEventArgs { Argument = userState };
          await Task.Run(() =>
            DoWork(this, args);
          IsBusy = false;
          OnRunWorkerCompleted(new RunWorkerCompletedEventArgs { Result = args.Result });
        catch (Exception ex)
          IsBusy = false;
          OnRunWorkerCompleted(new RunWorkerCompletedEventArgs { Error = ex });

  public delegate void DoWorkEventHandler(object sender, DoWorkEventArgs e);

  public class DoWorkEventArgs : EventArgs
    public DoWorkEventArgs()
    { }

    public DoWorkEventArgs(object argument)
      Argument = argument;

    public object Argument { get; set; }
    public bool Cancel { get; set; }
    public object Result { get; set; }

  public delegate void RunWorkerCompletedEventHandler(object sender, RunWorkerCompletedEventArgs e);

  public class RunWorkerCompletedEventArgs : EventArgs
    public RunWorkerCompletedEventArgs()
    { }

    public RunWorkerCompletedEventArgs(object result, Exception error, bool cancelled)
      Result = result;
      Error = error;
      Cancelled = cancelled;

    public Exception Error { get; set; }
    public object Result { get; set; }
    public bool Cancelled { get; set; }
Wednesday, October 12, 2011 12:32:14 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [2]  | 
 Tuesday, October 04, 2011

The Beta 1 release of CSLA 4 version 4.2 is now available for download on the CSLA download page.

This version adds support for:

  • Windows Phone 7.5 “Mango”
  • mono
  • mono for iOS (iPhone/iPad)
  • mono for Android

Of course it continues to support .NET 4 and Silverlight 4.

This release also includes numerous bug fixes and small enhancements. In particular, Jonny has done a lot of work to make the business rules subsystem more flexible and powerful. See the change log for a list of all changes.

At this point we have spent zero time or effort on the samples. Most samples will continue to run when bound against the 4.2 assemblies, but some may encounter minor issues. The samples in the download are still bound to the 4.1 assemblies. We will be updating the samples during the 4.2 beta phase.

Because of the organizational changes of mono from Novell to Xamarin, the 4.2 release has taken a lot longer than any of us would have preferred. I am pleased that we’re entering the beta phase, and can now move deliberately toward a release.

If you are using 4.1, I strongly recommend that you test your code against 4.2. In part to help us identify any outstanding issues, and in part because the bug fixes and enhancements to the rules subsystem may be very helpful to you.

Tuesday, October 04, 2011 2:07:55 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Wednesday, September 28, 2011

Magenic is hosting a Code Mastery event in Atlanta on October 8, and I am one of the speakers.

This is a day of free CSLA 4 training, with content created and presented by people who use CSLA to build applications, and by people (Sergey and myself) who are instrumental in creating and maintaining the framework.

Sign up now, I suspect seats will go fast!

Wednesday, September 28, 2011 4:11:27 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

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:


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]  | 
 Sunday, September 18, 2011

A number of people have asked about the future of CSLA .NET on WinRT (and Windows 8 and Metro).

(fwiw, you can always check out the CSLA roadmap to see what I’m planning)

The short answer is that (when Win8 comes out) I expect to have a CSLA 4 version 4.5 release that supports .NET 4.5, along with WinRT.

These are two different things.

.NET 4.5 builds apps that run on the Win8 desktop, not in Metro. I imagine .NET 4.5 will also support Win7, but I don’t know for sure. I was able to build the existing CSLA 4 version 4.2 code in .NET 4.5 without change. But I do expect that some changes will be required to take advantage of .NET 4.5 features.

For example, ASP.NET Web Forms is getting a major facelift in 4.5, as is ASP.NET MVC. It is reasonable to expect that CSLA will need to accommodate those changes – though the bulk of the impact should be in the Csla.Web and Csla.Web.Mvc projects.

Whether there are any interesting changes to WPF or Windows Forms is, at this point, something I haven’t explored.

WinRT is closer to Silverlight than full .NET, but it isn’t Silverlight either. I spent a couple hours this evening starting the port of CSLA 4 version 4.2 to WinRT.

  1. I started with the Csla.Silverlight project, because it is closest to what will work in WinRT
  2. I added the DataAnnotations implementation from Csla.Wp, because WinRT doesn’t have DataAnnotations
  3. WinRT is also missing both INotifyDataErrorInfo and IDataErrorInfo – so it isn’t clear how any validation errors can be reported to the UI from a business object (I hope they have some solution)
  4. I still need to add the WCF data portal service reference to the Csla.WinRT project, but it appears that the data portal is essentially the same as in SL

What remains are a couple relatively big issues that require some research:

  1. The BackgroundWorker component doesn’t exist in WinRT, and we’ll need to either rewrite it or switch everything to the new async/await model
  2. The .NET Type type is quite different in WinRT, so a lot of MethodCaller code needs to be changed to use the new WinRT type system

The MethodCaller issue is, I suspect, just a matter of learning and using the new type system. But this reveals an interesting fact: anyone using System.Reflection in their code (even for simple things) is probably going to need to make changes to move to WinRT.

The BackgroundWorker issue is more interesting. At first glance it seems obvious that we’d want to move to the async/await model. And I would – except that this model doesn’t exist in .NET 4, Silverlight 4, Silverlight 5, WP7, or WP7.5.

Silverlight 5 and WP7.5 are the challenges here, because they’ll be widely used concurrently with .NET 4.5 and WinRT over a period of months or years.

  1. If we require the use of async/await, then CSLA 4.5 could not support SL 5 or WP7.5 (this violates one of the key value statements of CSLA .NET)
  2. If we use async/await in .NET/WinRT, then you can’t have compatible object code between .NET/WinRT and SL/WP (this violates one of the key value statements of CSLA .NET)
  3. If we re-implement BackgroundWorker in WinRT, then CSLA and your business code is unaffected, but you won’t be able to use async/await when you interact with the async data portal or async business rules
  4. If we support the use of async/await on .NET/WinRT, but also support BackgroundWorker then you get to choose whether to write cross-compatible code, or code that works on 4.5/WinRT only

Clearly options 1 and 2 won’t work. So we have to explore re-implementing BackgroundWorker in WinRT. Presumably we’ll use async/await inside our BackgroundWorker replacement, but we’ll keep the external interface consistent. I hope this is possible – I’m just thinking out loud at this point.

In the medium timeframe option 4 has to be the goal. In the long run I think it is safe to assume that some future version of SL and some future version of Windows Phone will support async/await. When all the then-current Microsoft platforms support the model we’ll drop BackgroundWorker entirely.

Regardless, I am quite pleased by just how far I was able to get in just a couple hours work. I have the Csla.WinRT project structure in place, and have narrowed down the problem areas to:

  1. We need some validation error notification model to replace IDEI and INDEI
  2. We need a BackgroundWorker replacement
  3. We need a MethodCaller update

When you think about the breadth of scope of the CSLA 4 framework, I’m pretty amazed that we only have three problem areas to address for the core framework.

We’ll also need to create a Csla.Xaml.WinRT assembly with some UI helpers (that’s probably how we’ll solve the validation error issue for example). I haven’t explored how much of the existing Csla.Xaml concepts will carry forward – but I suspect Csla.Xaml.WinRT will be very much like the existing Csla.Xaml.Wp project.

Sunday, September 18, 2011 8:36:28 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [5]  | 
 Tuesday, June 07, 2011

The final draft of the Using CSLA 4: ASP.NET MVC ebook is now online, and available for purchase.

If you own the Using CSLA 4 ebook series, you already own this new ebook and can download it from

If you are buying the ebooks individually, the new book is now available for purchase from

This ebook also includes a code download, containing the latest ProjectTracker codebase. This includes the Mvc3UI project: an ASP.NET MVC 3 application built using the CSLA .NET business layer.

Books | CSLA .NET | Web
Tuesday, June 07, 2011 3:50:00 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Wednesday, May 04, 2011

I am pleased to announce that the Using CSLA 4: Data Portal Configuration ebook is available for purchase in draft form.

Owners of the Using CSLA 4 ebook series can also download the updated ebook draft.

This ebook (141 pages in PDF format) covers the use of the CSLA 4 data portal technology, which enables flexible n-tier deployments of your applications in 1-, 2-, 3- and 4-tier physical configurations. The ebook covers the use of the data portal in .NET smart client, Silverlight, WP7, and ASP.NET web applications.

The ebook also covers the authentication techniques supported by CSLA .NET, including Windows integrated domain or Active Directory authentication, the use of the ASP.NET MembershipProvider model and custom authentication against your own security data store.

The ebook includes a complete set of sample applications demonstrating the concepts and techniques discussed in the book.

Here is a high level list of the content in this ebook:

  1. Data Portal Deployment
    1. Data portal concepts
    2. Deployment options
    3. Using the local channel
    4. Using the WCF channel
    5. 4-tier Silverlight and WP7 deployment
  2. Data portal configuration reference
  3. Serialization
    1. .NET serialization
    2. MobileFormatter
  4. Custom data portal proxies
    1. Supporting multiple application servers
    2. Dynamically switching between online and offline mode
  5. Authentication models
    1. Custom authentication
    2. ASP.NET membership authentication
    3. Windows authentication
Wednesday, May 04, 2011 9:18:41 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Monday, April 25, 2011

Dunn training will be holding their next CSLA training class in Atlanta, June 21-23.

If you are gearing up to use CSLA .NET and want some solid classroom training to get started, this is the way to go!

Monday, April 25, 2011 8:01:38 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Sunday, March 27, 2011

I have been working on the Using CSLA 4: Data Portal Configuration ebook, part of the Using CSLA 4 ebook series. One section of the book covers the use of Windows Azure as the application server, where the server-side components of the CSLA .NET data portal and your application will run.

Perhaps the most interesting part of that section of the ebook is that there’s no meaningful difference between hosting in Windows Azure and hosting in IIS on an on-premise Windows Server. In fact, the only difference at all is that the project in Visual Studio is an Azure ASP.NET Web Role project instead of an Empty ASP.NET web project.

This is because Windows Azure allows WCF services to host in a web role in the same way IIS hosts WCF services. When using the WCF data portal channel, the server components are accessed through a standard WCF endpoint – nothing special or fancy. That means any place you can host WCF, you can host the data portal.

In my example solution, there’s also a Silverlight client app. It is part of that same Web Role app, so a user simply navigates to the web page in Azure that hosts the Silverlight app. The Silverlight app runs on the client, and uses the data portal to interact with the server-side components of the application running in Azure.

There is some potential value to hosting the data portal (your application server) in Windows Azure.

There’s the obvious scalability benefit. Because the data portal is stateless, and typical server-side business code in a CSLA application is also stateless, there is no problem with just adding more web role instances to the app. If more capacity is required on the server, just change the Azure configuration and just like that you have more capacity.

The business code running in Azure typically implements persistence. Another value of running the application server in Azure is that the application can store its data in SQL Azure. Pretty comparable to SQL Server, but based in the cloud. In that way, the entire app can be cloud-based, with the Silverlight client using client-side CPU and memory resources, while the rest of the app scales happily in Azure.

Alternately, the application could store its data in Azure Storage. That isn’t a relational data store, but does offer some interesting super-scaling capabilities that may be quite valuable.

In the end, perhaps the most notable thing to consider is this: when building an application using CSLA and the data portal, it is entirely possible to switch between hosting in IIS to hosting in Azure, and back again, without changing anything except the application configuration.

Sure, if you use Azure-specific features in your business code (like Azure Storage), you can’t easily move off Azure. But if you stick with SQL Server or SQL Azure, and avoid Azure Storage, the .NET Service Bus, and other Azure-specific constructs, CSLA can help you build an app that can exploit Azure, without being locked into Azure forever.

Sunday, March 27, 2011 6:11:17 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [1]  | 
 Saturday, March 26, 2011

There is now an alpha release of CSLA 4 version 4.2 available for download:

The big initiative for version 4.2 is to add support for the following platforms:

  • Linux and OS X (via Mono)
  • Android (via MonoDroid)
  • iPhone and iPad (via MonoTouch)

This alpha release does not include binaries for these platforms, but does include code and sln files (for Visual Studio and/or MonoDevelop) you can use to build the source on each of the platforms.

At this point in time we have the following:

  1. CSLA 4 builds and runs on mono in Windows and Linux.
    1. Core CSLA 4 functionality (Csla.dll) should be the same as on .NET 4.
    2. ASP.NET code using CSLA objects should work using Csla.Web.dll
    3. The Windows Forms support with Csla.Windows.dll is limited due to incompatibilities in data binding between real Windows Forms and the mono implementation of Windows Forms.
  2. CSLA 4 builds and runs on Android. Use the MonoDroid tools in Visual Studio to build Csla.dll.
    1. You should find behaviors and features for Android identical to that provided for WP7.
    2. There is not currently an equivalent to Csla.Xaml.dll for Android.
    3. No testing has been done around the use of any remote data portal channel – only the local data portal has had any testing.
  3. CSLA 4 builds and runs on iOS (iPhone/iPad). Use MonoDevelop on OS X to build Csla.dll.
    1. You should find behaviors and features for iOS identical to that provided for WP7.
    2. There is not currently an equivalent to Csla.Xaml.dll for iOS.
    3. No testing has been done around the use of any remote data portal channel – only the local data portal has had any testing.

Please remember, this is an alpha release, in the early stages of testing and stabilization. Any help you can provide in terms of testing and resolving issues is appreciated! Direct inquiries to

Other changes of note to existing .NET, SL, or WP7 users include:

  • When an async rule completes, rules for affected properties are now also run
  • BackgroundWorker from Csla.Threading is now available in WP7
  • Some cleanup work was done around CslaIdentity – this shouldn’t be a breaking change, but the internals are now quite different
  • Fix a bug in non-generic GetProperty where field wasn’t always set to the correct default value
Saturday, March 26, 2011 5:13:06 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Sunday, March 20, 2011

Dunn Training is offering their CSLA 4 training class on April 11-13. The location is Atlanta.

Here’s a quote from their last class: "The willingness of our trainer to discuss how the material applied to our specific applications and situations allowed me to get an extraordinary amount of knowledge that I could put to real use immediately after taking the CSLA 4 training class."

This is a great class, so if you are looking for training on CSLA .NET, you should take a look at this opportunity.

Sunday, March 20, 2011 7:24:36 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Friday, March 11, 2011

The full draft of the Using CSLA 4: Data Access ebook is now online and available for individual purchase.

If you purchase, or have purchased, the Using CSLA 4 ebook series, you can also download this new ebook, because it is part of the series.

This 214 page ebook (in PDF format) covers the four data access models supported by CSLA .NET, focusing on the two models that provide the best maintainability and flexibility without incurring undo complexity.

The book walks through each business object stereotype, demonstrating how to implement the encapsulated invoke and factory implementation data portal models. It also demonstrates the use of ADO.NET, ADO.NET Entity Framework, and mock database access technologies.

The book includes several sample applications that provide complete implementations of persistence to accompany the concepts and techniques discussed in the book.

Friday, March 11, 2011 3:19:12 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Wednesday, March 09, 2011

A few weeks ago I posted about my initial efforts to port CSLA 4 to MonoDroid. The idea being that business classes created for WP7 could be used on Android as well.

That inspired some people – which is awesome!

  • Stuart Bale volunteered to help port CSLA 4 to MonoTouch, for iOS (iPhone/iPad).
  • Jonny Bekkum (a long-time CSLA team member) volunteered to port CSLA 4 to mono – the open source implementation of .NET that runs on Linux, Windows, and other platforms.
  • Kevin Ford volunteered to finish what I’d started by getting CSLA 4 ported to MonoDroid (in reality, he’d already started a parallel effort, and then merged his work into mine).

Initial code for all three projects has been checked into the svn code repository. Jonny has some test apps running in mono, so there’s some confidence in that code. Kevin has a small test app running in Android, so there’s some confidence there too (though it is earlier in the process). The MonoTouch port is the hardest of the three due to some limitations of MonoTouch, and we don’t know for sure that the current code works (though it does build in MonoDevelop).

My current plan is that CSLA 4 version 4.2 will be the release that includes support for mono, Android, and iOS – in addition to the existing support for .NET, Silverlight, and Windows Phone. That’ll be exciting!

If you are a developer on any of these three new targets, we’d appreciate any help in testing the code to see if it works, and to find solutions to anything that doesn’t work. Please post any issues or comments on the forum at – thanks!

Wednesday, March 09, 2011 5:16:38 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [2]  | 
 Monday, February 21, 2011

I will be showcasing CSLA 4 at the Open Source Fest at MIX11. That’s Monday evening, April 11.

If you are attending MIX please stop by and say hello, it should be a good time!

Monday, February 21, 2011 9:26:05 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 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}"
                                           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.


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


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


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, February 15, 2011

CSLA 4 is now available through NuGet, the package installer for .NET products.

This is thanks to Johann Hough (jaans on the CSLA forum) - thank you Johann!

The following packages are available:

  • Core
  • Silverlight
  • WPF
  • Windows Phone
  • Windows Forms
Tuesday, February 15, 2011 10:03:29 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [1]  | 
 Wednesday, January 19, 2011

I’ve started the process of porting CSLA .NET version 4.1 to MonoDroid. I expected this to be relatively easy because I’ve already got a version of CSLA 4 running on WP7, and from everything I know about MonoDroid it should be pretty comparable (excluding anything to do with XAML and UI concepts of course).

After a couple hours of trying to get the Android emulator to run on my machine, I discovered that the hybrid C++ and Java worlds really don’t “get” Windows. They interpret Windows configuration in different ways. I’m not sure which one is lame and out of date (by around a decade), but either C++ or Java apparently needs help…

Fortunately some googling (with Bing of course Smile) turned up the answer in the form of an environment setting named ANDROID_SDK_HOME that both C++ and Java will honor. The problem is that my User directory isn’t on the C drive, and either C++ or Java can’t handle this concept. Setting ANDROID_SDK_HOME to the path of my actual User directory solves the issue so the emulator works as expected.

The Android emulator is extremely slow, but functional. Just deploying my tiny little test app takes several minutes, and my computer is no slouch. It is clear that Android developers don’t round-trip very fast in terms of running their code to see if it works. I feel sort of like I’m back in 1992 on a VAX where the compile-link-run cycle took minutes. I’m obviously very spoiled with the performance of things like the WP7 emulator or the ASP.NET development web server, where the compile-debug/run cycle takes seconds (at most).

The process of getting CSLA 4 to at least build in MonoDroid took around 4 hours of work. Not that I’m done, but the code does compile at this point. The holdups and issues are:

  1. MonoDroid doesn’t have ObservableCollection and a set of related types, so I’ve started implementing them myself
  2. MonoDroid doesn’t know about “Add service reference”, it only knows about “Add web reference”, and that means I need to create a new data portal proxy/host pair
  3. It doesn’t look like the System.ServiceModel assembly that comes with MonoDroid actually works – my one remaining build error has to do with this assembly – and this probably means some other client-side data portal elements will be affected (like LocalProxy) – I think this indicates some bad factoring on the part of CSLA in terms of the client-side data portal implementation though, so in an odd way this might be beneficial in that the problem highlights a design flaw that needs fixing
  4. There are some bugs in MonoDroid in VS, where setting some project properties “doesn’t take” – change the property values in VS and they aren’t saved to the project file – but edit the project file in a text editor and the changes are honored – not a big deal, and MonoDroid is in an early beta, so this sort of thing is to be expected
  5. There’s no XAML or directly comparable concept on Android, so I’m not even trying to port Csla.Xaml, only the core Csla project – I’ll probably need to create a Csla.Android project with UI components appropriate to the Android UI technology

I mocked up the initial types to implement ObservableCollection, and it won’t take a lot more effort to make them have the functionality required by CSLA. I don’t feel the need to completely replicate those types – only the parts CSLA cares about.

Creating a data portal proxy/host pair isn’t hard, the data portal is designed with this sort of flexibility in mind. However, this will be the first non-WCF proxy/host pair I’ve built on the Silverlight/WP7 code base, so I’m looking forward to establishing that it is as easy as it should be.

The unexpected dependencies on System.ServiceModel are probably the most worrisome aspect of this project so far. I suspect unraveling the dependencies and fixing the design/implementation may lead to some breaking changes in the Silverlight/WP7 code. On the other hand, if my early suspicions are correct, the design is probably flawed and I’ll be able to improve things as a result.

The question is whether I leave the SL/WP7 code alone and just fix the dependencies in the Android code base. That’s probably what I’ll do in the 4.x timeframe, because I really try to avoid substantial breaking changes in point releases…

The loss of Csla.Xaml is not ideal. At the very least I think a Csla.Android project will need ViewModelBase and ViewModel, but I suspect other Android-related UI components may be required.

Anyway, I’m quite impressed by MonoDroid. It seems pretty complete, pretty functional, and pretty well integrated into Visual Studio. Other than my issues with the emulator configuration the install was painless.

To head off this question before it is asked: I do expect I’ll create a version for MonoTouch at some point.

But MonoDroid has a much lower barrier of entry since it installs on Windows and works in Visual Studio. MonoTouch requires a non-trivial cash outlay to buy a Mac, and a non-trivial time outlay to learn the Mac, MonoDevelop, some Mac svn implementation, etc. Where I’ll probably have a working version of CSLA 4 for Android in under 20 hours, I strongly suspect it will take more than twice that long (and a lot of money) to get a version working in iOS.

In this regard I must give kudos to Google, Android and MonoDroid – they have a much lower barrier to entry than Apple currently provides.

Wednesday, January 19, 2011 11:30:11 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [10]  | 
 Tuesday, January 18, 2011

csla_logo1_32I am pleased to announce the release of CSLA .NET version 4.1 with support for .NET, Silverlight and Windows Phone 7 (WP7).

You can download CSLA 4 version 4.1 at

Although there are numerous new features in version 4.1, the primary focus of this release is Windows Phone 7. With CSLA 4 version 4.1 you can now author business classes that run unchanged across the entire .NET platform:

  • Windows Phone 7
  • Silverlight
  • WPF
  • ASP.NET Web Forms
  • WCF services (SOAP and REST)
  • asmx web services
  • Windows Forms

The ability to reuse your business layer on .NET, Silverlight and WP7 is incredibly powerful, enabling you to extend your application to users on Windows, the web, and now the phone.

You can learn how to use CSLA 4 to build scalable, flexible, and maintainable applications through the Using CSLA 4 ebook series. This ebook series is currently a work in progress and will be finished in the first half of 2011.

Tuesday, January 18, 2011 7:30:40 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Friday, January 14, 2011

Dunn Training is offering a CSLA 4 training class on February 23, 2011 in Atlanta.

If you are looking for CSLA .NET classroom training, this is a great opportunity. Here’s a quote from a student who attended the December class:

Dunn’s CSLA training was phenomenal!!! It significantly advanced our team’s knowledge of CSLA and helped layout the roadmap for our future development. Mark Berry  holistically demonstrated how CSLA works with MVVM, Silverlight, WPF, Expression, OO Programming and Code Generators. He also successfully answered extremely challenging CSLA questions that were thrown at him during class. Our team is pretty knowledgeable with CSLA and the other technologies, but Mark took us to an entirely new level, sprinkled in some nice tips, tied it all together, and reenergized our team. The training was well worth the money.

Friday, January 14, 2011 5:36:03 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Tuesday, January 04, 2011

The completed first draft of the Using CSLA 4: Creating Business Objects ebook is now online and available for purchase. UsingCsla4-02-120

If you’ve purchased (or now purchase) the Using CSLA 4 ebook series you’ll also have access to this new ebook.

This is book 2 of the series. The next book will be Using CSLA 4: Data Access, followed by Using CSLA 4: Security. These first four ebooks cover all the core concepts around using CSLA 4 to build your business layer, along with various options for building a data access layer and implementing authentication.

After these four are complete I’ll move on to ebooks covering how to use a CSLA .NET business layer to create applications with different types of UI, including Silverlight, WPF, ASP.NET MVC and Windows Phone 7 (WP7).

Here’s the top-level outline of the Creating Business Objects book’s contents:

  1. Introduction

  2. Key Object Concepts

    1. Stereotypes

    2. Serialization

    3. Object Lifetime

    4. Object Relationships

    5. Object Identity and Equality

    6. Platform Differences in .NET and Silverlight

    7. Property Declarations

    8. Method Declarations

    9. Metastate

  3. Solution Structure

    1. Project Types and Assembly References

    2. Combining Project to Create Solutions

  4. Object Stereotypes

    1. Editable Objects

    2. Read-Only Objects

    3. Execution Objects

    4. Criteria Objects

    5. LINQ Types

    6. Windows Forms Types

  5. Business Rules

    1. Business and Validation Rules

    2. Authorization Rules

For those who are wondering, the first ebook is almost through the editing process and the “draft” designation will then be removed.

Tuesday, January 04, 2011 5:41:03 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Friday, December 10, 2010

I just put CSLA 4 version 4.1 beta 2 online for download. This is probably the last beta release of version 4.1, so please download and try it – I appreciate any help I can get in testing these releases.

The primary changes in beta 2 include:

  1. Added a new Csla.Xaml.PropertyInfo control for WP7, WPF and Silverlight that is like PropertyStatus but totally non-visual. See the Samples\NET\cs\SimpleNTier solution’s WP7 UI project for an example of how this works
  2. Created a copy of the DataAnnotations functionality for WP7; this is a nice concept that Microsoft didn’t put into WP7, so I ported the parts of System.ComponentModel.DataAnnotations required by CSLA .NET, so if you have classes using DataAnnotations attributes in .NET or Silverlight, that code will now work in WP7 as well
  3. Laying the groundwork for a NuGet installer when 4.1 is released, so people will be able to download and install CSLA 4 via NuGet (thanks Jaans!)
  4. Laying the groundwork for a vsix installer for Visual Studio templates, so when 4.1 is released we can add this to the Visual Studio gallery (thanks Jonny!)

I’ve also put an updated draft of Using CSLA 4: Creating Business Objects online at

This ebook is incomplete, but I’m providing work-in-progress drops of the book as I work on it. People who’ve purchased the entire Using CSLA 4 ebook series (from can download this pre-draft content. This new drop includes a lot more content than the previous drop – including the entire sections on declaring and implementing properties and methods, and a good start on the metastate fields/methods available from BusinessBase and other base classes.

Finally, I also put a top level type diagram online that is available to anyone who has purchased either the Using CSLA 4: CSLA .NET Overview ebook or the entire ebook series. It is available from the same web page.

Books | CSLA .NET | WP7
Friday, December 10, 2010 3:25:51 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Monday, November 22, 2010

Thanks to Russ Blair, there is now a time-based index available for the entire Core 3.8 video series.

The series can be purchased from

Monday, November 22, 2010 3:05:35 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

The first ebook in the Using CSLA 4 ebook series is now available.

Using CSLA 4: CSLA Overview

This ebook (in PDF format) is an introduction to CSLA 4, and will provide you with an overview of the framework, its goals and its most basic usage scenarios. All other ebooks in the Using CSLA 4 ebook series assume you have read this first ebook and understand the overall architecture and philosophy of the CSLA .NET framework.

You should also be aware that the Using CSLA 4 ebook series is also available for purchase, and it will be cheaper to buy the series than every individual ebook. Obviously right now purchasing the series only gets you access to the first book, but you'll gain immediate access to all subsequent books in the series as they come online.

Monday, November 22, 2010 2:02:49 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [2]  | 

This is the proposed outline for the Using CSLA 4 ebook series. This is subject to change, but it is the outline I’m working against at the moment as I set up packaging and pricing for the ebooks and the ebook series.

The plan is to publish seven ebooks, and each will be released in PDF format for reading on the PC or any other PDF reader.

As a special note: I have not yet found a practical way to publish in native format for the Kindle because the Kindle can’t support different fonts or tables. And believe me, I really want this on the Kindle because I love, love, love my Kindle!! But I can’t delay publishing the content while I continue to try and find a cost-effective way to create a specific Kindle version.

You will be able to purchase each ebook individually, or purchase the entire ebook series. Purchasing the series will be cheaper than buying each book individually.

Individual books will be available for purchase as they enter the draft/review phase, and will be updated as corrections are made. I am doing this to get the content out as quickly as possible. If you don’t want a draft, wait until the DRAFT designation is removed from the description of the item on the store (

If you purchase the series, you will automatically gain access to each book as it enters the draft/review phase. In other words, you are buying future access to the entire series ebooks as they come out.

Here’s the current proposed outline for the series:

  1. Using CSLA 4: CSLA .NET Overview
    1. Introduction and Installation
    2. Architecture and Philosophy
    3. CSLA .NET framework design overview
  2. Using CSLA 4: Creating Business Objects
    1. Stereotypes
      1. Editable root/child
      2. Editable root/child list
      3. Dynamic list/root
      4. Read-only
      5. Read-only list
      6. NameValueList
      7. Command
      8. Unit of Work
    2. Object metastate
      1. IsNew, IsDirty, IsValid, etc.
    3. Property declarations
      1. PropertyInfo metastate field
      2. Managed backing fields
      3. Private backing fields
      4. Child object references
      5. Lazy loading of child objects
    4. Business rules
      1. Business rules
      2. Validation rules
      3. Authorization rules
      4. Sync/async rules
      5. DataAnnotations attributes
  3. Using CSLA 4: Data access
    1. Data access models
      1. DP_XYZ invoking DAL
      2. Factory objects as DAL
      3. DP_XYZ as DAL
      4. Factory objects invoking DAL
    2. Data access technologies
      1. ADO.NET
      2. ADO.NET Entity Framework
      3. OData services
    3. Data portal
      1. N-Tier
        1. 1-, 2-tier
        2. 3-tier
        3. 4-tier (Silverlight, WP7)
          1. MobileFactory
    4. Configuring the client
    5. Configuring the server
      1. IIS
      2. Windows Server AppFabric
      3. Windows Azure
    6. Using compression in Silverlight
  4. Using CSLA 4: Security
    1. MembershipProvider authentication
    2. Windows authentication
    3. Custom authentication
    4. IAuthorizeDataPortal
  5. Using CSLA 4: Silverlight 4 and WPF
    1. Development basics
      1. WPF
      2. Silverlight
    2. MVVM design pattern
      1. Basic XAML Framework (Bxf)
      2. TriggerAction
    3. Data binding
    4. ViewModelBase/ViewModel
    5. PropertyInfo/PropertyStatus
    6. Platform specifics
      1. WPF
      2. Silverlight
  6. Using CSLA 4: ASP.NET MVC 3
    1. ASP.NET MVC development basics
    2. Controller (Csla.Web.Mvc)
    3. CslaModelBinder
    4. Html authorization helpers
  7. Using CSLA 4: Windows Phone 7
    1. WP7 development basics
    2. MVVM design pattern
      1. Basic XAML Framework (Bxf)
      2. TriggerAction
    3. Data binding
    4. ViewModelBase/ViewModel
    5. PropertyInfo
Monday, November 22, 2010 11:01:22 AM (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 08, 2010

This is a bit of a teaser, but I want to keep people posted on my progress.

I’m getting very close to finishing the first, and in some ways hardest, book in the CSLA 4 ebook series.

Overview Cover

It is arguably the hardest of the ebooks to write, because this is around 125 pages explaining the architecture, goals and basic design parameters of CSLA .NET. Lots of concepts, not so much code. While I’m still working on this, and will be for a few more days, here’s the rough outline:

  1. Introduction
    1. About this ebook and the ebook series
    2. Downloading, installing and building CSLA 4 and its samples
  2. Architecture and Philosophy
    1. Logical and Physical architecture
      1. 5 layer architecture
      2. N-tier vs service-oriented
      3. Applying the layers to real scenarios
    2. Managing business logic
      1. Defining a home for business logic
      2. Behavioral object design
      3. Mobile objects
    3. Architectures and frameworks
  3. CSLA .NET Framework
    1. Basic design goals
    2. Framework design
      1. Base classes and stereotypes
      2. Data binding
      3. N-level undo
      4. Business, validation and authorization rules
      5. Data portal
      6. Authentication
      7. Data access helpers
    3. Assembly and namespace organization

The next ebook will be easier and faster to write. Its title? Using CSLA 4: Creating Business Objects.

This current book should be online, in draft form at least, by November 19.

Monday, November 08, 2010 5:10:36 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [3]  | 

Listen to an interview where I talk about CSLA 4, UnitDriven and a lot of things related to Silverlight, WPF and Windows Phone (WP7) development.

Pluralcast 28 : Talking Business and Objectification with Rocky Lhotka

This was recorded in October at the Patterns and Practices Symposium in Redmond.

Monday, November 08, 2010 10:56:59 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Wednesday, October 27, 2010

In the past week I’ve had a couple people mention that CSLA .NET is ‘heavyweight’. Both times it was in regard to the fact that CSLA 4 now works on WP7.

I think the train of thought is that CSLA 4 supports .NET and Silverlight, but that phones are so … small. How can this translate?

But I’ve had people suggest that CSLA is too heavyweight for small to medium app development on Windows too.

As you can probably guess, I don’t usually think about CSLA as being ‘heavyweight’, and I feel comfortable using it for small, medium and large apps, and even on the phone. However, the question bears some thought – hence this blog post.

I think there are perhaps three things to consider:

  1. Assembly size
  2. Runtime footprint
  3. Conceptual surface area

CSLA is a small framework in terms of assembly size – weighing in at around 300k (slightly more for .NET, less for SL and WP7). This is smaller than many UI component libraries or other frameworks in general, so I feel pretty good about the lightweight nature of the actual assemblies.

The runtime footprint is more meaningful though, especially if we’re talking about the phone. It is a little hard to analyze this, because it varies a lot depending on what parts of CSLA you use.

The most resource-intensive feature is the ability to undo changes to an object graph, because that triggers a snapshot of the object graph – obviously consuming memory. Fortunately this feature is entirely optional, and on the phone it is not clear you’d implement the type of Cancel button this feature is designed to support. Fortunately, if you don’t use this feature then it doesn’t consume resources.

The other primary area of resource consumption is where business rules are associated with domain object types. This can get intense for applications with lots and lots of business rules, and objects with lots and lots of properties. However, the phone has serious UI limitations due to screen size, and it is pretty unrealistic to think that you are going to allow a user to edit an object with 100 properties via a single form on the phone…

Of course if you did decide to create a scrolling edit form so a user could interact with a big object like this, it doesn’t really matter if you use CSLA or not – you are going to have a lot of code to implement the business logic and hook it into your object so the logic runs as properties change, etc.

There’s this theory I have, that software has an analogy to the Conservation of Energy Principle (which says you can neither create nor destroy energy). You can neither create nor destroy the minimum logic necessary to solve a business problem. In other words, if your business problem requires lots of properties with lots of rules, you need those properties and rules – regardless of which technology or framework you are using.

The CSLA 4 business rule system is quite spare – lightweight – at least given the functionality it provides in terms of running rules as properties change and tracking the results of those rules for display to the user.

The conceptual surface area topic is quite meaningful to me – for any framework or tool or pattern. Developers have a lot to keep track of – all the knowledge about their business, their personal lives, their relationships with co-workers, their development platform, the operating system they use, their network topography, how to interact with their IT department, multiple programming languages, multiple UI technologies, etc. Everything I just listed, and more, comes with a lot of concepts – conceptual surface area.

Go pick up a new technology. How do you learn to use it? You start by learning the concepts of the technology, and (hopefully) relating those concepts to things you already know. Either by comparison or contrast or analogy. Technologies with few concepts (or few new concepts) are easy to pick up – which is why it is easy to switch between C# and VB – they are virtually identical in most respects. But it is harder to switch from Windows Forms to Web Forms, because there are deep and important conceptual differences at the technology, architecture and platform levels.

I think large conceptual surface areas are counterproductive. Which is why, while I love patterns in general, I think good frameworks use complex patterns behind the scenes, and avoid (as much as possible) the requirement that every developer internalize every pattern. Patterns are a major avenue for conceptual surface area bloat.

CSLA has a fairly large conceptual surface area. Larger than I’d like, but as small as I’ve been able to maintain. CSLA 4 is, I think, the best so far, in that it pretty much requires a specific syntax for class and property implementations – and you have to learn that – but it abstracts the vast majority of what’s going on behind that syntax, which reduces the surface area compared to older versions of the framework.

Still, when people ask me what’s going to be the hardest part of getting up to speed with CSLA, my answer is that there are two things:

  1. Domain-driven, behavior-focused object design
  2. Learning the concepts and coding practices to use the framework itself

The first point is what it is. That has less to do with CSLA than with the challenges learning good OOD/OOP in general. Generally speaking, most devs don’t do OO design, and those that try tend to create object models that are data-focused, not behavior-focused. It is the fault of tooling and a matter of education I think. So it becomes an area of serious ramp-up before you can really leverage CSLA.

The second point is an area where CSLA could be considered ‘heavyweight’ – in its basic usage it is pretty easy (I think), but as you dive deeper and deeper, it turns out there are a lot of concepts that support advanced scenarios. You can use CSLA to create simple apps, and it can be helpful; but it also supports extremely sophisticated enterprise app scenarios and they obviously have a lot more complexity.

I can easily see where someone tasked with building a small to mid-size app, and who’s not already familiar with CSLA, would find CSLA very counter-productive in the short-term. I think they’d find it valuable in the long-term because it would simplify their maintenance burden, but that can be hard to appreciate during initial development.

On the other hand, for someone familiar with CSLA it is a lot harder to build even simple apps without the framework, because you end up re-solving problems CSLA already solved. Every time I go to build an app without CSLA it is so frustrating, because I end up re-implementing all this stuff that I know is already there for the taking if I could only use CSLA…

.NET is great – but it is a general-purpose framework – so while it gives you all the tools to do almost anything, it is up to you (or another framework) to fill in the gaps between the bits and pieces in an elegant way so you can get down to the business of writing business code. So while CSLA has a non-trivial conceptual surface area where it solves these problems – you’ll have to solve them anyway because they exist and must be solved.

In summary, from an assembly size and runtime size perspective, I don’t think CSLA is heavyweight – which is why it works nicely on WP7. But from a conceptual surface area perspective, I think there’s an argument to be made that CSLA is a very comprehensive framework, and has the heavyweight depth that comes along with that designation.

Wednesday, October 27, 2010 9:58:30 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [5]  | 
 Friday, October 22, 2010

I would like to call out the amazing help I’ve had in getting the 4.1 beta out the door.

Jonny Bekkum is responsible for nearly all the non-WP7 changes in this release, with the exception of ASP.NET MVC.

Gary Brandt has really taken ownership of the ASP.NET MVC functionality provided by CSLA 4, and has made some really nice improvements, and perhaps most importantly has provided a good sample app (Samples\Net\cs\CslaMVC).

Justin Chase put a huge amount of work into updating UnitDriven for WP7 and getting most of the CSLA .NET unit tests running in WP7. This included fighting with some WP7 bugs, and perhaps even a Visual Studio debugger bug.

Without the substantial contributions of these individuals 4.1 wouldn’t be where it is!

Of course the framework wouldn’t continue to improve without the continuing support and suggestions from the CSLA .NET community on – thank you to everyone who posts, your contributions are invaluable. I hope people continue to provide such high quality interactions via the forum.

Friday, October 22, 2010 1:54:36 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

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

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]  | 
 Friday, October 15, 2010

Over the past 14 years of building and maintaining the CSLA framework I’ve tried several source control technologies and strategies. My current technology is Subversion and I have a branching and tagging strategy with which I’ve been very happy. So I thought I’d share how this works.

My CSLA .NET development team is distributed, with contributors to CSLA in various regions of the US and as far away as Norway. And my user base is truly global, with people using the code (and presumably looking at the repository) from countries in every corner of the planet.

I use Subversion primarily because it is “free as in beer”. In many ways I’d rather use TFS, but since I expose my repository to the world via svn clients and the web (and since CSLA is a free, open-source framework) TFS is completely out of reach financially.

The thing is though, if I used TFS I’d almost certainly use it the same way I’m using svn today. The lessons I’ve learned over the years about maintaining numerous releases, building major new versions and reducing administrative and developer complexity should generally apply to any source control technology.

Top level folders

My top level folder structure organizes each project.


No branching or tagging at this level. I tried that years ago, and it was a mess, because the branches and tags often don’t operate at the project level (because projects often have multiple components), so there’s a mismatch – the top level folders contain projects, but the branches/tags often contain components – and that’s confusing.

I know I could have a different repository for each project. And for more narrowly focused authorization access to the projects that would be nice. But in my case I want to expose all these projects externally via svn and web clients, so having the projects within a single repository makes my administration burden quite manageable. And I think it makes the repository easier to consume as an end-user, because there’s this one URI that provides access to the entire history of CSLA .NET.

You can see some “legacy projects” in this structure. Things like csla1-x or samples are really just places where I’ve dumped very old code, or code from some of the ways I no longer use svn. I don’t want to lose that history, but at the same time it wasn’t realistic to try and fit that older code into the way I currently organize the code.

Normally you’d look at core (the current code) or other comparatively live projects like n2, vb or ce.

Project folder structure

Within each project folder I have trunk, branches and tags.


This keeps each project isolated and reduces confusion within the repository.

Within the trunk I have the folders of my project. In the current trunk I’ve organized the CSLA 4 content into some high level areas.


At one point in the past I had the Samples as a separate project, rather than a folder within a project. That was a problem though, because the samples need to version along with the actual project source. They are dependent on the source. The same is true of the support files and setup project (and hopefully soon the NuPack project).

Basically what I’m doing is keeping all related content together within a project to avoid version mismatch issues (such as having samples versioning independent from the framework they demonstrate).


I use tagging for releases. When I release a version of the framework, I create a tag that includes everything from trunk at the point of release.


The way svn prefers to think about tags is as a read-only snapshot of a point in time. That is perfect for a release, since it really is a snapshot in time. This is incredibly valuable because it means the code for any given release can always be easily discovered.

I wasn’t always so disciplined about this, and the results were bad. People would report issues with a version of the code and I wasn’t always able to see or even find that version. Nor was it possible to do change comparisons between versions. Having an easily discoverable and accessible snapshot of each version is invaluable.


I have used branching for different reasons:

  • Long-term maintenance of a point release (like 3.8)
  • Fixing bugs in an old release (where old is more than 1 release prior to current)
  • Creating major new versions of the code
  • Supporting experimental or research efforts that may or may not ever merge into the trunk
  • Creating alternate versions of the framework (like the N2 or VB versions)


Not all those reasons turn out to be good ones… Specifically, I no longer use branching to create alternate versions of the framework. Efforts like N2 or the VB version of the framework are now top level projects. While I might use “branching” to create those top level projects, I don’t maintain that code here in the branches folder of the core. The reason is that those projects take on a life of their own, and need their own branching and tagging – because they version and release independently.

However, I find that the long term maintenance of a point release is a perfect use for a branch. So you can see the branch for V3-8-x for example, which was created when I started working on CSLA 4 in the trunk.

In fact that’s an important point. In the past, when I started a major new version, I’d start that work in a branch and then merge back into trunk. While that technically works, the merge process is really painful. So I now keep trunk as being the future-looking code – including major new versions. In other words, whenever I start working on CSLA 4.5 (or whatever) that work will occur in the trunk, and before I start that work I’ll create a V4-0-x branch where I’ll be able to keep working on the then-current version.

I do cross-merging while working on major releases, especially early in the process when the code is still very similar. For example, while I was building CSLA 4 people would report issues with 3.8. So I’d fix the issue in 3.8 and then merge that fix from the 3.8 branch into trunk. That was easy, because trunk started out exactly the same. Over time however, that becomes increasingly difficult because the trunk diverges more from any given branch, and eventually such cross-merging becomes (in my experience) too difficult and it is easier to manually do the bug fix in both places (if appropriate).

Today almost all work is done in trunk, because the primary focus is on CSLA 4. At the same time, there are occasional bug fixes or changes made to 3.8, which of course occur in the V3-8-x branch. And when I do a release of 3.8.x that still results in a new tag for that release – with that tag created off the branch.

In some extremely rare cases, I might end up doing a bug fix for an older release (like 3.6 or something). While this is really unlikely, it can happen, and in such a case I’d create a branch off the tag (the snapshot of the release) to make that fix. And when that update is released, I’d create a tag off that branch for the release.

In summary, for branching I always end up with a branch to maintain the current code every time the trunk becomes focused on a major future release. I sometimes create a branch to fix a bug in an old release. And I sometimes create a branch to do some experimental or research work – to see “what if I did something crazy” without affecting any mainstream efforts.

I no longer use branching to create alternate versions of the framework, or to create major new versions. The drawbacks to using branching in those cases, specifically in terms of complexity and/or merging issues, is just too high.

This particular approach to folder structures, tagging and branching may not apply to all scenarios, but it has absolutely made maintenance of CSLA .NET easier and better over the past several years.

Friday, October 15, 2010 10:39:57 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [4]  | 
 Friday, October 08, 2010

Every now and then someone asks me for some content they can use in a high level or executive presentation about CSLA .NET. Here’s a PDF with the slides I’ve been using for CSLA 4.

The first slide lays out the high level goals I keep in mind when building the framework.


The second slide provides a brief history of the framework. I use this to establish that CSLA has been around for a very long time, much longer than the vast majority of open source tools and frameworks for .NET (or most other platforms).


The third slide is more tactical, showing a high level list of features provided by the framework. What’s interesting about this list, is that the primary reason most people use the framework is that it provides such rich data binding support, but my original motivation was the concept of mobile objects. But as servers have become so powerful over the past 14 years that feature has actually become less important to a lot of people.


The final slide is a high level illustration of the types of organizations and applications that use CSLA .NET. You can get similar information on my web site ( I think the important thing to realize is that this framework is used all over the world, by organizations both big and small. For my part, I am honestly humbled by this reality – that amazingly talented people use CSLA to create some software that impacts people in many ways great and small.


Feel free to use this information if you find it valuable.

Thursday, October 07, 2010 11:02:45 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Thursday, September 30, 2010

Dunn Training is offering a three day hands-on CSLA .NET training class in Atlanta, November 8-10, 2010.csla_logo1_32

For more information, click here:

If you need CSLA .NET training, this is a great opportunity – check it out!

Thursday, September 30, 2010 5:47:37 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Wednesday, September 01, 2010

Lessons learned getting CSLA 4 to build and run in WP7.

  • Obviously WP7 is based on SL3, so SL4 specific code won’t work (which caused most of my initial build issues).
  • Human error plays a big role – I created several new projects for WP7, and even though they shared existing code files (via file linking), I forgot to set things like the assembly names and default namespaces – obviously that caused issues with serialization between client and server. Never underestimate the ability of the human to overlook simple things…
  • Don’t underestimate the impact of the tiny screen. While WP7 can run code from a full-screen app (the same business objects, etc), it is amazing how the need to fit into a tiny screen can impact the way you build your application!
  • VS10 doesn’t support signing assemblies, but you can do it by manually editing the csproj file.
  • VS10 doesn’t support resource files, but you can manually add a resx to the main project, then drag it into the Properties folder, then set the file’s properties (custom tool, etc) so it works correctly.
  • WP7 appears to throw different exceptions from .NET/SL for various things. There are a number of cases where I’m having to catch and rethrow exceptions to get the expected exception type – which is something I don’t need to do in .NET/SL. Since my unit tests often check for expected exceptions (testing failure conditions), I’m seeing a lot of these issues and having to tediously address them one by one.
  • VS10 crashes “for no reason” on some WP7 code. I have the same code in .NET, SL and WP7 and can walk through code in the debugger, but sometimes WP7 crashes Visual Studio – I assume this is due to the beta state of the tools.
Wednesday, September 01, 2010 12:24:12 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [2]  | 
 Saturday, August 28, 2010

CSLA 4 version 4.0.1 is released and available for download.

Download CSLA 4

This is a bug fix release, with important fixes for some issues in version 4.0.0. If you are using CSLA 4, you should consider upgrading to 4.0.1 as soon as possible.

Please note that there are a couple potential breaking changes in 4.0.1:

  • If you are using private backing fields, your RegisterProperty() calls must now specify Relationships.PrivateField so CSLA knows you are using a private backing field. If you don't do this, you'll get runtime exceptions.
  • The Save() and BeginSave() methods now raise different (and more reliable) exceptions. If you are explicitly checking for NotSupportedException you will need to check for InvalidOperationException.

While I try to avoid adding breaking changes in point releases, these were important and I thought it better to get them out as early in the CSLA 4 life-cycle as possible.

Saturday, August 28, 2010 9:53:42 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Tuesday, August 10, 2010

I started by getting the CSLA 4 codebase (from Silverlight) to compile in WP7.

As an aside – working with WP7 is really a smooth experience. The emulator works quite well, and the debugging experience is comparable to working with Silverlight. I can see where it would be hard to debug/test things requiring touch or other device hardware, but for basic app development the process is quite enjoyable.

Then we got UnitDriven running in WP7 so I could run my unit tests.

Then I spent some quality time fighting with reflection. Over the years, as .NET has evolved alternatives for reflection, CSLA has adopted those alternatives; dynamic methods and now lambda expressions. The specific things CSLA is doing can’t be easily done using the DLR, or I’d consider using that approach.

But WP7 is based on Silverlight 3, which predates the cool stuff in Silverlight 4. That means that the lambda expression concepts used in CSLA 4 wouldn’t build in WP7 – so I basically put TODO comments in their place to get the codebase to compile. Then I went back through and dug up the older 3.x code and tried to just plug it in, replacing the TODO comments.

That turned out to be a little harder than I expected. As part of replacing reflection, we enhanced the functionality of some of the code in CSLA 4, and the 3.x code didn’t handle all the same scenarios. I don’t want my WP7 code to be incompatible with the .NET/SL implementations though, so this basically meant rewriting the 3.x reflection code to support the CSLA 4 functionality.

After a few hours of work all my dynamic method calling unit tests now pass (except for the one that proves that dynamic method invocation is faster than reflection – obviously that one has no meaning in WP7 at the moment). That’s a relief, as it means that essentially all the core functionality of CSLA 4 now works.

With the notable exception of the data portal. It isn’t clear yet what’s failing, but it appears to have something to do with type resolution. I know that Silverlight and .NET don’t work the same in this regard, and I’m beginning to suspect that either I need to revert some other code back to 3.x, or that WP7 doesn’t act the same as Silverlight 3 or 4.

In any case, this is all very encouraging. I am now quite confident that we’ll be able to take CSLA 4 business classes from Silverlight and run them in .NET or on WP7 without change. Just think about building a business class and knowing that it can be used to create Silverlight, ASP.NET MVC, WP7, WPF, WCF, Web Forms, Windows Forms and asmx interfaces! Too cool!!

Tuesday, August 10, 2010 7:02:49 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [3]  | 
 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]  | 
 Thursday, July 29, 2010

This is kind of a running commentary, or personal log (stardate July 2010), recording the various things I had to do to get the CSLA 4 Silverlight codebase to build in the WP7 (Windows Phone 7) beta SDK.

This has nothing to do with getting anything actually running – this is just the stuff I had to change to get the code to compile.

To create the Csla.Wp project, I just linked in files from Csla and Csla.Silverlight. There are almost no actual files in Csla.Wp – it is almost completely reusing the same code used to implement Csla.Silverlight. That’s really cool, as it means my maintenance burden is (theoretically) quite low.

(though this exercise did highlight the need for me to go through the Csla and Csla.Silverlight projects to remove all code files from the Csla.Silverlight project too – ideally there’d be exactly one of any given file, with a few #if statements to deal with platform differences – but that’s a task for another day)

Most of my issues building on WP7 turned out to be caused by the fact that CSLA 4 targets Silverlight 4, and WP7 is based on SL3.

  • Missing: DataAnnotations
  • Missing: Reflection.Emit
  • Missing: Lambda expressions
  • Missing: string.IsNullOrWhiteSpace
  • Missing: Browsable attribute

Most of the DataAnnotations code I just had to block out with #if statements, though I did create my own DisplayAttribute class because I don’t want to lose that particular feature (the friendly name part). So business classes using that particular attribute should work fine, but the other DataAnnotations attributes won’t compile in WP7.

I also created my own BrowsableAttribute class, even though it doesn’t do anything. This saved me from littering tons and tons of code with #if statements, and I can’t see where it hurts anything to have this dummy attribute in my code. The attribute normally just affects the behavior of Visual Studio, which wouldn’t be affected either way.

The IsNullOrWhiteSpace method I just replaced with the (not as good) IsNullOrEmpty using #if statements. A little cluttered, but a workable answer.

What I’m working on now is the final part: dealing with the lack of lambda expressions and dynamic methods. Basically I need to revert the CSLA code back to using raw reflection in those cases, since none of the modern reflection alternatives appear to exist in WP7. That shouldn’t be too hard, as I can get most of that older code from earlier versions of CSLA and just put it into the existing codebase using #if statements (so I don’t affect the .NET or SL implementations).

Given the size and complexity of CSLA 4, I’m really quite pleased with the relative easy by which I’ve been able to get the code to (almost) build in WP7.

Thursday, July 29, 2010 8:19:10 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [3]  | 
 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:

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]  | 
 Friday, July 23, 2010

I am very happy to announce the release of CSLA 4, with support for .NET 4, Silverlight 4 and Visual Studio 2010.

Download CSLA 4 here

This is a major release of the CSLA .NET framework, not only because of the support for the Visual Studio 2010 wave of technologies from Microsoft, but also because of significant changes to CSLA itself based on feedback and input from the vibrant CSLA community.

As always, CSLA .NET couldn’t exist as it does without the strong support I receive from Magenic. Thank you!

CSLA 4 is the result of a lot of effort on the part of a global development team:

  • Jonny Bekkum is a C# software architect and developer at InMeta ASA in Norway. He has been developing large-scale enterprise applications on .NET and other platforms for more than 20 years, working in financial, retail, public and betting industries. Jonny has been using CSLA .NET since 2005.
  • Sergey Barskiy is a principal consultant with Magenic. He is a Microsoft MVP. He has been in IT industry for 15 years. He has been using CSLA for 3+ years.
  • Justin Chase is from Minnesota and currently works for Microsoft on the Expression team. He has been a CSLA contributor for more than 3 years and has a special interest in DSLs and code generation.
  • Blake Niemyjski is a Software Development Engineer with CodeSmith Tools and a student at UW-Platteville. He has been a contributor to various open source projects over the past three years. In his spare time he enjoys flying, learning about new technologies and contributing back to the community.
  • Ricky Supit has been developing software professionally for almost 20 years. He currently is focusing on web development technology including ASP.NET WebForm/MVC, Ajax, jQuery, and Silverlight. Ricky has been using Rocky Lhotka’s CSLA framework since Visual Basic 6.0. Ricky is currently working as software development manager for a fortune 500 health insurance company. He has a master degree in Computer Engineering.
  • Peran Borkett lives with his family in South East England. He has worked as a software consultant in the City of London financial district for over 12 years. He has been using CSLA for several years and has recently started contributing to the framework.
  • Rockford Lhotka is the creator of the popular CSLA .NET development framework, and is the author of numerous books, including Expert 2008 Business Objects. He is a Microsoft Regional Director and MVP, and a regular presenter at major conferences around the world. Rockford is the Principal Technology Evangelist for Magenic.

CSLA 4 includes significant new features. See the change log for a complete history of the changes from 3.8 to 4. Here are some important highlights:

  • Requires Visual Studio 2010, .NET and (optionally) Silverlight 4
  • New business and authorization rules system (details here, here and here)
  • Base list/collection types are now ObservableCollection for WPF; (BindingList implementations still exist for Windows Forms and some third party WPF controls)
  • Support for MVVM in Silverlight and WPF
  • Support for new Silverlight 4 data binding and validation features
  • Support for ASP.NET MVC 2
  • Allow an object to be bound to multiple bindingsource controls in Windows Forms
  • Silverlight data portal is now as extensible as the .NET data portal
  • Rework LINQ to CSLA to be easier to use
  • .NET unit tests now run in mstest (though you may still be able to run them in nunit with some work)
  • New solution and project structure to isolate UI technology support from the core framework
  • Consolidated release for .NET and Silverlight

Since this is a major version change (from 3 to 4), there are numerous breaking changes, which are highlighted in the change log.

In terms of future activities:

  • I am actively working on ebook and video content covering CSLA 4. Right now you can get special pre-release pricing on the CSLA 4 MVVM video series at Watch for more ebook and video content on the store over the next few months.
  • I am also actively working on CSLA 4 for Windows Phone 7, and I’ll have more information about this over the next few months.
  • As always, contains my plans for CSLA related work and content.

I hope you enjoy CSLA 4 and find it useful in your development efforts. I know the CSLA 4 development team has put a lot of work into this release, and we’re all excited to see how people make use of it to create cool applications.

Code well, have fun!

Friday, July 23, 2010 9:05:02 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [4]  | 
 Tuesday, July 13, 2010

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

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 08, 2010

CSLA 4 release candidate 0 is now available for download from

We are rapidly closing in on the final release of CSLA 4 with support for .NET 4, Silverlight 4 and Visual Studio 2010. This is primarily a bug fix release, and should be very stable.

There are a couple new enhancements to the ASP.NET MVC support, and a handful of bug fixes focused primarily on XAML data binding and the new business rules system.

Assuming no major issues are discovered in this release candidate in the next week or so, I expect CSLA 4 to release around July 19.

Thursday, July 08, 2010 9:12:21 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [1]  | 
 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
    if (!FieldManager.FieldExists(ChildProperty))
      Child = DataPortal.Fetch<ChildLoader>().Child;
    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:

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
    if (!FieldManager.FieldExists(ChildProperty))
      DataPortal.BeginFetch<ChildLoader>((o, e) =>
          if (e.Error != null)
            throw e.Error;
          Child = e.Object.Child;
    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]  | 
 Friday, June 25, 2010

CSLA 4 beta 3 is now available for download.

This is the final beta release of CSLA 4. All work going forward will be focused on stabilization, bug fixing and updating sample applications. My current plan is to do a release candidate the week of July 5, and final release around July 15.

New features include:

  • Improved ASP.NET MVC 2 support
  • Server exceptions can be altered by your IDataPortalExecptionInspector implementation
  • ERLB now has a default AddNewCore() implementation
  • Numerous other bug fixes and minor tweaks based on user feedback

As always, see the change log for a list of important changes in this release.

Given the short timeline until release, it is really important that anyone considering using CSLA 4 in the near future help out by using the framework and identifying any bugs or stability issues. In short, I need your help to make this a successful release.

Thank you!

Friday, June 25, 2010 11:30:18 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [3]  | 

CSLA .NET 3.8.4 is now available as a beta download. This is mostly a bug fix release to address a few issues from 3.8.3, plus some ASP.NET MVC work.

Version 3.8.4 targets .NET 3.5 and Silverlight 3 (though with a little effort it works with Silverlight 4 as well).

See the change log for a list of changes. There aren’t many, but if they affect you then they are important.

The only feature change in 3.8.4 is that most of the new ASP.NET MVC 2 support from CSLA 4 has been back-ported to 3.8. This means that the Csla.Web.Mvc project now targets and supports ASP.NET MVC 2, and provides more features and functionality that was there in 3.8.3.

This is a stable beta, given the small number of changes (other than the MVC support). So if you are affected by any of the issues listed in the change log I strongly recommend moving from 3.8.3 to 3.8.4 beta to test and utilize the changes.

Friday, June 25, 2010 11:19:03 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 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.

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]  | 
 Wednesday, May 26, 2010

Thanks to Russ Blair, there is now a time-based index for all the video segments in the CSLA for Silverlight video series:

This index makes it much easier to find specific topics within the videos. As always, if you’d like to buy the video series, please visit

Wednesday, May 26, 2010 9:11:01 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [1]  | 
 Monday, May 03, 2010

CSLA 4 Beta 1 is now available for download. This includes CSLA .NET version 4 for .NET and Silverlight.

Beta 1 is essentially feature complete. It includes some really big (breaking) changes from 3.8.

Here’s a list of highlights, and of course the change log lists essentially all the changes (with the breaking changes highlighted).

The biggest change is the new business, validation and authorization rules system (info here, here and here). While the new rule system requires changes to your existing business, validation and authorization rules code, the new capabilities are pretty amazing and I think you’ll find it is worth the effort to make the changes.

There are many other changes as well, touching almost every aspect of the framework. From new ASP.NET MVC support, to enhanced MVVM support in Silverlight and WPF, to addressing many of the most common requests around the data portal, CSLA 4 should offer benefits to most application scenarios.

This is a beta 1 release, and is the start of the overall beta-to-release process. Based on your feedback using this beta, I expect to do a couple more beta releases over the next few weeks, with a final release in about 6-8 weeks (so around the end of June).

While I’m sure there will be changes based on feedback, the focus during the beta process is on fixing bugs or addressing anything that is clearly broken. I do not anticipate any major feature changes or enhancements during this process – that’s what the past few months of pre-releases were all about.

CSLA 4 does require .NET 4 and (optionally) Silverlight 4. It also requires Visual Studio 2010. If you are using older versions of Visual Studio, .NET or Silverlight then you should continue to use version 3.8.

Please download CSLA 4 Beta 1 and offer bug reports or other feedback using the CSLA forum.

Monday, May 03, 2010 11:17:04 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Tuesday, April 27, 2010

Here’s a really nice forum post discussing how one CSLA user combined the Reactive (Rx) framework with the CSLA data portal to streamline async calls.

Tuesday, April 27, 2010 3:03:54 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Monday, April 26, 2010

I’m looking at how to provide information around .NET 4, Silverlight 4 and CSLA 4.

It is a challenging consideration. Many people like books, and I do to. I could create an Expert 2010 Business Objects book, which would take around 6 months. That means it would be out just about in time for Silverlight 5 to ship. Given the rate of Silverlight releases, conventional books (at least of the ~750 page variety) are too slow.

A lot of people have found my PDF ebooks to be very useful. Each one was around ~140 pages, and there’s no print/shipping/production time. This means they come out much faster – but they are still essentially static content once published, just like a conventional book.

The Silverlight and Core 3.8 video series have also been very popular. Not everyone likes to read, and there’s some real value in watching how things are done in a more dynamic manner. Also, videos take less time to produce than either an ebook or conventional book, so they are potentially more responsive. On the other hand, some people really dislike video content and prefer books.

I think it is safe to say that I’ll continue to produce video content, as that addresses an important set of users and is relatively fast to produce.

But I also think text content is important. It has a different price point, and offers advantages around consumption that just aren’t there with videos.

So the question is how to make text content timely, and at least a little less static – while still recognizing the realities of the amount of work involved.

Most conventional publishers now offer a “beta program” of some sort for their books. Basically you buy the book before it exists, and you get access to draft copies of chapters as they arrive. Once the chapters go through the edit process, you then get access to the final versions.

I’m thinking about doing something along that line for CSLA 4. Create ebook content, perhaps with each chapter as a separate PDF. Put this content on like I do with the videos, and then refresh the PDF files as they go through the revision process.

To be clear, this would be the “How to Use CSLA 4” book, not the “How to Build a .NET Framework” book. The focus would be on using the various features of CSLA to construct a reusable business layer, and how to use the data portal to achieve flexible n-tier deployment and scalability. Nor would it dive into specific UI technologies – I’d do separate ebooks for those.

Basically it will be like the Core 3.8 video series, but in ebook form, and targeting CSLA 4 of course.


Monday, April 26, 2010 12:36:35 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [17]  | 
 Saturday, April 24, 2010

I’m well into the redesign of the authorization system in CSLA .NET. The new system is integrated into the new business rules system, and so is no longer a separate concept. To me this makes sense, since authorization rules are just a specific type of business rule.

Some of the basic concepts from CSLA .NET 2.0 to 3.8 are still there. Per-property authorization:

  • CanReadProperty()
  • CanWriteProperty()
  • CanExecuteMethod()

Per-type authorization (which is a little different now) where you can ask:

  • Can the user create an instance of this type?
  • Can the user get/fetch an instance of this type?
  • Can the user edit/save an instance of this type?
  • Can the user delete an instance of this type?

And the new per-instance authorization where you can ask:

  • Can the user create the instance you already have? (silly, but possible)
  • Can the user get/fetch the instance you already have? (silly, but possible)
  • Can the user edit/save this instance?
  • Can the user delete this instance?

The actual authorization checks occur by executing an IAuthorizationRule rule object. CSLA provides the AuthorizationRule base class to make it easy to implement most rules, and includes IsInRole and IsNotInRole rules. For example, here’s the IsInRole rule:

/// <summary>
/// IsInRole authorization rule.
/// </summary>
public class IsInRole : AuthorizationRule
  private List<string> _roles;

  /// <summary>
  /// Creates an instance of the rule.
  /// </summary>
  /// <param name="action">Action this rule will enforce.</param>
  /// <param name="roles">List of allowed roles.</param>
  public IsInRole(AuthorizationActions action, List<string> roles)
    : base(action)
    _roles = roles;

  /// <summary>
  /// Creates an instance of the rule.
  /// </summary>
  /// <param name="action">Action this rule will enforce.</param>
  /// <param name="element">Member to be authorized.</param>
  /// <param name="roles">List of allowed roles.</param>
  public IsInRole(AuthorizationActions action, Csla.Core.IMemberInfo element, List<string> roles)
    : base(action, element)
    _roles = roles;

  /// <summary>
  /// Rule implementation.
  /// </summary>
  /// <param name="context">Rule context.</param>
  protected override void Execute(AuthorizationContext context)
    if (_roles.Count > 0)
      foreach (var item in _roles)
        if (Csla.ApplicationContext.User.IsInRole(item))
          context.HasPermission = true;
      context.HasPermission = true;

At its most basic a rule is composed of some simple items:

  • An action (read/write property, execute method, create/get/edit/delete type/instance)
  • An optional target element (property/method)
  • An Execute() method that actually implements the rule

If your rule needs more information that’s fine – it is your class, so you can just add more properties. Just remember that a rule object is used across all instances of a business object type, so (just like with other business rules) the Execute() method absolutely must not change instance-level state in the rule object.

The Execute() method is passed a context object. The context object contains some simple properties:

  1. Target (optional reference to business object)
  2. HasPermission (true/false result returned by rule)

The Target property may be null. For per-property rules it will not be null, and for per-instance rules it will not be null. But for per-type rules it will be null. The way CSLA itself (especially the data portal) invokes rules is always per-property or per-type. The thing is, when possible even the per-type checks include the Target reference (typically only for CanEditObject checks). So you can use it if it is there, but you need to handle the case where it is null.

But the real point here, is that you can write your own authorization rule that has nothing to do with roles. You could use permissions, claims, random numbers – whatever you want to use to decide whether the user can or can’t perform the requested action.

Authorization rules are added in the AddBusinessRules() override in your business class – just like other business rules:

protected override void AddBusinessRules()
  BusinessRules.AddRule(new IsInRole(
    new List<string> { “Administrator” });

The rule set concept from other business rules applies here too – so you can have different authorization rules for different users/contexts/etc.

Finally, you can invoke rules as follows:

// per-type
bool result = Csla.Rules.BusinessRules.HasPermission(
  AuthorizationActions.CreateObject, typeof(Customer));
// per-instance
bool result = Csla.Rules.BusinessRules.HasPermission(
  AuthorizationActions.EditObject, _myCustomer);

The existing IAuthorizeReadWrite interface continues to operate as in 3.x, so you can use that to invoke CanReadProperty/CanWriteProperty/CanExecuteMethod as before.

Friday, April 23, 2010 11:07:27 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [13]  | 
 Monday, April 19, 2010

Jason Bock just blogged with some interesting work he’s been doing around custom code analysis rules for CSLA 4:

Using Custom CodeAnalysis Rules in Your CSLA Projects

Monday, April 19, 2010 9:34:11 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

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

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.


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


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.


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


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.


Demo showing some concepts and implementation around MVVM.


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]  | 
 Friday, April 16, 2010

I have put CSLA 4 Preview 4 online for download.

CSLA 4 requires Visual Studio 2010, .NET 4 and (optionally) Silverlight 4.

There are a lot of changes in CSLA 4 - make sure to read the change log!

This will be the last preview, and it includes all planned CSLA 4 functionality except:

  • New authorization rules system
  • INotifyDataErrorInfo support (SL only)
  • Class level DataAnnotation attributes

My intent is to finish these three items within the next two weeks, and then enter a beta phase.

Your feedback now and through the beta phase is absolutely invaluable to the quality of the release. If you are using or planning to use .NET 4 or Silverlight 4 please take a look at the preview and let me know your thoughts and any bugs you find by replying to this thread on the forum.

Friday, April 16, 2010 10:41:48 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Friday, April 09, 2010

In preparation for the Twin Cities Code Camp I put together a short list showing the biggest and most important changes in CSLA 4:

  • Solution/project structure
    • Projects/assemblies better organized
    • Client profile support
    • Setup project
  • Business objects
    • List types now ObservableCollection<T>
    • New RegisterProperty() overloads
    • Automatic use of description/display attributes
    • CommandBase/CriteriaBase/CslaIdentity generic
    • Parent property public
    • Widespread use/requirement of Csla.Core.IPropertyInfo
  • Business rules
    • New business rule system
    • DataAnnotations
  • Authorization rules (coming)
    • New authz rule system
    • Integrated into business rule system
  • LINQ to CSLA
    • Remove 3.x implementation
    • Add LinqObservableCollection and ToSyncList()
    • CslaModelBinder
    • Controller
    • IModelCreator
  • Silverlight
    • IDataErrorInfo
    • INotifyDataErrorInfo (coming)
    • Browsable(false)
  • XAML
    • MVVM (ViewModelBase/ViewModel)
    • TriggerAction
    • Unified PropertyStatus/BusyAnimation
  • Data portal
    • Open up data portal for SL
    • Pluggable proxy objects to dynamically switch app servers
    • Compressed WCF example for .NET
    • Impersonation allowed via WCF
    • Client culture flows from SL client to app server
  • Reflection
    • MethodCaller uses lambda expressions
Friday, April 09, 2010 10:53:36 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Monday, April 05, 2010

I knew I was forgetting something when I wrote the big post covering the new CSLA .NET business rule system. And it was rule chaining, which really is a big feature.

In CSLA 3.8 a rule could return one value: true or false. This is because a rule was a Boolean method. Oh sure, you could return some limited data through the RuleArgs (Description, Severity, StopProcessing), but this was really all part of one result.

In CSLA 4 a rule can return many results. This means that one rule can invoke other rules, and all their consolidated results are returned as the result of the one rule. Or you could create a rule that invoked an external rules engine, returning all results of the engine as a result of your rule. Or you could create a rule that invoked a workflow (as in Windows Workflow Foundation 4), again consolidating the results of the workflow as a result of your rule.

One way to use this is as an escape hatch. If you don’t like the way CSLA manages rules, just write your own “rule” that is actually a replacement rule engine, and allow CSLA to invoke your rule engine every time a property changes.

But even if you don’t go so far as to write your own rule engine, there are various interesting patterns that fit neatly within the existing CSLA 4 rule model.

For example, it is quite common for people to want to invoke a rule only if other properties of the object are in a certain state. Maybe you only want to require a value if the object is new, but not if it already exists. To do this, you can create a gate rule

public class NewGateRule : BusinessRule
  public NewGateRule(Csla.Core.IPropertyInfo primaryProperty)
    : base(primaryProperty)
  { }

  private IBusinessRule _innerRule =
    (IBusinessRule)new Csla.Rules.CommonRule.Required(PrimaryProperty);

  protected override void Execute(RuleContext context)
    var obj = context.Target as Csla.Core.ITrackStatus;
    if (obj != null && obj.IsNew)

This rule creates an instance of the Required rule, but only executes that inner rule if the target business object’s IsNew property is true. So the real rule is only invoked if the gate condition is met.

Notice the use of the GetChainedContext() method, which takes the RuleContext passed to the NewGateRule and creates a chained RuleContext that is appropriate for the inner rule. This technique automatically consolidates the results of the inner rule together with the outer rule (and any other chained rules) so when the NewGateRule completes all the results are automatically processed.

The same coding technique could be used to invoke many other rules if desired, each one having its own chained RuleContext. And chaining can be nested, so you could have a gate rule execute another gate rule that executes the real rule and that should work fine.

Keeping in mind that rules are just types, it is possible to do something slightly more dynamic – though your metadata does need to include not just the full type name of the rule, but also a way to describe the constructor parameters required. But this pseudo-code illustrates the concept:

public class DynamicRule : BusinessRule
  public DynamicRule(Csla.Core.IPropertyInfo primaryProperty, string innerRule)
    : base(primaryProperty)
    var t = Type.GetType(innerRule);
    object[] args = new object[] { primaryProperty };
    _innerRule = (IBusinessRule)Activator.CreateInstance(t, args);

  private IBusinessRule _innerRule;

  protected override void Execute(RuleContext context)

In this case the rule expects the full type name of the real rule to be provided. It uses that type information to dynamically create an instance of the real rule, and then executes it using a chained RuleContext. It should be clear that this basic concept could be extended to create a rule that dynamically loads an entire set of rules (perhaps using MEF) and executes those rules using chaining.

Monday, April 05, 2010 10:51:46 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

The first preview of the new CSLA 4 business rules subsystem will be available soon from

Of course there are a lot of other changes to CSLA .NET in this preview, so make sure to carefully read the change log. Although there are a lot of breaking changes, most of them have pretty minimal impact on people who are already using the 3.8 coding style for classes. Except for the business rules – that impacts everyone.

This is a major change to the way business and validation rules work, with some pretty amazing new capabilities as a result.

The next preview will roll authorization rules into this as well, and that’ll be the last major change for CSLA 4.

The business rule changes apply to both Silverlight and .NET – as always the idea is that the vast majority of your business code should be the same regardless of platform.

I’d like to summarize the primary changes from 3.8 to 4 in regards to business and validation rules.

Simple changes

The simplest change is that the ValidationRules property in BusinessBase is now named BusinessRules. Also, the Csla.Validation namespace has been replaced by the Csla.Rules namespace.

If you are using DataAnnotations validation attributes in 3.8, they continue to work in 4 without change.

That was the easy part. Now for the interesting changes.

Rule classes

Rule methods are replaced by rule classes. This means a 3.8 rule like this:

private static bool MyRule<T>(T target, RuleArgs e) where T : Customer
  if (target.Sales < 10)
    e.Description = "Customer has low sales";
    e.Severity = RuleSeverities.Information;
    return false;
    return true;

becomes a class like this:

private class MyRule : Csla.Rules.BusinessRule
  protected override void Execute(RuleContext context)
    var target = (Customer)context.Target;
    if (target.Sales < 10)
      context.AddInformationResult("Customer has low sales");

It is the same basic rule, but packaged just a little differently. Rule types must implement IBusinessRule, but it is easier to inherit from BusinessRule, which provides a set of basic functionality you’ll typically need when implementing a rule.

The most important thing to understand is that the RuleContext parameter provides input and output for the Execute() method. The context parameter includes a bunch of information necessary to implement the rule, and has methods like AddErrorResult() that you use to indicate the results of the rule.

There’s one coding convention that you must follow: the protected properties from BusinessRule must never be changed in Execute(). I wish .NET had the ability to create an immutable type – a class where you could initialize properties as the object is created, and then ensure they are never changed after that point. But such a concept doesn’t exist, at least in C# or VB. But that is what you must do with rule objects. You can set the properties of the rule object as it is created. After that point, if you change properties of the rule object you are going to cause bugs. So do not change the properties of a rule in Execute() and you’ll be happy.

AddRule Method

In the Customer business class you still override AddBusinessRules(), and that code looks like this:

protected override void AddBusinessRules()
  BusinessRules.AddRule(new MyRule { PrimaryProperty = SalesProperty });

The new AddRule() method accepts an instance of an IBusinessRule instead of a delegate like in 3.8. This one instance of the rule is used for all instances of the business object type. In other words, exactly one instance of MyRule is created, and it is used by all instances of Customer. You must be aware of this when creating a rule class, because it means you can never alter instance-level fields or properties after the rule is initialized. If you do alter an instance-level field or property, you’ll affect the rule’s behavior for all Customer objects in the entire application – and that’d probably be a very bad thing.

Most rule methods that require a primary property will actually require it on the constructor. For example, look at the Required and MaxLength rules:

protected override void AddBusinessRules()
  BusinessRules.AddRule(new MyRule { PrimaryProperty = SalesProperty });
  BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(NameProperty));
  BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxLength(NameProperty, 20));

The result is the same either way, but when you are writing your rules it is typically best to explicitly require a primary property on the constructor if you plan to use the primary property value. Later I’ll talk about per-object rules that have no primary property.

You should also notice that the properties are always Csla.Core.IPropertyInfo, not string property names. The new business rule system requires that you use PropertyInfo fields to provide metadata about your properties. This syntax has been available since CSLA 3.5, and for my part I haven’t created a business class without them for years. This is one part of a larger effort to eliminate the use of string property names throughout CSLA and CSLA-based business code.

Invoking Rules

In the previous AddRule() call, the PrimaryProperty property of the rule is set to SalesProperty. This is what links the rule to a specific property. So when the Sales property changes, this rule will be automatically invoked. As in 3.8, all rules are invoked (by default) when an object is created through the data portal, and can be invoked by calling BusinessRules.CheckRules(). And you can invoke rules for a property with BusinessRules.CheckRules(SalesProperty) – though you should notice that CheckRules() now requires an IPropertyInfo, not a string property name.

If you don’t provide a PrimaryProperty value as shown in this example, the rule method is associated with the business type, not a specific property. This means that the rule will run when CheckRules() is called with no parameter, or when the new CheckObjectRules() method is called to invoke rules attached to the business type.

In summary, there are now three CheckRules() overloads:

  1. CheckRules() – checks all rules for an object
  2. CheckObjectRules() – checks all rules not associated with a specific property (object rules)
  3. CheckRules(property) – checks all rules for a specific property

The same concepts of priority and short-circuiting from 3.8 apply in 4.

InputProperties and InputPropertyValues

You can write that same rule just a little differently, making it unaware of the Target object reference:

public class MyRule : Csla.Rules.BusinessRule
  public MyRule(Csla.Core.IPropertyInfo primaryProperty)
    : base(primaryProperty)
    InputProperties = new List<Csla.Core.IPropertyInfo> { primaryProperty };

  protected override void Execute(RuleContext context)
    var sales = (double)context.InputPropertyValues[PrimaryProperty];
    if (sales < 10)
      context.AddInformationResult("Sales are low");

This is a little more complex and a lot more flexible. Notice that the rule now requires a primary property, which is actually managed by the BusinessRule base class. Also notice that it adds the primaryProperty value to a list of InputProperties. This tells CSLA that any time this rule is invoked, it must be provided with that property value.

In the Execute() method notice how the sales value is retrieved from the context by using the InputPropertyValues dictionary. This dictionary contains the values from the business object based on the properties in the InputProperties list. A rule can require many property values be provided. Of course the rule will only work with objects that actually have those properties!

Because this rule will work with any object that can provide a double property value, the class is now public and could be placed in a library of rules.

The AddRule() method call in Customer must change a little:

protected override void AddBusinessRules()
  BusinessRules.AddRule(new MyRule(SalesProperty));

As before, the PrimaryProperty property is being set, but this time it is through the constructor instead of setting the property directly. This is because the rule now requires the primary property value, and can only work if it is supplied.

Business Rules: Rules that modify data

The CSLA 4 rules system formally supports business rules. Really 3.8 did too, but it was a little confusing with the terminology, which is why ValidationRules is now called BusinessRules – to avoid that confusion.

The RuleContext object now has an AddOutValue() method you can use to provide an output value from your rule:

context.AddOutValue(NameProperty, “Rocky”);

When the rule completes, any out values are updated into the business object using the LoadProperty() method (so there’s no circular loop triggered).

This AddOutValue() technique is safe for synchronous and asynchronous rules, because the business object isn’t updated until the rule completes and control has returned to the UI thread.

If you are creating a synchronous rule, the RuleContext does have a Target property that provides you with a reference to the business object, so you could set the property yourself – just remember that setting a property typically triggers validation, which could cause an endless loop. Overall, it is best to use AddOutValue() to alter values.

Validation Rules: Errors, Warnings and Information

As in 3.8, CSLA 4 allows validation rules to provide an error, a warning or an informational message. The RuleContext object has three methods:

  1. AddErrorResult()
  2. AddWarningResult()
  3. AddInformationalResult()

Each of these methods takes a string parameter which is the human-readable text to be displayed. A rule should only call one of these methods. If the rule calls them more than once, only the last one will have effect.

If AddErrorResult() is called, the rule is returning a failure result, and the business object will become invalid (IsSelfValid will be false).

If no method is called, or AddWarningResult() or AddInformationalResult() is called the rule is returning a success result and the business object will not become invalid. This is basically the same as the 3.8 behavior.

Dependent Properties

The concept of dependent properties is quite different in the new system. Instead of an AddDependentProperty() method, a rule now indicates the properties it affects. This can be coded into the rule itself or specified when AddRule() is called. Either way, what’s happening is that every rule object maintains a list of AffectedProperties for that rule.

When a rule completes a PropertyChanged event is raised for every property in AffectedProperties, as well as any properties altered through AddOutValue().

It is also important to realize that, with an async rule, all properties in AffectedProperties will be marked busy when the rule starts, which typically means the user will see a busy animation (if you are using the PropertyStatus control) to show that the property has some outstanding operation running.

Rule Sets

This is a major new feature of the rules system that is designed to support web applications where multiple customers/clients/organizations are sharing the same virtual root and application. In that case it might be necessary to have different business rules for each customer/client/organization. Rule sets are a way to accomplish this goal.

When you call BusinessRules.AddRule(), the rules are added to a rule set. Normally they are added to the default rule set, and if you only need one set of rules per type of object you can just be happy – it works. But if you need multiple sets of rules per type of object (such as one set of rules for customer A and a different set for customer B), then you’ll want to load each set of rules and attach those rules to your business object type.

This is done by changing the BusinessRules.RuleSet property. For example:

protected override void AddBusinessRules()

  // add rules to default rule set

  // add rules to CustA rule set
  BusinessRules.RuleSet = "CustA";

  // add rules to CustB rule set
  BusinessRules.RuleSet = "CustB";

  // use default rule set
  BusinessRules.RuleSet = “default”;

This code loads rules into three rule sets: default, CustA and CustB. It is up to you to set the RuleSet property to the correct value for each business object instance.

To set the rule set, set the BusinessRules.RuleSet property, then make sure to call BusinessRules.CheckRules() to apply the new set of rules.

The RuleSet value is serialized along with the state of the business object, so you can (and typically will) set the RuleSet property in your DataPortal_Create() and DataPortal_Fetch() methods, and that rule set will be used through the life of the object. I expect the most common scenario will be to set the RuleSet based on the identity of the current user, or some context value in Csla.ApplicationContext.ClientContext.

Per-Object Rules

Finally, it is possible to have rules that are not attached to a specific primary property. These rules are attached to the business object. For example:

protected override void AddBusinessRules()
  BusinessRules.AddRule(new MyObjectRule());

private class MyObjectRule
  protected override void Execute(RuleContext context)
    var target = (Customer)context.Target;
    // check rules here

Notice that the AddRule() method has no primary property specified. Because there’s no primary property, the rule is attached to the business object itself. Normally this type of rule is a private rule in the business class, and uses the business object’s properties directly. But you can specify input and affected properties, as well as provide output values as discussed earlier.

Per-object rules are run in two cases:

  • You call BusinessRules.CheckRules()
  • You call BusinessRules.CheckObjectRules()

Per-object rules are not run automatically when properties change. So if you don’t invoke them, they won’t run.

Async Rules

One of my primary goals in designing the new rule system is to provide a lot of consistency between sync and async rules. To this end, both sync and async rules are constructed the same way: by implementing IBusinessRule or subclassing BusinessRule.

But there are some extra restrictions on async rules. Most notably, async rules must get their input values through the RuleContext, and must provide any output values through RuleContext. To help enforce this, the context.Target property is always null in an async rule. This should help prevent the rule from trying to interact directly with the business object.

The reason this is so important, is that I assume an async rule will run some of its code on a background thread. Most of CSLA (and .NET) is not threadsafe, so having multiple threads interact with a business object will cause problems. If the async rule uses the RuleContext as a message to get and return values, CSLA can help ensure processing occurs on the correct thread.

Here’s a simple async rule. It is a little silly, in that all it does is ToUpper() a string value, but it should give you the idea:

public class AsyncToUpper : Csla.Rules.BusinessRule
  public AsyncToUpper(Csla.Core.IPropertyInfo primaryProperty)
    : base(primaryProperty)
    IsAsync = true;
    InputProperties = new List<Csla.Core.IPropertyInfo> { primaryProperty };

  protected override void Execute(Csla.Rules.RuleContext context)
    var bw = new System.ComponentModel.BackgroundWorker();
    bw.DoWork += (o, e) =>
      var value = (string)context.InputPropertyValues[PrimaryProperty];
      context.AddOutValue(PrimaryProperty, value.ToUpper());
    bw.RunWorkerCompleted += (o, e) =>
      if (e.Error != null)

The rule indicates that it is async by setting IsAsync to true in its constructor. This tells CSLA that the rule expects to run some or all of its logic on a background thread, so CSLA does some extra work for you. Specifically, CSLA marks the primary property and any AffectedProperties as busy before the rule starts and not busy when it ends. It also sets up the rule invocation so its results are handled through an async callback within CSLA. And it makes sure the RuleContext.Target property is null.

Next, notice that the InputProperties list is initialized in the rule’s constructor. This is the list of property values the rule requires to operate, and these property values will be provided through the RuleContext to the Execute() method in the InputPropertyValues dictionary.

The Execute() method itself is using a BackgroundWorker to run some code on a background thread. You can use BackgroundWorker or the async DataPortal and they’ll work fine. The one big requirement here is that whatever you use must ensure that the competed callback is on the UI thread. It is your responsibility to make sure the completed callback is on the UI thread (if any). The BackgroundWorker and data portal do this for you automatically. If you use some other async technology you must take steps to make sure this is done correctly.

The AddOutValue() method is used to provide the output value. Remember that the actual business object property isn’t affected until after the rule completes, which is when CSLA is handling the results of your rule on the UI thread (where it can safely update the business object).

The RunWorkerCompleted event is used to handle any async errors. You’d do the same thing with the data portal, handling the FetchCompleted event (or similar). It is important to remember that exceptions occurring on a background thread are lost unless you carry them through. The code shown here is following what I typically do, which is to add an error result from the rule in the case of an async exception.

One last thing to keep in mind: there is exactly one instance of your rule object being used by all instances of a business type. Because of this, the Execute() method must be atomic and stateless. To put it another way, you should never, ever, ever alter any instance-level fields or properties of the rule object from the Execute() method. If you do alter an instance-level field or property of the rule object, that change will affect all business objects, not just the one you are running against right now. And with async rules you’ll run into race conditions and other nasty multi-threading issues. This is really the same restriction I mentioned earlier with sync rules – don’t change rule properties in Execute() – but it is so important that I wanted to reiterate the point here too.

While there are some restrictions on how you construct an async rule, I am pretty happy with how similar sync and async rules are to implement. In fact, all the async concepts (input values, AddOutValue()) work just fine with sync rules too.

Moving from 3.8 to 4

While the new business rules system is somewhat different from the 3.8 implementation, the process of moving from 3.8 to 4 isn’t terribly painful.

  • Every rule method must become a rule class. This is a pretty mechanical process, but obviously does require some work
  • Every use of ValidationRules must be changed to BusinessRules
  • Every AddRule() call will be affected, which is another mechanical change
  • Dependent properties become AffectedProperties on each AddRule() method call

I was able to get the entire unit test codebase changed over in less than 8 hours – and that included changes not only for the business rules, but also for the data portal and several other breaking changes. I don’t mean to trivialize the effort required, but the changes are mostly mechanical in nature, so it is really a matter of plowing through the code to make the changes, which is mostly repetitive and boring, not really hard.


I’m using the major version change from 3 to 4 as an opportunity to make some fairly large changes to CSLA. Changes that enable some key scenarios needed by Magenic customers, and requested by people on the forum explicitly or implicitly. Some effort will be required to upgrade, but I suspect most people will find it well worth the time.

The big changes are:

  • Rule sets
  • Per-object rules
  • Rule objects instead of rule methods
  • Common model for sync and async rules

I’m pretty excited about these changes, and I hope you find them useful!

Monday, April 05, 2010 12:40:05 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [19]  | 
 Friday, April 02, 2010

This is the first of a series of blog posts I’m putting together as I prepare for the next preview release of CSLA 4. That preview release is coming soon, there are just a couple more things to wrap up, but I want to have the preview out by the .NET 4 launch, which is April 12.

CSLA 4 includes a lot of changes, including some changes to the data portal. This post covers the highlights.

DataPortal methods

Some are relatively small, but might impact existing code.

One example is the removal of the non-generic DataPortal method overloads. Create() is gone in favor of Create<T>().

Another example is that DataPortal_Fetch(object) is no longer a virtual method in the base classes, which means if you are overriding this method you’ll need to remove the override keyword in your code.

The reason for removing the non-generic DataPortal methods is that it makes the criteria parameter for Create/Fetch/Delete more flexible. It is now possible to use any serializable object as a criteria. On .NET this means anything that can be serialized with the BinaryFormatter and/or NDCS. On Silverlight this means anything that can be serialized with MobileFormatter. And this includes primitive types. In short, you can now do this:

var cust = DataPortal.Fetch<Customer>(123);

This eliminates the need for the SingleCriteria<> type, and generally simplifies most data portal calls.

Proxy factory

A more significant change, though one that has no impact unless you want to use it, is the ability to create your own proxy factory. By default the data portal loads the client-side proxy based on the type you specify in your config file – so you can switch between local, WCF, Remoting and other proxies through configuration.

But it is now possible to create a proxy factory by implementing IDataPortalProxyFactory. This factory is responsible for creating the data portal proxy object based on the type of business object being sent through the data portal. Add a key in your config file for CslaDataPortalProxyFactory to specify the assembly qualified type of your implementation and CSLA will use that instead of the default behavior.

The idea is that some applications need to use different app servers or different protocols for different business objects. If you create your own proxy factory, you get the opportunity to examine the business object type (probably using reflection) so you can decide which proxy should be used to talk to an app server for that particular type of object.

Server exceptions

(not implemented yet, but in progress)

Server exceptions are always returned to the client wrapped in a DataPortalException. This is not changing, because the DataPortalException is what allows CSLA to provide you with the full stack trace and other useful information from the server.

However, it is now possible to replace the original server exception with a new exception in your override of DataPortal_OnDataPortalException() or the InvokeError() method of a factory object.

Silverlight flexibility

The Silverlight data portal was not as flexible as the .NET data portal. Specifically, it wasn’t possible to create your own proxy/host channel that totally replaced the WCF proxy/host provided by CSLA. In CSLA 4 you can now create completely custom proxy/host channels for the Silverlight data portal. This means you could, for example, create one that didn’t use WCF at all, but instead used raw TCP sockets. Or more likely, it means you can create a proxy/host that uses a custom third-party WCF binding.

A related change is to the MobileFormatter, which now has the ability to provide you with completely serialized data (the default), or to provide you with the serialized data in an intermediate DTO form. If you get the DTO form, you are getting an object graph that consists only of objects which can be serialized using the DataContractSerializer (or similar serializers). This opens up a lot of flexibility, because it means you can apply other serializers (perhaps from third parties) to the DTO graph. In some cases this

Design time data

VS10 has a new design time data model, so the old design time data behaviors have been removed from the data portal. This won’t break any code, but if you were using the design time data generation concept, it is now gone and your methods won’t be invoked.

.NET compression sample

There’s a new sample for .NET that shows how to use a standard compression library (of your choice) to compress the data that goes over the data portal. I think it is probably best to get a WCF binding that does the compression, but if you want an alternative this sample shows you how to do it.

Overall the data portal continues to offer the same n-tier and network transport flexibility it has always provided, but these changes make common scenarios easier to implement, and enable some important advanced scenarios that have been frequently requested.

Friday, April 02, 2010 11:36:03 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [1]  | 
 Thursday, March 04, 2010

MCsla is a prototype that takes SQL Server Modeling (aka “Oslo” and “M”) and CSLA .NET, using them to create an end-to-end story. This story goes like this:

  1. Developer creates a business database for business data
  2. Developer writes concise DSL code
  3. Developer “compiles” DSL code into the SQL Server Modeling repository
  4. End user executes a runtime application, which dynamically creates a UI, business layer and data layer that uses the business database – all this based on the compiled DSL metadata stored in the repository

This saves the developer from a lot of work. In fact the developer writes perhaps 5% of the code they would have written to create the UI, business layer and data layer by hand.

See my discussion of the concepts and prototype in a three part video series:

Exploring SQL Server Modeling through MCsla

You can see the MCsla code in the CSLA .NET repository (web view) or grab it using any svn client from svn://

Thursday, March 04, 2010 11:06:23 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [7]  | 
 Monday, March 01, 2010

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 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.


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.


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


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]  | 
 Tuesday, January 26, 2010

From time to time CSLA .NET users are able to provide me with a summary of their experiences with the framework. Here’s an account I thought I’d share (with permission of course). First, here are some useful links related to A.J.’s summary:

Now to A.J.’s comments:

To all those who struggle with CSLA:

I must admit that at the beginning I had a hard time with CSLA. I remember when I first looked at the ver. NET 2.0, it seemed that there were dozens of objects all over the place and it simply appeared overdeveloped. The whole move to .NET from VB6 seemed even more discouraging to me.

The good thing is that I am stubborn (must be my Slovak origin). I was equally determined to understand why particular approach was chosen, what exactly was the author (Rocky) thinking, what were his findings? So I started way back at VB6 Business Objects book. Shortly after that I moved to first VB.NET Business Objects and then the 2005…story continues.

At some point I had an idea to strip CSLA, make it leaner, less bloated. I figured “why not have some type of a framework that entirely runs locally and doesn’t need any of this extra stuff?”

So I started to strip out serialization, reflection (Data Portal), remoting, n-level undo, trimming validation rules, created new code gen templates, and I soon realized that I was gaining nothing other than trouble, wasting time, and giving away a lot not to mention that this new “low fat” thing of mine needed some serious testing and documentation. It is obvious that I didn’t “get it”.

Well, I went through the 2005 book again, this time at the slower pace. And again, and again. PT Tracker helps for sure.  Eventually it started to make sense. If you write down what functionality and behavior you would like to have in your business object and data access object, you soon realize that CSLA has it all and does it better that you originally wanted. A true "E pour si muove" moment for me.

I guess the message is not to give up. Everything that is there needs to be there. The alternatives were to try to make some sense of data sets, data islands, relations, contexts, EF, and who knows what else out of which none include comprehensive validation, authorization, and simplistic object relation.

Invest your time in CSLA. Get a decent code generation tool that has CSLA templates or write your own templates.

It's good for you. Have fun!


Santa Monica, CA

clip_image001  clip_image001[4]

Tuesday, January 26, 2010 11:29:00 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [2]  | 
 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]  | 
 Thursday, January 07, 2010

Miguel Castro has kindly compiled a chm help file from the 3.8.2 source code, and it is now available on the CSLA .NET download page – click here.

Thanks Miguel!!

Thursday, January 07, 2010 3:36:34 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [2]  | 

I’ve been working in the VS10 beta trying to get my unit tests converted from nunit to mstest. Overall that went very smooth and easy thanks to some great foresight on the part of the Magenic guys who put together most of the tests.

But I keep running into issues where random tests fail due to a file IO exception:

“a procedure imported by System.Transactions could not be loaded”

The same tests may fail or work seemingly at random. After chasing this far too long, I think I’m going to assume it is a .NET 4 beta bug and just live with it for now. I can’t see where it is my code, since this code is unchanged from .NET 3.5 to 4.0, and any given test will pass around 90% of the time and fail around 10% of the time – and they only fail when run in groups of tests – so I strongly suspect something is messed up in the .NET type loader or something along that line…

Frustrating though – hopefully the next release of VS10 will magically resolve the issue.

Thursday, January 07, 2010 12:05:01 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [6]  | 
 Tuesday, December 29, 2009

csla_net_videos For those who have purchased the CSLA .NET Core 3.8 video series, you'll be happy to know that segment 6 (Authentication and authorization) is online, along with associated sample code.

This completes the core video series. As we move into 2010 I plan to produce separate UI-specific videos covering WPF, ASP.NET MVC, etc, so watch for those.

If you haven't purchased the CSLA .NET Core 3.8 video series, there are only two days left of the special pre-release pricing. And only two days left for the holiday discount on the CSLA .NET for Silverlight video series.

So if you want to save 15% to 33% off regular pricing, buy the video series before the end of 2009!

Tuesday, December 29, 2009 12:42:01 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Sunday, December 20, 2009

Part 5 of the Core CSLA .NET 3.8 video series is now available from the download page.

This video segment covers business and validation rules in CSLA .NET. This includes discussion of the .NET DataAnnotations attributes, along with synchronous and asynchronous rule methods, rule priorities, short-circuiting and a whole lot more.

The business and validation rule subsystem is one of the most important and compelling features of CSLA .NET, and even seasoned users of the framework are likely to learn some new things by watching this video!

If you haven’t purchased the video series yet, please go to – and don’t wait, because the special 33% discount pricing only runs through the end of 2009!!

Sunday, December 20, 2009 11:49:00 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Thursday, December 17, 2009

The 4th video in the Core CSLA .NET 3.8 video series (available from is now online. If you’ve already purchased the series, you can download the new video from the download page.

Video 4 covers the data portal and how you can use it for 1-, 2- and 3-tier deployments of your applications. This is 1:53 hours of in-depth content, providing an overview of the data portal concept, and an extensive walk-through of code using the data portal. You’ll see how to configure the client, set up and configure a server – all using WCF. Even better, you’ll see various object patterns that leverage the data portal, including the powerful unit of work pattern.

The special pre-release pricing is still in effect for this amazing video series. Buy before the end of the year and get 33% off the regular $300 price. That’s right – buy now for just $200.

And while you are at the store, take a look at the CSLA .NET for Silverlight video series, which is 15% off until the end of 2009. If you are using CSLA .NET to build Silverlight applications, this video series will get you up and running – from creating your first Silverlight project in Visual Studio 2008, through implementing the UI, the business objects and data access, everything you need to know is in this one series of videos.

Thursday, December 17, 2009 10:10:13 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Wednesday, December 09, 2009

There’s a new DNR TV show online where I talk about the MVVM support added to CSLA .NET 3.8.


Wednesday, December 09, 2009 12:18:28 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Sunday, December 06, 2009

Last week I spent a few hours switching the CSLA .NET for Windows unit/integration tests from nunit to mstest.

This wasn’t terribly hard, because the tests were originally created with the idea of supporting both test frameworks. Of course as different people added tests over several years time inconsistencies crept in, and that’s what I had to address to make this switch.

I didn’t remove the compiler directives for nunit, so it should take relatively little effort to switch back to nunit, but I don’t personally plan to do that.

mstest is now available in all professional versions of Visual Studio 2010, and Microsoft is obviously faster about getting their test framework updated as .NET and Visual Studio change. Looking at there’s no mention of VS10 or .NET 4.0. Yes, I know people have tweaked nunit to work on .NET 4.0, but mstest allows me to eliminate one level of uncertainty from my process.

Besides, there are all these really cool tools and capabilities in VS10, some of which tie into testing and coverage, and this gives me motivation to play with them :)

Sunday, December 06, 2009 9:02:07 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Sunday, November 29, 2009

The Core CSLA .NET 3.8 Video Series provides nearly 9 hours of high quality training content to build your skills around CSLA .NET - for any type of user interface. The focus of this series is not on user interface development, it is on the core concepts of CSLA .NET – the knowledge you need to build a solid business layer for any application.

This six part series provides an introduction to CSLA .NET, then dives into detail to show how to code each type of business object, including business, validation and authorization rules. You’ll also learn about the various options for implementing data access, and how to effectively utilize the data portal for 1-, 2- and 3-tier deployments of your applications.

I’m offering a special “pre-release” sale price of 33% off on the video series. Buy now with this heavy discount, and get each new video segment as they become available. Segments 1 and 2 are online now!

Act now, the discount will phase out as the entire series comes online!!

Here is a summary of the video segments:

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, and the requirements necessary to build CSLA .NET applications.

Business Object Types
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.

Data Access
This video details the various options supported by CSLA .NET for data access. You will learn how to put data access code into your business class, or into a separate data access assembly using a repository pattern, 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.

Data Portal
In this video you will learn how to build 1-, 2- and 3-tier applications using CSLA .NET. 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 and Validation Rules
In this video you will learn how to implement business and validation rules in your business objects. This includes the use of validation attributes, common validation rules and custom business and validation rules. You will also learn how to implement and use synchronous and asynchronous business rules in your applications.

Authentication and Authorization
In this video you will learn about the various authentication and authorization techniques supported by CSLA .NET. Authentication options include Windows, ASP.NET Membership Provider and custom authentication. The CSLA .NET authorization subsystem supports per-property and per-type authorization, which is role-based by default, and can be customized.

Sunday, November 29, 2009 11:46:20 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

I’m heading to Atlanta to talk about “Microsoft Oslo” – oh wait – to talk about the SQL Server Modeling at ALEMUG on Wednesday, December 2.

Actually I’ll be talking about MCsla, which is the prototype domain specific language and runtime I created for CSLA .NET using the SQL Server Modeling tools. It is a good topic, because I get to talk about designing and defining a DSL with a custom grammar, using the m.exe and mx.exe tools to compile DSL code into instance data, and then defining a schema so that data can be loaded into SQL Server tables. Tables that you can view (and edit) using “Quadrant”, or any other SQL Server tools of your choice.

In short, nearly every part of SQL Server Modeling gets used, and the DSL code actually executes as a WPF application – so it is an end-to-end prototype solution.

So if you are in the Atlanta area, maybe I’ll see you there!

Sunday, November 29, 2009 10:39:08 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Thursday, November 26, 2009

csla_logo1_42 In celebration of the holiday season the CSLA .NET training videos are on sale now through the end of the year.

Save 15% off the regular price on the following products from the CSLA .NET online store:

  • CSLA .NET for Silverlight video series (includes sample code)
  • Business object types video (includes sample code)
  • N-Tier data access video (includes sample code)

Don’t miss this opportunity to get a great deal on these invaluable CSLA .NET training materials!

Thursday, November 26, 2009 12:12:30 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Thursday, November 05, 2009

CSLA .NET version 3.8.0 is now released and is available for download.

For Windows Forms and Web Forms users there are not any major new features, but some of the bug fixes may be valuable. Upgrading from 3.7 to 3.8 should be painless for these UI types (as well as XML services and workflow interfaces).

If you use WPF or Silverlight, you will almost certainly want to take a look at the features in 3.8. The downside is that there are several breaking changes in the XAML controls, but the upside is that the new XAML control implementations are far superior to previous versions. Controls impacted include:

  • PropertyStatus – now supports a “pull model” so a UI control can bind to properties of PropertyStatus, rather than having PropertyStatus directly manipulate the UI control’s IsReadOnly and IsEnabled properties. Also in Silverlight, PropertyStatus now makes use of the Silverlight 3 binding capabilities.
  • InvokeMethod – can now be triggered by any UI event, and can invoke a couple different method signatures on the DataContext. Also, MethodParameter is now bindable. The end result is that InvokeMethod provides really good support for both the CslaDataProvider model and the MVVM design pattern.
  • Execute – a new control that is a trigger action that works in the Blend 3 Interactivity model. This is very similar to InvokeMethod, but works with the Blend 3 scheme.
  • ViewModelBase<T> – provides a base class to make it easy to build a viewmodel class when using the MVVM pattern.
  • ViewModel<T> – provides a base class to make it easy to build a viewmodel class that works with InvokeMethod/Execute when using the MVVM pattern.
  • CslaDataProvider – the ObjectInstance property is now bindable, so it is possible to create master-detail (parent-child) relationships in the UI between different data provider controls.

See this blog post for more MVVM information.

Other important or interesting features include:

  • Support for System.ComponentModel.DataAnnotations validation attributes. This blog post has information about the change.
  • A CSLA .NET specific model binder for ASP.NET MVC, enabling the use of CSLA .NET rule methods and DataAnnotation validation attributes in the same object, with the UI displaying combined results.
  • Performance enhancements for MobileFormatter, including the use of binary XML. This forum thread has some great comparative information around binary XML and compression.
  • Better support for altering the behavior of IsDirty when using managed backing fields. This blog post has good information about using the changes.
  • All the samples have been updated to build with 3.8.0, and the MVVMexperiment projects for WPF and Silverlight illustrate most of the new MVVM features.

There are also numerous bug fixes, including a solution to the memory leak issue with BusyAnimation and a null reference issue with LINQ to CSLA. See the change logs for more details about bug fixes.

Thursday, November 05, 2009 8:48:50 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
  • WPF (to a lesser degree)
  • 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]  | 
 Monday, November 02, 2009

When I sit down to work on CSLA .NET I look at the wish list, and I tend to order my work based on a few priorities:

  1. Is it a bug with no workaround?
  2. Will it help a Magenic client/project?
  3. Is it fun/interesting/intellectually stimulating to me?
  4. Will it help make the lives of a reasonable number of users better?
  5. Is it easy (low-hanging fruit)?
  6. Does it make CSLA more "complete"? (like the recent MVVM work)

And there are some anti-priorities:

  1. Is it boring? Or worse, boring and time consuming?
  2. Does it increase complexity without amazing payoff in productivity/flexibility?
  3. Does it increase my testing/support surface area?
  4. Does it focus on "legacy" technologies (now including Windows Forms, Remoting, asmx, Enterprise Services and maybe Web Forms)?
  5. Does it solve a problem that's already been solved? (like ORM stuff or UI framework stuff)

These priorities are especially important during point releases, but they certainly factor into major releases (like 4.0) as well. Though the "fun factor" becomes a much bigger priority for major releases, and tactical things like bug fixes or specific Magenic client requirements are usually not as big an issue.

I guess this is one advantage of working on a free framework. Since I’m not directly making money by selling the framework, I can prioritize what I do based on my own intellectual stimulation and fun as much as anything else.

Monday, November 02, 2009 10:25:17 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Friday, October 30, 2009

CSLA .NET 3.8.0 Beta 3 is now available for download

Beta 3 includes fixes for some bugs found in Beta 2 (mostly in ViewModelBase and BusyAnimation), and two more significant changes:

  • InvokeMethod no longer attempts to manage the attached UI control’s IsEnabled property; this is a breaking change, but was necessary to avoid an otherwise unavoidable memory leak. It wasn’t a good practice anyway, so this implementation is both safer and better.
  • There’s a new Csla.Web.Mvc.CslaModelBinder class; it addresses a key issue around the data annotation validation attributes and how their validation information is reported back to the ASP.NET MVC framework. (I know I said Beta 1 was feature-complete, but this was too important to hold back…)

I’ve also continued to update samples, and I think all the C# samples are now updated, as are some of the VB ones. Hopefully I can get the rest of the VB ones updated before final release.

I am still on track to release 3.8.0 in about a week – hopefully Nov 6 or 9.

Friday, October 30, 2009 5:07:05 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Sunday, October 25, 2009

I have put CSLA .NET 3.8.0 Beta 2 online for download.

This completes the work for version 3.8.0, and (barring anyone finding a show-stopping issue) I plan to release 3.8 in just a couple weeks.

For Windows Forms and Web Forms users there are not any major new features, but some of the bug fixes may be valuable. Upgrading from 3.7 to 3.8 should be painless for these UI types (as well as XML services and workflow interfaces).

If you use WPF or Silverlight, you will almost certainly want to take a look at the features in 3.8. The downside is that there are several breaking changes in the XAML controls, but the upside is that the new XAML control implementations are far superior to previous versions. Controls impacted include:

  • PropertyStatus – now supports a “pull model” so a UI control can bind to properties of PropertyStatus, rather than having PropertyStatus directly manipulate the UI control’s IsReadOnly and IsEnabled properties. Also in Silverlight, PropertyStatus now makes use of the Silverlight 3 binding capabilities.
  • InvokeMethod – can now be triggered by any UI event, and can invoke a couple different method signatures on the DataContext. Also, MethodParameter is now bindable. The end result is that InvokeMethod provides really good support for both the CslaDataProvider model and the MVVM design pattern.
  • Execute – a new control that is a trigger action that works in the Blend 3 Interactivity model. This is very similar to InvokeMethod, but works with the Blend 3 scheme.
  • ViewModelBase<T> – provides a base class to make it easy to build a viewmodel class when using the MVVM pattern.
  • ViewModel<T> – provides a base class to make it easy to build a viewmodel class that works with InvokeMethod/Execute when using the MVVM pattern.
  • CslaDataProvider – the ObjectInstance property is now bindable, so it is possible to create master-detail (parent-child) relationships in the UI between different data provider controls.

See this blog post for more MVVM information.

Other important or interesting features include:

  • Support for System.ComponentModel.DataAnnotations validation attributes.
  • Performance enhancements for MobileFormatter, including the use of binary XML.
  • Better support for altering the behavior of IsDirty when using managed backing fields.

There are also numerous bug fixes, including (hopefully) a solution to the memory leak issue with BusyAnimation. See the change logs for more details about bug fixes.

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

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?


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.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:EventTrigger EventName="Click">
      <csla:Execute MethodName="SaveData" />

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:


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


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


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


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


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


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


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


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

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:

  <this:SalesOrderViewModel x:Key="ViewModel" />
<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”>
    <this:LineItemsViewModel x:Key=”LineItemsViewModel”
                                           Model=”{Binding Path=Model.LineItems}”/>
  <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]  | 
 Tuesday, October 20, 2009

Dunn Training is offering their CSLA Master Class next month in Atlanta

If you want to get up to speed fast with CSLA .NET this is the class for you. Instructor Miguel Castro is a CSLA .NET expert and has contributed elements to the framework itself, as well as being the author of the courseware used for the class.

Sign up now!

Tuesday, October 20, 2009 1:28:14 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Monday, October 19, 2009

Microsoft has made Visual Studio 2010 and .NET 4.0 Beta 2 available for download to MSDN subscribers, with general availability soon. VS10 includes a lot of really nice features over VS2008, and I’m personally very excited to see the Beta 2 release.

I’ve made a pre-alpha CSLA .NET “4.0” available for download as well. This is really just the version 3.8.0 code (somewhere between beta 1 and beta 2) that I’ve updated to build under Visual Studio 2010 with .NET 4.0.

Over the next few months I’ll continue to release updates to version 4.0 that take advantage of the .NET 4.0 features, but I wanted to make sure there was a version online that builds with VS10 as soon as possible, so this is it – enjoy!

Monday, October 19, 2009 1:41:33 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.

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]  | 
 Saturday, October 03, 2009

CSLA .NET version 3.8 Beta 1 is now available for download.

Beta 1 brings the WPF PropertyStatus in line with the Silverlight version.

And Beta 1 adds support for the System.ComponentModel.DataAnnotations attributes. Data annotation attributes applied to properties are automatically added as rules using the CSLA .NET validation rules subsystem when ValidationRules.AddAnnotations() is called in your AddBusinessRules() override. If you don’t override AddBusinessRules() the base implementation calls AddAnnotations() on your behalf.

The C# ProjectTracker has been updated to work with 3.8.

Saturday, October 03, 2009 10:07:14 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Tuesday, September 29, 2009

CSLA .NET version 3.8.0 alpha 3 is now available.

The primary focus of version 3.8 is to enable more seamless support for the MVVM design pattern in Silverlight and WPF. The alpha 3 release brings the features I’ve been implementing in Silverlight into WPF.

Also, the samples downloads now include my MVVM experimental applications. I suppose you can call these samples, but they are really the apps I’m using to try out different ideas – so they aren’t what I’d consider a “full sample”. Still, you can see how the various new features work, and how the MVVM features allow creation of at least a basic CRUD UI (with some navigation) with no code-behind any XAML.

Please note that version 3.8 requires System.Windows.Interactivity.dll to build. This assembly is installed with Expression Blend 3, or the Blend 3 SDK. You must install at least the SDK before you can build CSLA .NET 3.8.0.

The new features (now in Silverlight and WPF) include:

  • New ViewModelBase and ViewModel base classes to simplify the creation of view model types in your application. ViewModelBase provides protected methods to simplify interaction with business object types, and ViewModel is an example subclass that exposes public methods for use by InvokeMethod or Execute
  • CslaDataProvider enhancements to allow “chaining” of data providers (so a child data provider’s ObjectInstance property can be bound to a property from a parent data provider’s business object)
  • InvokeMethod enhancements to handle essentially any UI control event, and to invoke either data provider or view model methods, including passing parameter values from data bound sources in the UI. Additionally, InvokeMethod is now fully bindable which simplifies (but changes) the XAML needed to use the control
  • Execute trigger action, which is somewhat like InvokeMethod, but is an action used within a System.Windows.Interactivity trigger handler. The trigger action model imposes some limitations on data binding, so Execute isn’t quite as powerful as InvokeMethod, but it is more compatible with the Blend 3 designer model
  • PropertyStatus enhancements so you can bind your UI control’s properties to properties on PropertyStatus to control its visual state. This is instead of having PropertyStatus try to directly manipulate the visual state of the UI control. Additionally, PropertyStatus is now fully bindable which simplifies (but changes) the XAML needed to use the control
  • MobileFormatter now uses binary XML by default to help improve performance

Please give these new features a try and let me know your thoughts on the forum.

Tuesday, September 29, 2009 2:36:13 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

Thanks to a tremendous amount of time and effort on the part of Sean Rhone there’s a new release of CSLA .NET VB available for download from the VB download page.

Thank you Sean!!

This VB version of the framework should now have full parity with CSLA .NET for Windows 3.6.3. There’s one slight difference with the async data portal to work around the lack of multi-line lambda expressions in VB 9 – hopefully we’ll be able to bring that code back into parity with C# when VB 10 is available.

I recommend using this VB version of the framework as an implementation reference, not for production. The official release of CSLA .NET for Windows is the C# implementation, which is currently at version 3.7.1. It is available from the download page.

Tuesday, September 29, 2009 12:32:15 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Monday, September 28, 2009

CSLA .NET 3.7.1 for Windows and Silverlight are now available for download.csla_logo1_32_r

Version 3.7.1 supports .NET 3.5 SP1 and Silverlight 3.

This is primarily a bug fix release to address some issues with 3.7.0. Please see the change logs for details about the changes.

If you are using CSLA .NET version 3.5 or higher I recommend you look at the 3.7.1 release, as this is the current version for use with .NET 3.5 SP1, Visual Studio 2008 and Silverlight 3.

Monday, September 28, 2009 1:04:14 PM (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}"
         csla:InvokeMethod.Target="{Binding Source={StaticResource ListModel}}"
         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}"
    <i:EventTrigger EventName="SelectionChanged">
      <csla:Execute MethodName="ShowItem2" />

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}"
         Name="DataListBox" />

And the Button looks like this:

<Button Content="Process items"
        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}"

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:EventTrigger EventName="Click">
      <csla:Execute MethodName="ProcessItems2" />

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:EventTrigger EventName="Click">
      <csla:Execute MethodName="Load" MethodParameter="{Binding ElementName=MyListBox, Path=SelectedItem}" />

(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:EventTrigger EventName="Click">
      <csla:Execute MethodName="Load" />

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

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]  | 
 Thursday, August 13, 2009

CSLA .NET 3.6 normally requires .NET 3.5 SP1. However, if you are using Visual Studio 2008 it is possible (with some work and a third party LINQ library) to get CSLA .NET 3.6 running on .NET 2.0 SP1. Jonny Bekkum has done just that, and has contributed the results of his efforts to the community - thank you Jonny!

The result is a large subset of version 3.6.3 that builds and runs on .NET 2.0 SP1, eliminating the need for .NET 3.5 SP1 (though adding the need for LINQbridge, a third-party component).

You get to use the most of the new features in CSLA .NET, including:

  1. Managed properties in BusinessBase, ReadOnlyBase and CommandBase that reduces the number of lines required to declare a property.
  2. PropertyInfo type for less hardcoding of property names in your code.
  3. FieldManager and DataPortal enhancements, including the asynchronous DataPortal and Child_XYZ mehthods.
  4. ObjectFactory for separation of BO and DAL
  5. CslaActionExtender reduces the amount of code behind required in Windows Forms
  6. Reflection enhancements (MethodCaller) for dynamic calls
  7. An easier upgrade path to CSLA .NET 3.7 and Silverlight
  8. and a lot more ….

Jonny has not only got the CSLA .NET framework running on .NET 2.0, but he’s got unit tests and samples! This is an amazing contribution to the community.

You can download this version from

Thursday, August 13, 2009 10:33:45 AM (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.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:

         ItemsSource="{Binding Path=Model}"
         ItemTemplate="{StaticResource DataList}"
         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.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]  | 
 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(
  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); }
    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)

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.


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.


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.


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.Resource="{StaticResource ListModel}"

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.Resource="{StaticResource ListModel}"

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:


Or maybe more elegant would be a different property:


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 01, 2009

I’ve updated my prototype MCsla project to work on the “Olso” May CTP. The update took some effort, because there are several subtle changes in the syntax of “Oslo” grammars and instance data. What complicated this a little, is that I am using a custom DSL compiler because the standard mgx.exe utility can’t handle my grammar.

Still, I spent less than 8 hours getting my grammar, schemas, compiler and runtime fixed up and working with the CTP (thanks to some help from the “Oslo” team).

I chose at this point, to put the MCsla project into my public code repository. You can use the web view to see the various code elements if you are interested.

The prototype has limited scope – it supports only the CSLA .NET editable root stereotype, which means it can be used to create simple CRUD screens over single records of data. But even that is pretty cool I think, because it illustrates the end-to-end flow of the whole “Oslo” platform concept.

A business developer writes DSL code like this:

Object Product in Test
  Public ReadOnly int Id;
  Public string Name;
  Public double ListPrice;
} Identity Id;

(this is the simplest form – the DSL grammar also allows per-type and per-property authorization rules, along with per-property business and validation rules)

Then they run a batch file to compile this code and insert the resulting metadata into the “Oslo” repository.

The user runs the MCslaRuntime WPF application, which reads the metadata from the repository and dynamically creates a XAML UI, CSLA .NET business object and related data access object that talks to a SQL Server database.


The basic functionality you get automatically from CSLA .NET is all used by the runtime. This includes application of authorization, business and validation rules, automatic enable/disable for the Save/Cancel buttons based on the business object’s rules and so forth.

If the business developer “recompiles” their DSL code, the new metadata goes into the repository. The user can click a Refresh App button to reload the metadata, immediately enjoying the new or changed functionality provided by the business developer.

The point is that the business developer writes that tiny bit of DSL code instead of pages of XAML and C#. If you calculate the difference in terms of lines of code, the business developer writes perhaps 5% of the code they’d have written by hand. That 95% savings in effort is what makes me so interested in the overall “Oslo” platform story!

Wednesday, July 01, 2009 5:15:07 PM (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]  | 
 Wednesday, May 27, 2009

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

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

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

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

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

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

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

I have put a beta release of version 3.6.3 online for download. This version is now feature complete, and my plan is to release it around the next of next week. I'll only be changing this version for show stopping issues, otherwise this is the final code.

If you are using 3.6.x, you should download and test this version. There are important bug fixes in this version - please see the change logs for details. If you are developing Silverlight, WPF or Windows Forms applications (in particular), you'll almost certainly want some of these fixes!

There are minor new features as well, including

  • Named connections in the GetManager methods for ConnectionManager and similar types
  • ReadProperty() method in the ObjectFactory base class

But the primary focus is on fixing bugs and refining key usage scenarios.

Tuesday, May 26, 2009 11:41:52 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Tuesday, May 19, 2009

I decided to try using Visual Studio 2010 Beta 1 to open CSLA .NET for Windows 3.6.3.

Unfortunately this isn’t as smooth as one would hope.

VS runs an upgrade wizard on the solution, but this breaks the project file. I had to manually edit the project file using notepad to remove a bunch of stuff in the configuration. How did I know what to remove? I created a brand new Class Library project for .NET 4.0 and compared the contents of that file to the Csla file…

Now that I could open the solution I figured it would just build. Unfortunately not.

Two references were broken: System.ComponentModel.dll and System.Runtime.Serialization.dll. Perhaps the project references them by version number, I’m not sure. I do know that the references were broken, so I removed and re-added the references to these files.

Next is an issue with the web service reference required for the old asmx data portal channel. I suspect the issue is that I need to update (or remove and re-add) the service reference to the web services host. But I am not entirely sure it is worth carrying this legacy channel forward (or the Remoting or Enterprise Services ones) into CSLA .NET 4.0 – WCF is the preferred solution after all, and it has been around for a few years. So at least for now I just removed the service reference, the web service proxy class in Csla.DataPortalClient and the web service host class in Csla.Server.Hosts.

The result is that the solution builds. I haven’t tried running (or building) the unit test project yet, and I suspect there’ll be a few issues there as well, but at least the basic build of Csla.dll is now possible.

Tuesday, May 19, 2009 10:34:55 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
 Monday, May 18, 2009
Monday, May 18, 2009 6:00:00 PM (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

Download the content from

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:

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]  | 
 Friday, April 10, 2009

I’m working on a number of things at the moment. Most notably the CSLA .NET for Silverlight video series that will be available in the very near future (it turns out that creating a video series is a lot of work!). And of course I’m prepping for numerous upcoming speaking engagements, and I’d love to see you at them – please come up and say hi if you get a chance.

But I’m also working on some content around Microsoft Oslo, MGrammar and related concepts. To do this, I’m creating a prototype “MCsla” language (DSL) that allows the creation of CSLA .NET business objects (and more) with very concise syntax. I’ll probably be blogging about this a bit over the next couple weeks, but the goal is to end up with some in-depth content that really walks through everything in detail.

My goal is for the prototype to handle CSLA editable root objects, but covers business rules, validation rules and per-type and per-property authorization rules. Here’s a conceptual example:

Object foo
    // per-type authz
    Allow Create ("Admin");
    Allow Edit ("Admin", "Clerk" );

    // property definitions

    Public ReadOnly int Id;

    Public Integer Value {
       // per-property authz
       Allow Write ("Clerk" );
       // business/validation rules
       Rule MinValue (1 );
       Rule MaxValue (50 );

But what I’ve realized as I’ve gotten further into this, is that I made a tactical error.

A lot of people, including myself, have been viewing MGrammar as a way to create a DSL that is really a front-end to a code generator. My friend Justin Chase has done a lot of very cool work in this space, and he’s not alone.

But it turns out that if you want to really leverage Microsoft Oslo and not just MGrammar, then this is not about creating a code generator. And what I’m finding is that starting with the DSL is a terrible mistake!

In fact, the idea behind MOslo is that the DSL is just a way to get metadata into the Oslo repository. And you can use other techniques to get metadata into the repository as well, including the graphical “Quadrant” tool.

But my next question, and I’m guessing yours too, is that if all we do is put metadata into the repository, what good is that???

This is where a runtime comes into play. A runtime is a program that reads the metadata from the repository and basically executes the metadata.

I always had a mental picture of MOslo “projecting” the metadata into the runtime. But that’s not accurate. It is the runtime that “pulls” metadata from the repository and then uses it.

And that’s OK. The point is that the runtime is this application that interprets/compiles/uses/consumes the metadata to end up with something that actually does some work.


What I’m learning through this process, is that the DSL exists to service the metadata in the repository. But it is the runtime that defines the metadata. The runtime consumes the metadata, so the metadata exists to serve the needs of the runtime.

In other words, I should have started with the runtime first so I knew what metadata was required, so I could design a DSL that was capable of expressing and capturing that metadata.

The example MCsla code you see above is OK, but it turns out that it is missing some important bits of information that my runtime needs to function. So while the DSL expresses the important CSLA .NET concepts, it doesn’t express everything necessary to generate a useful runtime result…

So at the moment I’ve stopped working on the DSL, and am focusing on creating a working runtime. One that can execute the metadata in a way that the user gets a dynamically created UI (in WPF) that is bound to a dynamically created CSLA .NET business object, that leverages a dynamically created data access layer (using the CSLA .NET 3.6 ObjectFactory concept). I’m not dynamically creating the database, because I think that’s unrealistic in any real-world scenario. We all have pre-existing databases after all.

Once I get the runtime working (and it is close – here’s a screenshot of a simple object, showing how the dynamic WPF UI is running against an object with business rules, buttons bound to the CslaDataProvider through commanding and all the other nice CSLA features.


Not that my UI is a work of art, but still :)

I have a lot more to do, but it is now clear that starting with the runtime makes a lot more sense than starting with the DSL.

Friday, April 10, 2009 9:30:07 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]  | 
     Thursday, March 26, 2009

    Andrew Hallmark, a passionate user of CSLA .NET from the UK, gave a user group presentation introducing CSLA .NET and the presentation was recorded.

    The presentation is available for download from

    Thank you for sharing your content Andrew!

    Thursday, March 26, 2009 10:01:34 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]  | 
     Thursday, March 12, 2009

    When CSLA .NET 3.6.2 is released in a couple weeks, it will be sporting a slightly altered license and copyright notices, with the name Marimer, LLC.

    Marimer, LLC is my shiny new corporate entity, and it is now the owner of all versions of the CSLA .NET framework.

    This doesn’t change the terms of the license, nor should it have any effect on CSLA .NET or anyone’s use of CSLA .NET. It is simply a formal step I felt was necessary to protect myself and my family for legal liability reasons. Honestly, it is something I probably should have done years ago, but it is done now, so I can sleep better at night.

    At the moment I don’t plan to change anything beyond the copyright and ownership statements, and since I have sole control over Marimer, LLC, nothing changes in relation to the continued development of the CSLA .NET framework.

    Thursday, March 12, 2009 5:00:35 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
    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)
    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

    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, December 17, 2008



    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, December 03, 2008

    One of the topic areas I get asked about frequently is authorization. Specifically role-based authorization as supported by .NET, and how to make that work in the "real world".

    I get asked about this because CSLA .NET (for Windows and Silverlight) follow the standard role-based .NET model. In fact, CSLA .NET rests directly on the existing .NET infrastructure.

    So what's the problem? Why doesn't the role-based model work in the real world?

    First off, it is important to realize that it does work for some scenarios. It isn't bad for course-grained models where users are authorized at the page or form level. ASP.NET directly uses this model for its authorization, and many people are happy with that.

    But it doesn't match the requirements of a lot of organizations in my experience. Many organizations have a slightly more complex structure that provides better administrative control and manageability.


    Whether a user can get to a page/form, or can view a property or edit a property is often controlled by a permission, not a role. In other words, users are in roles, and a role is essentially a permission set: a list of permissions the role has (or doesn't have).

    This doesn't map real well into the .NET IPrincipal interface, which only exposes an IsInRole() method. Finding out if the user is in a role isn't particularly useful, because the application really needs to call some sort of HasPermission() method.

    In my view the answer is relatively simple.

    The first step is understanding that there are two concerns here: the administrative issues, and the runtime issues.

    At administration time the concepts of "user", "role" and "permission" are all important. Admins will associate permissions with roles, and roles with users. This gives them the kind of control and manageability they require.

    At runtime, when the user is actually using the application, the roles are entirely meaningless. However, if you consider that IsInRole() can be thought of as "HasPermission()", then there's a solution. When you load the .NET principal with a list of "roles", you really load it with a list of permissions. So when your application asks "IsInRole()", it does it like this:

    bool result = currentPrincipal.IsInRole(requiredPermission);

    Notice that I am "misusing" the IsInRole() method by passing in the name of a permission, not the name of a role. But that's ok, assuming that I've loaded my principal object with a list of permissions instead of a list of roles. Remember, the IsInRole() method typically does nothing more than determine whether the string parameter value is in a list of known values. It doesn't really matter if that list of values are "roles" or "permissions".

    And since, at runtime, no one cares about roles at all, there's no sense loading them into memory. This means the list of "roles" can instead be a list of "permissions".

    The great thing is that many people store their users, roles and permissions in some sort of relational store (like SQL Server). In that case it is a simple JOIN statement to retrieve all permissions for a user, merging all the user's roles together to get that list, and not returning the actual role values at all (because they are only useful at admin time).

    Wednesday, December 03, 2008 11:19:01 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
     Wednesday, November 19, 2008

    As the Expert C# 2008 Business Objects book becomes available (now in alpha ebook form, and in paper by the end of this year), I'm getting more questions about what book to buy for different versions of CSLA .NET, and for different .NET technologies.

    (Expert VB 2008 Business Objects should be out in February 2009. The one unknown with this effort is how quickly the team of volunteers can get the VB port of CSLA .NET 3.6 complete, as I don't think we can release the book until the code is also available for download.)

    I do have a summary of book editions that is often helpful in understanding what book(s) cover which version of CSLA .NET. But I thought I'd slice and dice the information a little differently to help answer some of the current questions.

    First, by version of CSLA .NET:

    CSLA .NET Version Book(s)
    3.6 Expert 2008 Business Objects
    3.5 <no book>
    3.0 Expert 2005 Business Objects &
    CSLA .NET Version 2.1 Handbook &
    Using CSLA .NET 3.0
    2.1 Expert 2005 Business Objects &
    CSLA .NET Version 2.1 Handbook
    2.0 Expert 2005 Business Objects


    Next, by .NET technology:

    .NET Technology Book(s)
    WPF Expert 2008 Business Objects
    WCF Expert 2008 Business Objects
    Silverlight <no book yet>
    Expert 2008 Business Objects gets you 80% there though
    WF Expert 2008 Business Objects &
    Using CSLA .NET 3.0 (for WF example)
    ASP.NET MVC <no book yet>
    ASP.NET Web Forms Expert 2008 Business Objects
    Windows Forms Expert 2008 Business Objects &
    Using CSLA .NET 3.0 (for important data binding info)
    LINQ to CSLA Expert 2008 Business Objects
    LINQ to SQL Expert 2008 Business Objects
    ADO.NET Entity Framework Expert 2008 Business Objects (limited coverage)
    .NET Remoting Expert 2005 Business Objects
    asmx Web Services Expert 2005 Business Objects


    As always, here are the locations to download CSLA .NET for Windows and to download CSLA .NET for Silverlight.

    Wednesday, November 19, 2008 9:17:58 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
     Wednesday, November 12, 2008

    Expert C# 2008 Business Objects book coverYou can now purchase the "alpha" of Expert C# 2008 Business Objects online as an ebook directly from the Apress web site. This gets you early access to the content, and access to the final ebook content when it is complete.

    While their website indicates you can provide feedback during the writing process, the reality with this book is that I'm only three chapters from being completely done with the final review, so it is terribly close to being final already :)

    Wednesday, November 12, 2008 8:12:05 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]  | 
     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]  | 
     Wednesday, October 22, 2008

    Dunn Training is offering a CSLA .NET Master Class in November, located in Atlanta.

    This is a full 5 day class covering CSLA .NET, and related technologies such as WPF, WCF, Web Forms and much more! Not only will this provide intensive coverage of CSLA .NET 3.6 (the latest version), but you'll learn an amazing amount about the application of important .NET technologies in the context of real-world business application development.

    There is still time to register for this class, and you'll have a hard time finding training of this depth and breadth elsewhere!

    Wednesday, October 22, 2008 11:44:16 AM (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, 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]  | 
     Monday, September 29, 2008

    Dunn Training is offering a CSLA .NET Master Class in November, located in Atlanta.

    This is a full 5 day class covering CSLA .NET, and related technologies such as WPF, WCF, Web Forms and much more! Not only will this provide intensive coverage of CSLA .NET, but you'll learn an amazing amount about the application of important .NET technologies in the context of real-world business application development.

    Monday, September 29, 2008 7:38:54 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.


    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.


    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.


    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, 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]  | 
     Thursday, September 11, 2008

    A few weeks ago I posted what was basically a request for input on one aspect of the future of CSLA .NET. I got a lot of really thoughtful and useful feedback and input from that post (and a related thread in the forum). I've also been discussing this with Apress and other colleagues, and I've come to a decision.

    Starting with version 3.6, CSLA .NET for Windows and CSLA .NET for Silverlight will be maintained in C# only. This will allow me to focus more of my energies on improving the framework, and on providing resources and materials on how to use the framework (in both C# and VB).

    In the short term this means continuing to finalize version 3.6 and to finish Expert C# 2008 Business Objects (current availability target is December).

    However, I am willing to take some people up on their offer to help maintain the VB version of the framework, if those offers still stand. The idea would be to have the community keep the VB code base in sync with the C# code base as it evolves - at least for CSLA .NET for Windows.

    And here's a possible incentive. If the VB code can be brought up to sync by mid-December or so, I will work with Apress to create Expert VB 2008 Business Objects following the C# edition of the book. I really can't do that book in VB unless the framework exists in VB, but if that can happen then I'm pretty sure we can make the book happen shortly thereafter.

    Contributors will need to sign a contributor agreement, to keep everything clear and legal. And they'll use the current subversion repository and issue tracking database, so I think it should be a pretty smooth arrangement. And obviously contributors will have the undying gratitude of the community :)

    If you are interested in making this happen, please email me - rocky (at) lhotka dot net - and we'll go from there.

    I think this should be a good overall solution, hopefully making everyone happy in both the short and long term.

    Thursday, September 11, 2008 3:56:23 PM (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 27, 2008

    The second part of the DNR TV show covering CSLA .NET 3.5.1 is now online. Here are links to both parts:

    As always, you can download CSLA .NET from here.

    Wednesday, August 27, 2008 7:03:12 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
     Wednesday, August 20, 2008

    I've been thinking a lot about the future of CSLA and of .NET, and I'd like thoughtful input.

    The .NET platform is, for lack of a better word, fragmenting. We have .NET, the .NET client-only framework, .NET Compact Framework, Silverlight and probably others. All of these are ".NET", but they are all different.

    CSLA will soon support .NET and Silverlight. It sort of supports the Client-Only Framework now, but it was just pointed out to me that while it works, there are compiler warnings in this scenario.

    For the past 6 or so years, I've been maintaining all my code twice, once in VB and once in C#. This has never been fun, and wouldn't have been possible at all without help from my colleague Brant Estes and from the Instant VB and Instant C# tools. Even with this, the reality is that I have to do everything twice, and test everything twice.

    (yes, I have a unified set of unit tests, but there's a ton of manual testing around data binding in Web Forms, Windows Forms, WPF and now Silverlight that can't be automated)

    But now I'm faced with a truly horrific future scenario. CSLA .NET, CSLA Light, possibly CSLA CF and CSLA Client-Only. Four versions of the framework. Two languages for each version. Fixing a single bug requiring changing and testing 8 implementations.

    Clearly that's not realistic. Not only would it eliminate any fun, but it just isn't practical. I doubt it would be practical even if I made CSLA a commercial product...

    Of course I can cut the complexity in half by maintaining the framework in only one programming language.

    This is a touchy thing of course. I was thinking Modula II, but I can't find a good compiler for .NET... :)

    Seriously though, the clear choice would be to maintain the framework in C#, at which point I run the risk of alienating the VB community. You might argue I should maintain the framework in VB, but (for better or worse) that would almost certainly alienate a much bigger constituency.

    The really important thing is that the framework would support both VB and C#. Regardless of what I do or don't do inside the framework, it can be used by either language (and other languages for that matter) equally well. After all, most of the .NET framework is written in just one language, yet it is used by everyone equally.

    Right now CSLA Light is only in C#, though I'm testing in both VB and C# to make sure it supports both equally. I haven't tried, but I imagine you can use it from Ruby or Python too, since both of those languages work in Silverlight too.

    Another alternative would be to solicit help from the community. For example, perhaps one or more people would be willing to help keep the VB version of the framework in sync over time. That has its own complications, but might be a worthy solution.

    This also ties into my book projects. I'm working on Chapter 16 of 21 for Expert C# 2008 Business Objects right now. As with the previous editions, most of the book is focused on the design and creation of the framework itself, with less focus on how to use the framework.

    I think a lot of people would actually prefer a book on how to use the framework, not caring so much how and why I implemented things internally. And I'd enjoy writing that book (in VB and C# editions). But as it is, I'm looking at 2-3 months of work to get CSLA .NET 3.6 working in VB (which will have to wait until the current book is done), then a couple months to get the Expert VB 2008 Business Objects book done. That's 4-5 months where I could write a book on how to use the framework. Or perhaps a series of highly focused ebooks. Or something along that line.

    I haven't reached a decision, I'm just thinking long and hard. Thoughtful input is welcome, thanks!

    Wednesday, August 20, 2008 3:15:50 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 
     Friday, August 15, 2008

    One of the features we added in CSLA Light was the idea of a "factory" or "observer" object - kind of like a police sobriety checkpoint - that can be called when any data portal request comes in from the client. This is a server-side object that can examine or manipulate the business object or criteria object sent from the client, before any other server-side processing is allowed.

    I liked the idea so much that I decided to put it into the CSLA .NET 3.6 data portal too. Which turned out to be much harder than I expected...

    Of course I don't want to break compatibility with the current data portal behavior, so it must continue unchanged.

    But if you put the ObjectFactory attribute on your business class, that should redirect the data portal to create an instance of the factory object you specify, and to route all data portal calls to methods on that object instead of calling DataPortal_XYZ as normal.

    For example:

    public class CustomerEdit : BusinessBase<CustomerEdit>

    This tells the data portal to not call any DataPortal_XYZ methods, but instead to create an instance of a MyFactory object and to call methods named Create(), Fetch(), Update() and Delete() on that object instead.

    This is extensible in numerous ways. You can specify the names of the four methods. You can provide a "factory loader" so that string parameter passed to ObjectFactory can be interpreted differently - how ever you'd like. The default factory loader treats that string like an assembly qualified type name, because I think that's what most people will want.

    So you have to create MyFactory:

    namespace Factories
      public class MyFactory
        public object Create()
          // create object here
          return obj;

        public object Fetch(SingleCriteria<CustomerEdit, int> criteria)
          // retrieve object here
          return obj;

        public object Update(CustomerEdit obj)
          // insert/update/delete object here

        public void Delete(SingleCriteria<CustomerEdit, int> criteria)
          // delete data here

    Normal method overloading rules apply to these methods. So you can have multiple Fetch() methods with different criteria object types and the data portal will call the right method. This is exactly the same behavior as with DataPortal_Create(), DataPortal_Fetch() and DataPortal_Delete() today.

    Notice that the RunLocal and Transactional attributes can be applied to these methods just like they would have been applied to the DataPortal_XYZ methods.

    RunLocal is interesting though, because it obviously can only work if you deploy your factory assembly to the client along with the business assembly. In most cases I expect people won't choose to do that, and so won't be able to use RunLocal.

    The default for Transactional is to use Manual transactions. In other words, if you don't use the attribute it is entirely up to your factory method to handle any transaction details.

    It is very important to realize that when using this factory model, the data portal does virtually nothing for you. It doesn't automatically call MarkOld(), MarkNew() or MarkAsChild(). You assume total responsibility for creating and initializing the business object graph, and for setting the state of all objects in the graph.

    Friday, August 15, 2008 2:16:41 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:

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

    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}"
                 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:


    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:

                <behavior name="WcfPortalBehavior">
                    <serviceMetadata httpGetEnabled="true"/>
                    <serviceDebug includeExceptionDetailInFaults="true"/>
            <service behaviorConfiguration="WcfPortalBehavior"
                <endpoint address=""
                        <dns value="localhost"/>

    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:

                    <binding name="BasicHttpBinding_IWcfPortal"
                                  receiveTimeout="10" sendTimeout="10">
                    name="BasicHttpBinding_IWcfPortal" />

    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.


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


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

    <UserControl x:Class="SimpleApp.Page"
        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 Orientation="Horizontal" Margin="5,5,5,5">
            <TextBlock Width="100" Text="Name" />
            <TextBox Width="150" Text="{Binding Name, Mode=TwoWay}" />
          <StackPanel Orientation="Horizontal" Margin="5,5,5,5">
            <TextBlock Width="100" Text="Status" />
            <TextBlock Width="150" Text="{Binding Status}" />
          <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" />

    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.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.


    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

    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 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]  | 

    CSLA .NET version 3.5.1 has been released and is now available at

    This is a bug-fix release, and includes a number of very important bug fixes in the following areas:

    • Windows Forms data binding
    • LINQ to CSLA
    • SmartDate type conversion

    Please see the change log for a full list of changes and fixes.

    If you are using version 3.5.0, I strongly recommend upgrading to 3.5.1.

    Sunday, August 03, 2008 9:49:43 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:


    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:


    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
        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
        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
        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
      ' .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
    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)
    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.


    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:


    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]  | 
     Sunday, July 27, 2008

    I have put CSLA .NET 3.5.1 release candidate 0 online at

    Version 3.5.1 has some very important bug fixes for 3.5, especially around some of the new property syntax and Windows Forms data binding.

    If you are using any of the new 3.5 property syntax, or are using Windows Forms data binding, you really should test 3.5.1 ASAP!

    There's only one breaking change in how a "new PropertyInfo(...)" expression is written - I had to remove a constructor. This is unfortunate, but necessary, because the overload was ambiguous with another overload when the property type was string. The compiler will find these for you, and they are easily resolved - just check the change log for info.

    Beta 2 was quite stable - no bug reports, only one feature change for data binding - so I expect RC0 to be very good. Please let me know if you encounter issues.

    Sunday, July 27, 2008 4:05:08 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

    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]  | 

    I get a lot of questions about Expert 2008 Business Objects as to what it will and won't cover, so I thought I'd try and answer at least some of them in a blog post.

    The book will cover CSLA .NET 3.6. Version 3.6 is the same as 3.5, but with support for CSLA Light and some .NET 3.5 SP1 features (such as the Entity Framework). And along with CSLA Light comes some interesting support for things like an async data portal and async validation rules. But please note that this book will not cover CSLA Light - that's a book by itself, believe me!

    Here's the tentative table of contents for the book:

    1.     Architecture

    2.     Design

    3.     Object-oriented design

    4.     Supported stereotypes

    5.     Stereotype templates

    6.     Framework Implementation

    7.     Editable Objects and Collections

    8.     Data Binding

    9.     Business and Validation Rules

    10.   Authorization Rules

    11.   N-level Undo

    12.   LINQ to CSLA

    13.   Persistence and the Data Portal

    14.   Other Framework Features

    15.   Example Business Library

    16.   WPF Application

    17.   Web Forms Application

    18.   WCF Service Application

    The items in green are complete - first draft anyway - and so you can get an idea where I am in the process.

    Due to space and time constraints, this book will have three UI chapters just like the previous books. So I had to choose which interface technologies to cover - out of the myriad options available:

    • WPF
    • WPF/XBAP
    • Windows Forms
    • asmx services
    • WCF services
    • WF workflows and activities
    • ASP.NET Web Forms
    • Office/VSTO (Word, Excel, etc)
    • Console

    I want to make sure to cover smart clients, web development and services. While WCF and Web Forms were easy choices (though I do like ASP.NET MVC a lot, it isn't mainstream yet), the choice between Windows Forms and WPF was difficult. But I have to give WPF the nod, because it is a really nice technology, and it really shows off the power of CSLA .NET business objects very nicely.

    My current plan is to release ebooks that specifically focus on each of the interface technologies not covered in Expert 2008 Business Objects, and some sort of book (ebook or traditional) covering CSLA Light.

    Tuesday, July 15, 2008 9:17:28 AM (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.


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


    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:// and svn:// 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);

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

    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
      public class CustomerEdit : BusinessBase<CustomerEdit>
        protected override void OnGetState(SerializationInfo info)
          info.AddValue("MyApp.CustomerEdit._id", _id);
          info.AddValue("MyApp.CustomerEdit._name", _name);

        protected override void OnSetState(SerializationInfo 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
      public class CustomerEdit : BusinessBase<CustomerEdit>
        protected override void OnGetState(SerializationInfo info, StateModes mode)
          if (mode == StateModes.Serialization)
            info.AddValue("MyApp.CustomerEdit._id", _id);
          info.AddValue("MyApp.CustomerEdit._name", _name);

        protected override void OnSetState(SerializationInfo info, StateModes mode)
          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]  | 
     Thursday, June 12, 2008

    The MobileFormatter serializer being created for CSLA Light serializes objects that implement IMobileObject. CSLA Light and CSLA .NET classes will implement this interface so the business developer doesn't normally need to worry about it.

    (the exception being when a business object uses private backing fields, in which case the business object developer will need to override OnGetState() and OnSetState() to get/set the private fields they've declared)

    To organize the implementation, we are planning to introduce two new base classes to CSLA: MobileObject and MobileList<T>. The following diagram shows how the new inheritance hierarchy will work:


    Note that Silverlight doesn't have a BindingList<T> type, and so CSLA Light will supply that type. CSLA .NET already uses BindingList<T> extensively, and so this will provide parity on both sides of the data portal.

    In other words, this will be the inheritance hierarchy for both CSLA .NET and CSLA Light.

    It is also the case that FieldDataManager, the object that manages all the managed backing field values in CSLA 3.5, must serialize itself as well. And so will the BrokenRulesCollection.


    The overall hierarchy remains as it is in CSLA .NET, we're just inserting MobileObject and MobileList at the top of the hierarchy (or as high as possible in the case of .NET).

    This will allow the MobileFormatter to interact with any CSLA-derived business class, automatically serializing all managed backing fields and the child objects contained in the FieldManager of a business object, or the inner list of any MobileList (BindingList<T>).

    Thursday, June 12, 2008 2:28:48 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

    I've been engaged in a discussion around CSLA .NET on an MSDN architecture forum - you can see the thread here. I put quite a bit of time/effort into one of my replies, and I wanted to repost it here for broader distribution:

    I don’t think it is really fair to relate CSLA .NET to CSLA Classic. I totally rewrote the framework for .NET (at least 4 times actually – trying different approaches/concepts), and the only way in which CSLA .NET relates to CSLA Classic is through some of the high level architectural goals around the use of mobile objects and the minimization of UI code.

    The use of LSet in VB5/6, btw, was the closest approximation to the concept of a union struct from C or Pascal or a common block from FORTRAN possible in VB. LSet actually did a memcopy operation, and so wasn’t as good as a union struct, but was radically faster than any other serialization option available in VB at the time. So while it was far from ideal, it was the best option available back then.

    Obviously .NET provides superior options for serialization through the BinaryFormatter and NetDataContractSerializer, and CSLA .NET makes use of them. To be fair though, a union struct would still be radically faster Smile

    Before I go any further, it is very important to understand the distinction between ‘layers’ and ‘tiers’. Clarity of wording is important when having this kind of discussion. I discuss the difference in Chapter 1 of my Expert 2005 Business Objects book, and in several blog posts – perhaps this one is best:

    The key thing is that a layer is a logical separation of concerns, and a tier directly implies a process or network boundary. Layers are a design constraint, tiers are a deployment artifact.

    How you layer your code is up to you. Many people, including myself, often use assemblies to separate layers. But that is really just a crutch – a reminder to have discipline. Any clear separation is sufficient. But you are absolutely correct, in that a great many developers have trouble maintaining that discipline without the clear separation provided by having different code in different projects (assemblies).


    CSLA doesn’t group all layers into a single assembly. Your business objects belong in one layer – often one assembly – and so all your business logic (validation, calculation, data manipulation, authorization, etc) are in that assembly.

    Also, because CSLA encourages the use of object-oriented design and programming, encapsulation is important. And other OO concepts like data hiding are encouraged. This means that the object must manage its own fields. Any DAL will be working with data from the object’s fields. So the trick is to get the data into and out of the private fields of the business object without breaking encapsulation. I discussed the various options around this issue in my previous post.

    Ultimately the solution in most cases is for the DAL to provide and consume the data through some clearly defined interface (ADO.NET objects or DTOs) so the business object can manage its own fields, and can invoke the DAL to handle the persistence of the data.

    To be very clear then, CSLA enables separation of the business logic into one assembly and the data access code into a separate assembly.

    However, it doesn’t force you to do this, and many people find it simpler to put the DAL code directly into the DataPortal_XYZ methods of their business classes. That’s fine – there’s still logical separation of concerns and logical layering – it just isn’t as explicit as putting that code in a separate assembly. Some people have the discipline to make that work, and if they do have that discipline then there’s nothing wrong with the approach imo.


    I have no problem writing business rules in code. I realize that some applications have rules that vary so rapidly or widely that the only real solution is to use a metadata-driven rules engine, and in that case CSLA isn’t a great match.

    But let’s face it, most applications don’t change that fast. Most applications consist of business logic written in C#/VB/Java/etc. CSLA simply helps formalize what most people already do, by providing a standardized approach for implementing business and validation rules such that they are invoked efficiently and automatically as needed.

    Also consider that CSLA’s approach separates the concept of a business rule from the object itself. You then link properties on an object to the rules that apply to that object. This linkage can be dynamic – metadata-driven. Though the rules themselves are written as code, you can use a table-driven scheme to link rules to properties, allowing for SaaS scenarios, etc.


    This is an inaccurate assumption. CSLA .NET requires a strong separation between the UI and business layers, and allows for a very clear separation between the business and data access layers, and you can obviously achieve separation between the data access and data storage layers.

    This means that you can easily have UI specialists that know little or nothing about OO design or other business layer concepts. In fact, when using WPF it is possible for the UI to only have UI-specific code – the separation is cleaner than is possible with Windows Forms or Web Forms thanks to the improvements in data binding.

    Also, when using ASP.NET MVC (in its present form at least), the separation is extremely clear. Because the CSLA-based business objects implement all business logic, the view and controller are both very trivial to create and maintain. A controller method is typically just the couple lines of code necessary to call the object’s factory and connect it to the view, or to call the MVC helper to copy data from the postback into the object and to have the object save itself. I’m really impressed with the MVC framework when used in conjunction with CSLA .NET.

    And it means that you can have data access specialists that only focus on ADO.NET, LINQ to SQL, EF, nHibernate or whatever. In my experience this is quite rare – very few developers are willing to be pigeonholed into such a singularly uninteresting aspect of software – but perhaps your experiences have been different.

    Obviously it is always possible to have database experts who design and implement physical and logical database designs.


    I entirely agree that the DTO design pattern is incredibly valuable when building services. But no one pattern is a silver bullet and all patterns have both positive and negative consequences. It is the responsibility of professional software architects, designers and developers to use the appropriate patterns at the appropriate times to achieve the best end results.

    CSLA .NET enables, but does not require, the concept of mobile objects. This concept is incredibly powerful, and is in use by a great many developers. Anyone passing disconnection ADO recordsets, or DataSets or hashtables/dictionaries/lists across the network uses a form of mobile objects. CSLA simply wraps a pre-existing feature of .NET and makes it easier for you to pass your own rich objects across the network.

    Obviously only the object’s field values travel across the network. This means that a business object consumes no more network bandwidth than a DTO. But mobile objects provide a higher level of transparency in that the developer can work with essentially the same object model, and the same behaviors, on either side of the network.

    Is this appropriate for all scenarios? No. Decisions about whether the pattern is appropriate for any scenario or application should be based on serious consideration of the positive and negative consequences of the pattern. Like any pattern, mobile objects has both types of consequence.

    If you look at my blog over the past few years, I’ve frequently discussed the pros and cons of using a pure service-oriented approach vs an n-tier approach. Typically my n-tier arguments pre-suppose the use of mobile objects, and there are some discussions explicitly covering mobile objects.

    The DTO pattern is a part of any service-oriented approach, virtually by definition. Though it is quite possible to manipulate your XML messages directly, most people find that unproductive and prefer to use a DTO as an intermediary – which makes sense for productivity even if it isn’t necessarily ideal for performance or control.

    The DTO pattern can be used for n-tier approaches as well, but it is entirely optional. And when compared to other n-tier techniques involving things like the DataSet or mobile objects the DTO pattern’s weaknesses become much more noticeable.

    The mobile object pattern is not useful for any true service-oriented scenario (note that I’m not talking about web services here, but rather true message-based SOA). This is because your business objects are your internal implementation and should never be directly exposed as part of your external contract. That sort of coupling between your external interface contract and your internal implementation is always bad – and is obviously inappropriate when using DTOs as well. DTOs can comprise part of your external contract, but should never be part of your internal implementation.

    The mobile object pattern is very useful for n-tier scenarios because it enables some very powerful application models. Most notably, the way it is done in CSLA, it allows the application to switch between a 1-, 2- and 3-tier physical deployment merely by changing a configuration file. The UI, business and data developers do not need to change any code or worry about the details – assuming they’ve followed the rules for building proper CSLA-based business objects.

    Thursday, June 12, 2008 8:58:29 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

    Dunn Training is working with some people in Ireland to put together a CSLA .NET training class. If you are in Ireland, the UK or perhaps Europe, you may be interested. This CSLA forum post has some more information.

    Thursday, June 12, 2008 8:14:43 AM (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:


    The XML byte stream can lat