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 [0]  | 

 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:

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

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

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

 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 http://store.lhotka.net. 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, http://www.lhotka.net/cslanet/Roadmap.aspx 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:

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

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

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

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

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

 Thursday, July 08, 2010

CSLA 4 release candidate 0 is now available for download from http://www.lhotka.net/cslanet/download.aspx

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
{
  get
  {
    if (!FieldManager.FieldExists(ChildProperty))
    {
      Child = DataPortal.Fetch<ChildLoader>().Child;
      OnPropertyChanged(ChildProperty);
    }
    return GetProperty(ChildProperty);
  }
  private set { LoadProperty(ChildrenProperty, value); }
}

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

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

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

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

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

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

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

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

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

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

 Tuesday, June 29, 2010

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

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

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

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

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

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

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

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

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

And yet the state was being set to Valid.

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

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

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

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

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

Tuesday, June 29, 2010 2:58:25 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [3]  | 

 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.

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

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

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

 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:

http://download.lhotka.net/SLVid01Index.htm

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 http://store.lhotka.net.

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 http://download.lhotka.net 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.

Thoughts?

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;
          break;
        }
    }
    else
    {
      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(
    AuthorizationActions.WriteProperty,
    NameProperty,
    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:

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

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

BasicVM

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

Collective

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

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

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

LiveDemo

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

UsingBxf

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

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

VSL01

Demo showing some concepts and implementation around MVVM.

VSL02

Demo showing some concepts and implementation around MVVM.

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

 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()
  • ASP.NET MVC
    • 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)
      _innerRule.Execute(context.GetChainedContext(required));
  }
}

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)
  { 
    _innerRule.Execute(context.GetChainedContext(required));
  }
}

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 http://www.lhotka.net/cslanet/download.aspx.

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;
  }
  else
    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()
{
  base.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()
{
  base.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()
{
  base.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()
{
  base.AddBusinessRules();

  // add rules to default rule set
  BusinessRules.AddRule(...);
  BusinessRules.AddRule(...);
  BusinessRules.AddRule(...);

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

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

  // 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()
{
  base.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)
        context.AddErrorResult(e.Error.Message);
      context.Complete();
    };
    bw.RunWorkerAsync();
  }
}

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.

Summary

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://svn.lhotka.net/csla/mcsla/tags/Video1001.

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.

image

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

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

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

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

Whew!

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

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

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

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

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

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

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

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

 Tuesday, February 16, 2010

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

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

image

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

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

CollectionViewSource Indirection

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

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

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

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

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

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

Executing ViewModel Verbs

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

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

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

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

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

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

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

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

 Monday, February 01, 2010

CSLA .NET 3.8.2 is now available for Windows and Silverlight

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

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

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

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

 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!

A.J.

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.

http://download.lhotka.net/Default.aspx?t=Core38

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 http://store.lhotka.net – 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 http://store.lhotka.net) 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.

http://www.dnrtv.com/default.aspx?showNum=161

 

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

 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 www.nunit.org 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 [2]  | 

 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:

Introduction
In this video you will become familiar with the CSLA .NET framework's vision, goals and overall scope. You will be introduced to the various architectures supported by CSLA .NET, 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 [2]  | 

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 [3]  | 

 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 [2]  | 

 Wednesday, November 04, 2009

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

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

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

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

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

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

The answers are pretty clear:

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

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

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

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

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

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

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

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

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

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

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

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

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

 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 [3]  | 

 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 [5]  | 

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

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

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

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

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

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

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

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

What does this look like?

CSLA .NET MVVM Support

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

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

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

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

View Event Handling

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

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

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

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

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

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

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

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

public void SaveData()
{
}

Or this:

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

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

Creating a ViewModel

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

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

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

DoRefresh

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

BeginRefresh

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

DoSave

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

BeginSave

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

AddItem

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

Remove

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

Delete

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

Cancel

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

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

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

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

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

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

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

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

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

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

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

Creating the Model

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

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

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

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

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

 Tuesday, October 20, 2009

Dunn Training is offering their CSLA Master Class next month in Atlanta

http://www.dunntraining.com/training/cslamasterclass.htm

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 [4]  | 

 Monday, October 05, 2009

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

 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 [6]  | 

 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 [3]  | 

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 [2]  | 

 Wednesday, September 02, 2009

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

But I keep fighting with UI stuff in the process…

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

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

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

Single-select with InvokeMethod

With InvokeMethod it looks like this:

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

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

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

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

Single-select with event trigger

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

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

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

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

And the ViewModel method looks like this:

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

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

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

Multi-select with InvokeMethod

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

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

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

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

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

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

And the Button looks like this:

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

And the ViewModel method looks like this:

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

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

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

Multi-select with event trigger

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

 Friday, August 14, 2009

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

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

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

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

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

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

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

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

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

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

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

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

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

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

 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 http://www.lhotka.net/cslanet/N2.aspx.

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.TriggerEvent="Click"
        csla:InvokeMethod.MethodName="Load" />

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

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

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

ListBox doubleclick scenario

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

public void ProcessItem(Data item)
{
}

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

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

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

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

MultiSelect ListBox scenario

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

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

The ViewModel has a method to handle this:

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

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

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

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

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

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

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

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

 Friday, July 31, 2009

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

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

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

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

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

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

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

public class PropertyStatus : ContentControl
{

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

image

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

ViewModel as Sole Data Source

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

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

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

image

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

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

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

ViewModel as Action Repository

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

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

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

image

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

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

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

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

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

Routing XAML Events to a ViewModel

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

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

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

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

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

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

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

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

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

Why this isn’t Ideal

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

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

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

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

Then the ShowItem() code could be like this:

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

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

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

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

Or maybe more elegant would be a different property:

csla:InvokeMethod.ElementParameter=”SelectedItem”

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

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

 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.

f01

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 [2]  | 

 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 [1]  | 

 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 [2]  | 

 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 [2]  | 

 Monday, May 18, 2009
Monday, May 18, 2009 6:00:00 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [3]  | 

 Monday, May 04, 2009

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

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

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

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

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

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

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

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

 Friday, April 17, 2009

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

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

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

Here is a summary of all seven video segments:

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

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

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

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

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

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

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

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

 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.

image

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.

image

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 [4]  | 

 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

    http://www.vbug.com/members/pastevents.aspx

    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 [4]  | 

     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 [1]  | 

     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 [4]  | 

     Thursday, February 19, 2009

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

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

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

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

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

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

     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

    csla_logo1_42

    csla-lt_logo_42

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

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

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

    Here are some highlights:

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

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

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

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

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

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

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

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

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

     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 [1]  | 

     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.

    image

    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 [11]  | 

     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 [5]  | 

     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 [8]  | 

     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 [3]  | 

     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 [2]  | 

    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 www.apress.com, as they tell me that they'll be offering an "alpha release" program where you can pre-purchase the book and get early access to chapters in PDF form, and get the paper book when it comes out.

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

    Code well, have fun!

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

     Thursday, October 02, 2008

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

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

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

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

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

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

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

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

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

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

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

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

     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.

    image

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

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

    CSLA .NET Core Features

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

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

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

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

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

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

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

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

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

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

    CSLA .NET for Windows

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

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

    In WPF the following controls are provided:

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

    In Web Forms the following controls are provided:

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

    In Windows Forms the following controls are provided:

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

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

    For WCF and asmx services the following component is provided:

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

    For WCF services, there is another component:

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

    For Windows Workflow the following component is provided:

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

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

    CSLA .NET for Silverlight

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

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

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

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

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

    CSLA .NET Deployment Models and Mobile Objects

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

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

    image image image

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

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

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

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

     image

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

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

    Standardized Data Access

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

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

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

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

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

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

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

    Summary

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

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

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

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

    The new Silverlight version requires Silverlight 2.0 RC0.

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

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

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

     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 [7]  | 

     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 [1]  | 

     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 [44]  | 

     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:

    [ObjectFactory("Factories.MyFactory,Factories")]
    [Serializable]
    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
      {
        [RunLocal]
        public object Create()
        {
          // create object here
          return obj;
        }

        public object Fetch(SingleCriteria<CustomerEdit, int> criteria)
        {
          // retrieve object here
          return obj;
        }

        [Transactional(TransactionTypes.TransactionScope)]
        public object Update(CustomerEdit obj)
        {
          // insert/update/delete object here
        }

        [Transactional(TransactionTypes.TransactionScope)]
        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:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

     Tuesday, August 12, 2008

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

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

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

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

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

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

    Configuring the Server

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

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

    image

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

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

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

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

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

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

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

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

    Configuring the Client

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

    The config file looks like this:

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

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

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

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

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

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

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

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

    Csla.DataPortal.ProxyTypeName = "Local"

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

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

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

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

     Monday, August 11, 2008

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

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

    image

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

    UI XAML

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

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

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

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

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

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

    Creating or Retrieving the Object

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

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

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

    End Sub

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

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

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

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

      Me.LayoutRoot.DataContext = e.Object

    End Sub

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

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

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

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

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

    Saving the Object

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

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

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

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

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

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

    End Sub

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

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

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

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

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

      Me.LayoutRoot.DataContext = e.NewObject

    End Sub

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

    Deleting the Object

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

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

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

    End Sub

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

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

    Summary

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

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

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

     Sunday, August 03, 2008

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

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

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

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

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

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

    CSLA .NET version 3.5.1 has been released and is now available at www.lhotka.net/cslanet/download.aspx.

    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:

    image

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

    Library.Server Setup

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

    image

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

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

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

    CustomerEdit Class Declaration

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

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

    Imports Csla
    Imports Csla.Serialization

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

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

    Property Declarations

    The property declarations are standard CSLA .NET 3.5 fare:

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

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

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

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

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

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

    Silverlight vs .NET Code

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

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

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

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

    Silverlight Factory Methods

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

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

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

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

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

    In both the create and fetch scenarios the steps are:

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

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

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

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

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

    Silverlight Constructor

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

    Public Sub New()
      ' required by MobileFormatter
    End Sub

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

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

    Dim cust As New CustomerEdit

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

    .NET Constructor

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

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

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

    .NET DataPortal_XYZ Methods

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

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

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

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

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

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

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

    Summary

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

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

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

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

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

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

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

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

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

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

    3-Tier or SOA Model

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

    1. Silverlight
    2. Service
    3. Database

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

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

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

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

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

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

    3-Tier Mobile Objects Model

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

    1. Silverlight
    2. Data portal server
    3. Database

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

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

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

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

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

    image

    Here's an explanation of the projects:

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

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

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

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

    4-Tier Mobile Objects Model

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

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

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

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

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

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

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

     Sunday, July 27, 2008

    I have put CSLA .NET 3.5.1 release candidate 0 online at www.lhotka.net/cslanet/download.aspx.

    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 [5]  | 

     Tuesday, July 15, 2008

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

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

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

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

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

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

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

    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
    • ASP.NET MVC
    • 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 [7]  | 

     Monday, July 14, 2008

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

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

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

    As in .NET, when using the data portal in local mode things are pretty simple. A call to the data portal to fetch an object simply results in a call to a DataPortal_Fetch() method in your object, and the object is running on the client in Silverlight. What you do in that DataPortal_Fetch() method is entirely up to you, as long as the object is populated with data by the time the call completes.

    When you use the remote data portal there are more options. Things are somewhat different from the existing .NET data portal. The following figure will help explain.

    image

    The CSLA Light data portal interacts with a server (probably a web server, though it could be a Windows Server 2008 running WAS) through WCF. That server is running CSLA .NET 3.6, which includes data portal support to listen for CSLA Light data portal requests. Objects are serialized to/from CSLA Light using the MobileFormatter, which is a serializer included in both CSLA Light and CSLA .NET that provides a subset of the functionality provided by the BinaryFormatter (or NetDataContractSerializer), targeted at the CSLA scenario.

    On the web server, CSLA .NET 3.6 receives the inbound client request. Any objects sent from the client to the server are deserialized (including any criteria objects or business objects). At this point there are two ways the process will work.

    The default option is that the call from the client is "echoed" into the standard CSLA .NET data portal. In other words, if the client calls Fetch() on the data portal, that call is relayed into the standard data portal as a Fetch() request. This means that the .NET data portal applies its normal process and runs in local or remote mode and ultimately creates an instance of your business object and calls its DataPortal_Fetch() method. Remember that this is all happening in .NET on the server(s). The resulting business object is then returned through the .NET data portal to the web server, and from there through the Silverlight data portal to the client.

    So by default, the .NET data portal running on the web server (in the diagram) is a pass-through from Silverlight into .NET. The end result is that the Silverlight data portal works just like the .NET data portal does today.

    While the default is good and easy, it may not always be ideal. You may not trust the code running in Silverlight on the client. You may be concerned that the code has been compromised, that somehow a malicious user cracked into the Silverlight runtime, mucked around with your code and bypassed your logic. Thus far no one has established that this can be done, but I can understand the concern.

    In that case, another option is that the business class (on the .NET side) can have a MobileFactory attribute attached:

    [MobileFactory("MyLibrary.CustomerFactory,MyLibrary", "Create", "Fetch", "Update", "Delete")]
    public class Customer : BusinessBase<Customer>

    If this attribute is applied, the .NET data portal will create an instance of the type specified in the attribute, and will call methods on that factory object instead of on the business object. In other words, a call that would have gone to DataPortal_Fetch() will now go to a method matching the third parameter of the attribute - in this example a method called Fetch().

    The factory object is responsible for creating, initializing and returning the object from create/fetch/update operations. Delete returns nothing. How the factory object does this is up to the factory author - you. I suspect a very common implementation will be for the factory method to do extra business checks (validation/authorization) to decide if the client call is valid, and if it is valid then the factory will just echo the call into the .NET data portal. So you might write something like this in a factory:

    public object Fetch(SingleCriteria<Customer, int> criteria)
    {
      // do extra validation/authorization checks here
      if (allChecksPassed)
        return DataPortal.Fetch(criteria);
      else
        throw new Exception("Bad client request");
    }

    A colleague of mine at Magenic, Nermin Dibek, suggested an interesting enhancement to this MobileFactory model, which I'll include in the implementation. As a configuration option, you can specify a "factory of factories" object. The default behavior is to take the type name in the first parameter and use it to create an instance of the factory object. But if you'd like, you can create your own "factory creator" object that takes that first parameter and uses it however you'd like to create an instance of the factory. This would allow you to substitute MyTestLibrary for MyLibrary when you wanted to use a set of test factories instead of the production versions, and that sort of thing.

    It is my intent to extend this MobileFactory concept into the .NET data portal itself (in CSLA .NET 3.6), so in a pure-.NET scenario you'd have comparable options, like this figure:

    image

    The data portal would default to its existing behavior, which would be unchanged. However, you'd be able to apply an ObjectFactory attribute to your business classes to indicate that the data portal should route its calls to your factory object rather than to the DataPortal_XYZ methods.

    The only catch here, is that your factory objects then assume responsibility for managing the status values (IsNew, IsDirty, etc) of the object (and its child objects, etc). The data portal essentially steps out of the picture entirely - leaving you to do all the work of creating and manipulating the business object as necessary. However, this does open up some interesting alternatives for persisting objects even though the solution is less automated than the current implementation.

    The CSLA Light part of what I've discussed here is in the current 3.6 code in Subversion (svn://svn.lhotka.net/csla/branches/cslacs36 and svn://svn.lhotka.net/csla/trunk/cslalightcs). The ObjectFactory support for CSLA .NET itself will probably happen in a few weeks.

    Monday, July 14, 2008 9:41:52 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [3]  | 

     Tuesday, June 24, 2008

    With serialization largely out of the way - or at least under control - as described in a recent blog post, we've been able to put some focus on a couple other key areas.

    N-Level Undo

    The n-level undo functionality in CSLA .NET relies on reflection against private fields. Obviously that's not possible in Silverlight. Fortunately the serialization scheme we're using means that there's already a mechanism for trapping the values stored in the field manager. And there's the OnGetState()/OnSetState() methods that allow a business developer to trap/restore values in their private fields (if they choose). So UndoableBase had to be altered to use these techniques rather than using reflection. The end result is the same, which is what really matters.

    We opted not to replicate IEditableObject into CSLA Light. It is a .NET interface used by Windows Forms data binding, and is the source of never-ending pain thanks to all the edge cases and idiosyncrasies around this, seemingly simple, interface. Of course the interface isn't used by Silverlight (or WPF), and so isn't necessary. The effect of this choice is to simplify quite a bit of the n-level undo code, while at the same time preserving the shape of the pre-existing public interface for all objects. In other words, BeginEdit(), CancelEdit() and ApplyEdit() work as expected, but you can't use IEditableObject to get at its versions of those methods.

    Justin just ran into a strange issue with BusinessListBase, where an attempt to iterate through the items in the list caused a strange runtime exception from somewhere deep in the bowels of the Silverlight runtime. It appears there's some issue with a subclass of a collection iterating through its own items in a foreach loop. A for loop works fine however, so we have a workaround.

    Ultimately however, the ability to easily implement a Cancel button, including when using modal dialogs (which can be simulated in Silverlight) is supported

    Data Portal

    The data portal is coming along pretty well too. It supports a provider model, conceptually similar to the data portal in .NET. And we currently have two providers: local and WCF.

    One issue we're facing here is that Silverlight has no configuration subsystem comparable to System.Configuration. So there's no easy way to get configuration data from an "app.config" file or equivalent. At the moment I've come up with a code-based configuration scheme - but (unless Microsoft puts out a solution soon) we'll probably end up creating some embedded resource-based configuration subsystem of our own.

    The data portal itself is asynchronous. This changes the way the UI code interacts with the data portal when compared to .NET code. Rather than just calling DataPortal.Fetch() to get an object, in Silverlight the UI must call a BeginFetch() method to start the process and handle a completed event to process any results when they return.

    This means the UI code looks something like this:

    var dp = new DataPortal<MockEditableRoot>();
    dp.FetchCompleted += new EventHandler<DataPortalResult<MockEditableRoot>>(dp_FetchCompleted);
    dp.BeginFetch();

    This code starts the process, and the dp_FetchCompleted is invoked (on the UI thread) when the call is complete:

    private void dp_FetchCompleted(object sender, DataPortalResult<MockEditableRoot> e)
    {
      this.DataContext = e.Object;
    }

    Alternately you can wrap this code into a factory method and completed event provided by the business class. That is a little closer to the typical CSLA .NET model - but is still async, and the UI still must handle the result in a callback event handler.

    Local Data Portal

    When using the data portal in local mode, it calls DataPortal_XYZ methods, much like the .NET data portal. There are a couple interesting differences however. The first being that the DataPortal_XYZ methods must be public in scope. Remember, no private reflection, so only public methods can be called.

    I debated about using an interface-based approach, but decided against it for a couple reasons. First, it would be dissimilar to the existing .NET approach. Second, it would mean that your DataPortal_XYZ methods couldn't be strongly typed - they'd have to accept parameters of type object and you'd have to cast them to something meaningful.

    The second difference flows from the fact that most server-related activities in Silverlight are asynchronous. Most DataPortal_XYZ methods, therefore, will be invoking async server calls and getting the results from a callback event. So all DataPortal_XYZ methods are provided a delegate they can use to do a callback to indicate completion. In a simple (synchronous) example it looks like this:

    public void DataPortal_Insert(
      Csla.DataPortalClient.LocalProxy<MockEditableRoot>.CompletedHandler handler)
    {
      LoadProperty<string>(DataPortalMethodProperty, "insert");
      handler(this, null);
    }

    The DataPortal_Insert() method accepts a CompletedHandler parameter it can use to indicate completion. The call to handler() is the completion call, and the first parameter is the resulting business object, while the second is an Exception object if you want to indicate failure.

    In an asynchronous example things are a bit more complex. And the async scenario is the most common. Typically when using a "local" data portal you'd be doing so because you want to call some web service or data service from Silverlight. And since all the server call technologies in Silverlight are async, your DataPortal_XYZ method will almost certainly be invoking some async service. So more normal code might look like this:

    public void DataPortal_Insert(
      Csla.DataPortalClient.LocalProxy<MockEditableRoot>.CompletedHandler handler)
    {
      var svc = new Csla.Testing.Business.TestService.TestServiceClient();
      svc.InsertDataCompleted +=
        new EventHandler<Csla.Testing.Business.TestService.InsertDataCompletedEventArgs>
          (svc_InsertDataCompleted);
      svc.InsertData(GetProperty<string>(DataPortalMethodProperty), handler);
    }

    void svc_InsertDataCompleted(
      object sender, Csla.Testing.Business.TestService.InsertDataCompletedEventArgs e)
    {
      var handler = (Csla.DataPortalClient.LocalProxy<MockEditableRoot>.CompletedHandler)e.UserState;
      handler((MockEditableRoot)e.Result, e.Error);
    }

    This looks a bit odd, but after you do a bit of Silverlight programming this pattern becomes second nature.

    The DataPortal_XYZ method sets up and starts the call - passing parameters to the service, and one parameter that is "user state", which is extra (doesn't go to the server, but stays on the client). Notice that before making the InsertDataAsync() call, which is the call to the service, the code hooks the InsertDataCompleted event - this is the event that will be raised (on the UI thread) when the service call completes.

    The svc_InsertDataCompleted() method is the event handler. This is where you write the code to handle the results from the service call. When using the data portal, this is where you call back into CSLA to indicate that the call is complete. Ultimately CSLA will return the result to the UI code, but this mechanism allows CSLA to do any extra processing between the DP_XYZ call and the UI so it can manage the state of your business object.

    You can also shrink this by using a lambda:

    public void DataPortal_Insert(
      Csla.DataPortalClient.LocalProxy<MockEditableRoot>.CompletedHandler handler)
    {
      var svc = new Csla.Testing.Business.TestService.TestServiceClient();
      svc.InsertDataCompleted += (o, e) => { handler((MockEditableRoot)e.Result, e.Error); };
      svc.InsertDataAsync(GetProperty<string>(DataPortalMethodProperty));
    }

    That eliminates the need for a separate event handler method and simplifies the code.

    Remote Data Portal

    The remote data portal option works very much like the normal .NET data portal, and is generally simpler to use that the local data portal. When the data portal is configured to use the WcfProxy, it will use WCF to communicate with a CSLA .NET data portal on the web/app server.

    In this scenario you need a web or app server that is hosting a CSLA .NET data portal - the .NET end of the CSLA Light data portal. The CSLA Light code running on the Silverlight client will call the CSLA .NET code running on the app server.

    When using a remote data portal, the Silverlight business object will not include any DataPortal_XYZ methods. The DataPortal_XYZ methods will only be implemented in the .NET code, and will only exist on the server. The client-side code will still call the data portal, but the call will be automatically routed through WCF to the app server.

    This is exactly the same kind of behavior you'd get from the existing .NET data portal - you can choose to use a local or remote data portal, but the business object and UI code are the same either way (with the exception that a local data portal requires implementation of DataPortal_XYZ methods).

    On the app server, which is running CSLA .NET, requests will come in from the Silverlight client. These requests can be handled in one of two ways.

    The default is for the client call to be routed into the CSLA .NET data portal, and the rest of the processing is normal CSLA .NET processing. In other words, a Silverlight Fetch() call results in a DataPortal.Fetch() call on the app server, which runs the DataPortal_Fetch() method just like it always has. The result of the data portal call on the app server is then returned to the Silverlight client.

    I call that the "pass-through" mode because the server-side data portal just passes the client call through to the "real" data portal. And this is a great option for when you trust the client that is running the Silverlight app, because it requires the least amount of code and provides the simplest solution.

    But if you don't trust the Silverlight client. If you are worried that someone will break into the Silverlight runtime and somehow put bad data into your object's fields (perhaps bypassing your business logic, etc), then extra precautions are required. To address that concern, the server-side data portal can optionally invoke an "observer" or "factory" (I'm still debating the name of this thing).

    To do this, on your server-side business object code (in the server-only partial class) you use the MobileFactory attribute to specify the type name of the factory object, and the method names to be called for create, fetch, update and delete operations (the only operations the data portal supports).

    [MobileFactory("MyProject.MyFactory, MyProject", "Create", "Fetch", "Update", "Delete")]
    public partial class MockEditableRoot

    Then you must implement the factory class:

    public class MyFactory
    {
      public object Create(object criteria)
      {
        // create, initialize and return new object here
      }

      public object Fetch(object criteria)
      {
        // create, load and return object here 
      }

      public object Update(object inbound)
      {
        // insert, update or delete object here
        // return resulting object
      }

      public void Delete(object criteria)
      {
        // delete object here 
      }
    }

    The criteria or business object from the client does materialize on the server. Of course on the server it materializes within code you control, and so you can safely interact with the object from within the methods of this factory. Here, you can force re-running of the validation rules, apply extra authorization rules or other processing you see fit - all on the app server. Only if you are happy with the object would you then invoke the "real" data portal to actually allow the persistence to occur.

    Tuesday, June 24, 2008 10:24:09 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [4]  | 

     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 [8]  | 

     Saturday, June 14, 2008

    We're nearly done with the final serialization implementation. At this point it is possible to clone objects on Silverlight and on .NET using the same MobileFormatter. By extension, this means that objects can be cloned from Silverlight to .NET and visa versa, though we don't have tests for that yet. (and there's a bunch of cleanup and detail work to be done for completeness - but the core engine is there and working)

    The approach we've taken is automatic for managed backing fields in a subclass of BusinessBase or ReadOnlyBase. It is also automatic for BusinessListBase, ReadOnlyListBase, etc. It is not automatic for custom criteria classes, but is automatic for SingleCriteria.

    The approach does allow for serialization of private backing fields, as long as you override a couple methods in your business class to get/set the field values. This is quite comparable to the PropertyBag scheme from VB6, and is conceptually similar to implementing ISerializable (though not the same due to some required features that aren't in Silverlight - there's a reason Microsoft didn't implement something like the BinaryFormatter).

    What this means is that when using only managed backing fields, you have to do no work at all. Your objects will just serialize. If you are using one or more private backing fields you need to do something like this:

    namespace MyApp
    {
      [Serializable]
      public class CustomerEdit : BusinessBase<CustomerEdit>
      {
        protected override void OnGetState(SerializationInfo info)
        {
          base.GetState(info);
          info.AddValue("MyApp.CustomerEdit._id", _id);
          info.AddValue("MyApp.CustomerEdit._name", _name);
        }

        protected override void OnSetState(SerializationInfo info)
        {
          base.SetState(info);
          _id = info.GetValue<int>("MyApp.CustomerEdit._id";
          _name = info.GetValue<string>("MyApp.CustomerEdit._name");
        }
      }
    }

    Assuming, of course, that you have two private backing fields, _id and _name. The one important restriction is that the types of all fields must be primitive types, or types that can be coerced using Csla.Utilities.CoerceValue() (which means the value can be converted to/from a string as required by the DataContractSerializer).

    Of course if you have a field value that can't be automatically converted to/from a string, you can do the conversion yourself in the OnGetState/OnSetState methods.

    This will get a little more complex when we implement UndoableBase (which is the next item on the list), because your overrides must differentiate between "NonSerialized" and "NotUndoable" fields - by hand of course. I expect the final result will look more like this:

    namespace MyApp
    {
      [Serializable]
      public class CustomerEdit : BusinessBase<CustomerEdit>
      {
        protected override void OnGetState(SerializationInfo info, StateModes mode)
        {
          base.GetState(info);
          if (mode == StateModes.Serialization)
            info.AddValue("MyApp.CustomerEdit._id", _id);
          info.AddValue("MyApp.CustomerEdit._name", _name);
        }

        protected override void OnSetState(SerializationInfo info, StateModes mode)
        {
          base.SetState(info);
          if (mode == StateModes.Serialization)
            _id = info.GetValue<int>("MyApp.CustomerEdit._id";
          _name = info.GetValue<string>("MyApp.CustomerEdit._name");
        }
      }
    }

    The StateModes enum will have two values: Serialization and Undo. This will allow you to exclude certain fields that are serialization-only or perhaps undo-only. I think this is an edge case for the most part, but the option will be there.

    Child objects in CSLA .NET 3.5 and later should always be kept in managed backing fields, and so will be handled automatically. If you have a pressing need to store a child object reference in a private backing field, there are also OnGetChildren() and OnSetChildren() methods you can override. The code is slightly more complex, but is very prescriptive (you either do it right or it won't work :) ) - but I see this as an edge case too, and so I'm not worried if it is a little more complex.

    On the whole I'm pretty pleased with this approach. It automates as many cases as can be automated without using reflection, but provides a great deal of extensibility and flexibility for those who don't want to use managed backing fields.

    Saturday, June 14, 2008 8:58:12 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [3]  | 

     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:

    MobileObjectCD

    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.

    FMCD

    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:

    http://www.lhotka.net/weblog/MiddletierHostingEnterpriseServicesIISDCOMWebServicesAndRemoting.aspx

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

    1)

    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.

    2)

    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.

    3)

    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.

    4)

    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 [1]  | 

    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:

    image

    The XML byte stream can later be deserialized into a list of DTOs, and then into a clone of the original object graph, as shown here:

    image

    Notice that the object graph shape is preserved (something the DataContractSerializer in Silverlight can't do at all), and that the object graph is truly cloned.

    This decision does impose an important constraint on business objects created for CSLA Light, in that they must use managed backing fields. Private backing fields will not be supported. I prefer not to impose constraints, but this one seems reasonable because the alternatives are all worse than this particular constraint.

    My goal is to allow you to write your properties, validation rules, business rules and authorization rules exactly one time, and to have that code run on both the Silverlight client and on your web/app server. To have that code compile into the Silverlight runtime and the .NET runtime. To have CSLA .NET and CSLA Light provide the same set of public and protected members so you get the same CSLA services in both environments.

    By restricting CSLA Light to only support managed backing fields, I can accomplish that goal without imposing requirements for extra coding behind every business object, or the insertion of arcane reflection code into every business class.

    Tuesday, June 10, 2008 8:01:50 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [4]  | 

     Thursday, April 24, 2008

    Dunn Training has been offering a very good 3 day class on CSLA .NET for some time now, with lots of great feedback. And this class continues (with a sold-out class coming up in Toronto).

    As a compliment to that class, Dunn is now lining up a bigger and deeper 5 day master class. The plan is to have just two of these each year.

    This master class is quite different from the 3 day class. It will have more lecture, deeper labs and a faster pace. They tell me the intent is to cover everything from OO design to CSLA object creation to WPF/Windows/Web/WCF/WF interface design to LINQ in one intense week.

    Not only will this be the ultimate in CSLA .NET training, it'll be some incredibly awesome training on .NET itself!!

    Thursday, April 24, 2008 2:45:39 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [5]  | 

     Wednesday, April 23, 2008

    I spent some time over the past few days using my prototype Silverlight serializer to build a prototype Silverlight data portal. It is still fairly far from complete, but at least I've proved out the basic concept and uncovered some interesting side-effects of living in Silverlight.

    The good news is that the basic concept of the data portal works. Defining objects that physically move between the Silverlight client and a .NET web server is practical, and works in a manner similar to the pure .NET data portal.

    The bad news is that it can't work exactly like the pure .NET data portal, and the technique does require some manual effort when creating the business assemblies (yes, plural).

    The approach I'm taking involves having two business assemblies (VS projects) that share many of the same code files. Suppose you want to have a Person object move between the client and server. You need Person in a Silverlight class library and in a .NET class library. This means two projects are required, even if they have the same code file.

    Visual Studio makes this reasonable, because you can create the file in one project (say the Silverlight class library) and then Add Existing Item and use the Link feature to get that same file included into a .NET class library project.

    I also make the class be a partial class, so I can add extra code to the .NET class library implementation. The result is:

    BusinessLibrary.Client (Silverlight class library)
      -> Person.cs

    BusinessLibrary.Server (.NET class library)
      -> Person.cs (linked from BusinessLibrary.Client)
      -> Person.Server.cs

    One key thing is that both projects build a file called BusinessLibrary.dll. Also, because Person.cs is a shared file, it obviously has the same namespace. This is all very important, because the serializer requires that the fully qualified type name ("namespace.type,assembly") be the same on client and server. In my case it is "BusinessLibrary.Person,BusinessLibrary".

    The Person.Server.cs file contains the server-only parts of the Person class - it is just the rest of the partial class. The only catch here is that it can not define any fields because that would obviously confuse the serializer since those fields wouldn't exist on the client. Well, actually it could define fields as long as they were marked as NonSerialized.

    Of course you could also have a partial Person.Client.cs in the Silverlight class library - though I haven't found a need for that just yet.

    One thing I'm debating is whether the .NET side of the data portal should just directly delegate Silverlight calls into the "real" data portal - effectively acting as a passive router between Silverlight and the .NET objects. OR the .NET side of the data portal could invoke specific methods (like Silverlight_Create(), Silverlight_Update(), etc) so the business developer can include code to decide whether the calls should be processed on the server at all.

    The first approach is simple, and certainly makes for a compelling story because it works very much like CSLA today. The Silverlight client gets/updates objects in a very direct manner.

    The second approach is a little more complex, but might be better because I'm not sure you should blindly trust anything coming from the Silverlight client. You can make a good argument that Silverlight is always outside the trust boundary of your server application, so blindly passing calls from the client through the data portal may not be advisable.

    Either way, what's really cool is that the original .NET data portal remains fully intact. This means that the following two physical deployment scenarios are available:

    Silverlight -> Web server -> database
    Silverlight -> Web server -> App server -> database

    Whether the web/app server is in 2- or 3-tier configuration is just a matter of how the original .NET data portal (running on the web server) is configured. I think that's awesome, as it easily enables two very common web server configurations.

    The big difference in how the Silverlight data portal works as compared to the .NET data portal is on the client. In Silverlight you should never block the main UI thread, which means calls to the server should be asynchronous. Which means the UI code can't just do this:

    var person = Person.GetPerson(123);

    That sort of synchronous call would block the UI thread and lock the browser. Instead, my current approach requires the UI developer to write code like this:

    var dp = new Csla.DataPortal();
    dp.FetchCompleted +=
      new EventHandler<Csla.DataPortalResult<Person>>(dp_FetchCompleted);
    dp.BeginFetch<Person>(new SingleCriteria<int>(123));

    with a dp_FetchCompleted() method like:

    private void dp_FetchCompleted(object sender, Csla.DataPortalResult<Person> e)
    {
      if (e.Error != null)
        // e.Error is an exception - deal with the issue
      else
        // e.Object is your result - use it
    }

    So the UI code is more cumbersome than in .NET, but it follows the basic service-calling technique used in any current Silverlight code, and I don't think it is too bad. It isn't clear how to make this any simpler really.

    Wednesday, April 23, 2008 8:08:36 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [13]  | 

     Sunday, April 13, 2008

    Silverlight 2.0 doesn't have an equivalent to the BinaryFormatter or NetDataContractSerializer. This makes some things quite challenging - in my case building CSLA Light. CSLA .NET requires high-fidelity serialization both for implementation of the Clone() operation and within the data portal.

    I've been working on building a Silverlight-compatible equivalent to the BinaryFormatter/NDCS. It turns out to be quite hard due to the limitations of the Silverlight sandbox.

    For example, Silverlight does have reflection, even against private fields. However, you can only get or set a private field with code inside the same class as the field declaration. You can't get/set a field from another object, or even from a base class or subclass. The reflection call must be in the same class!

    At this point I have a prototype serializer that works in some limited scenarios. It is a starting point. Some aspects aren't ideal, but may just be the way they are to get around how Silverlight works. Still, the end result is relatively cool.

    To use the serializer:

    1. Build the Csla project (it is a Silverlight Class Library) and reference it from your Silverlight application
    2. In your business class, add a using/Imports statement for Csla.Serialization
    3. Add the Serializable attribute to your class
    4. You class must also either inherit from MobileObject or implement the IMobileObject interface (I recommend using inheritance, as otherwise you'll have to write a lot of nasty code)
    5. You must override GetValue() and SetValue() in your class - these methods are called by the MobileFormatter so you can reflect against your private fields. See the example below to see how this works
    6. You can now use the MobileFormatter much like you would the BinaryFormatter. See the example below

    The MobileFormatter is far from complete. But it can serialize/deserialize fields of an object that contain primitive types (anything that works with Convert.ChangeType()). And it handles references to other serializable objects, both single objects and lists of serializable objects (if they implement IMobileObject or inherit from MobileList<T> ).

    I'm pretty sure it can't handle arrays, nor can it handle any list type other than (effectively) List<T>. I'm not sure what it will do with enums or other types - just haven't gotten that far yet.

    Here's a serializable object:

    using System;
    using Csla.Serialization;

    namespace SilverlightApplication1
    {
      [Serializable]
      public class Person : MobileObject
      {
        #region Serialization

        protected override object GetValue(System.Reflection.FieldInfo field)
        {
          if (field.DeclaringType == typeof(Person))
            return field.GetValue(this);
          else
            return base.GetValue(field);
        }

        protected override void SetValue(System.Reflection.FieldInfo field, object value)
        {
          if (field.DeclaringType == typeof(Person))
            field.SetValue(this, value);
          else
            base.SetValue(field, value);
        }

        #endregion

        public string Name { get; set; }

        [NonSerialized]
        private DateTime _birthdate;
        public DateTime BirthDate
        {
          get { return _birthDate; }
          set { _birthdate = value; }
        } 
      }
    }

    And here's how to serialize/deserialize the object:

    var p = new Person();

    var formatter = new Csla.Serialization.MobileFormatter();
    var buffer = new System.IO.MemoryStream();
    formatter.Serialize(buffer, p);

    buffer.Position = 0;
    var copyOfP = (Person)formatter.Deserialize(buffer);

    Though it is unfortunate that every business class must implement GetValue() and SetValue(), I think that is a relatively small price to pay to get nearly the same capability as we have in .NET with the BinaryFormatter in terms of cloning objects, and more importantly in terms of serializing them across the network with full fidelity.

    Sunday, April 13, 2008 7:42:40 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [6]  | 

     Saturday, April 12, 2008

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

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

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

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

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

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

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

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

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

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

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

     Thursday, April 03, 2008

    CSLA .NET version 3.5 for .NET 3.5 and Visual Studio 2008 is now available for download from www.lhotka.net/cslanet/download.aspx. This version of CSLA .NET includes support for LINQ and provides substantial code reduction (often around 40%) when coding your business objects.

    Check out the official launch announcement on DotNetRocks!

    If you are using .NET 2.0 or 3.0 with Visual Studio 2005 or 2008 then you'll want to use CSLA .NET version 3.0.4. Version 3.0.4 includes some data binding bug fixes over version 3.0.3, and it works with .NET 2.0 or .NET 3.0. It is also available from the download page.

    As always, questions and comments are welcome on the forum at http://forums.lhotka.net.

    Thursday, April 03, 2008 8:27:11 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [4]  | 

     Monday, March 24, 2008

    Dunn Training is holding a three day CSLA .NET training class in Toronto, May 5-7. Dunn's three day class is a great way to jumpstart your use of CSLA .NET, and Toronto is a fun city, so this is a great opportunity!

    For details go to http://www.dunntraining.com/training/schedule.htm.
    Monday, March 24, 2008 8:50:29 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

     Monday, March 10, 2008

    In a previous post I talked about the new property declaration syntax options in CSLA .NET 3.5. When it comes to child objects, if the shortest form is used then CSLA will pretty much completely take care of all parent-child object interaction so you don't have to do it by hand. This is a tremendous code savings!

    So declaring a child property like this:

    private static PropertyInfo<ChildList> ChildListProperty =
      RegisterProperty<ChildList>(new PropertyInfo<ChildList>("ChildList");
    public ChildList ChildList
    {
      get { return GetProperty<ChildList>(ChildListProperty); }
    }

    allows CSLA to manage the child object. Of course you do need to create the child object somewhere, such as in the DataPortal_XYZ methods:

    [RunLocal]
    private void DataPortal_Create()
    {
      // initialize other fields here
      LoadProperty<ChildList>(ChildListProperty, ChildList.NewList());
      base.DataPortal_Create();
    }

    private void DataPortal_Fetch(...)
    {
      // initialize other fields here
      LoadProperty<ChildList>(ChildListProperty, ChildList.GetList(this.Id));
    }

    Another option is to use a lazy loading scheme. There are a couple options in how you can use lazy loading. You can avoid the DataPortal_Create() implementation by just creating a new, empty list - and I do this almost all the time now:

    private static PropertyInfo<ChildList> ChildListProperty =
      RegisterProperty<ChildList>(new PropertyInfo<ChildList>("ChildList");
    public ChildList ChildList
    {
      get
      {
        if (!FieldManager.FieldExists(ChildListProperty))
          SetProperty<ChildList>(ChildListProperty, ChildList.NewList());
        return GetProperty<ChildList>(ChildListProperty);
      }
    }

    With this approach you still need to load the child data in the DataPortal_Fetch() method. The only thing this does is eliminate the need for the code in DataPortal_Create() - which often means you don't need DataPortal_Create() at all.

    Another option is to truly lazy load the object by calling a factory method that actually loads the object with existing data:

    private static PropertyInfo<ChildList> ChildListProperty =
      RegisterProperty<ChildList>(new PropertyInfo<ChildList>("ChildList");
    public ChildList ChildList
    {
      get
      {
        if (!FieldManager.FieldExists(ChildListProperty))
          SetProperty<ChildList>(ChildListProperty, ChildList.GetList(this.Id));
        return GetProperty<ChildList>(ChildListProperty);
      }
    }

    Obviously this requires that the ChildList class implement a GetList() factory that calls the data portal so it can be loaded independently from its parent. This is different from the first example, where GetList() would use the new child data portal support (or could be implemented the old 3.0 way). I'll discuss the new child data portal support in a future blog post.

    If you use lazy loading, CSLA will automatically ensure that the newly created child has its edit level set correctly and that all data binding events cascade appropriately.

    in all cases you no longer need to write code in a parent object like this:

    protected override bool IsDirty
    {
      get
      {
        return base.IsDirty || _childList.IsDirty;
      }
    }

    protected override bool IsValid
    {
      get
      {
        return base.IsValid && _childList.IsValid;
      }
    }

    Nor do you need to do any hooking of child object events like PropertyChanged or ListChanged - that's all automatic as well.

    Monday, March 10, 2008 10:15:41 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [3]  | 

     Sunday, March 09, 2008

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

     Monday, March 03, 2008

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

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

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

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

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

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

     Thursday, February 28, 2008

    One of my primary goals with CSLA .NET 3.5 was to reduce the amount of code necessary for common business object tasks - like declaring a property or implementing a parent-child relationship. I've mentioned what I'm doing on the forum and elsewhere, but I thought a summary blog post would be nice. I'm motivated, because I spent some time earlier today upgrading some business object code based on CSLA 3.0.3 to 3.5 and it was just fun to watch the class shrink :)

    Basic Properties

    Prior to 3.5 my properties were comparatively large:

    public string Name
    {
      [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
      get
      {
        CanReadProperty(true);
        return _name;
      }
      [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
      set
      {
        CanWriteProperty(true);
        if (value == null) value = string.Empty;
        if (_name != value)
        {
          _name = value;
          PropertyHasChanged();
        }
      }
    }

    Now the same property looks like this:

    private static PropertyInfo<string> NameProperty =
      RegisterProperty<string>(typeof(CertificationEdit), new PropertyInfo<string>("Name"));
    public string Name
    {
      get { return GetProperty<string>(NameProperty); }
      set { SetProperty<string>(NameProperty, value); }
    }

    I think that is so cool!! Though there's a performance hit to this much reduction, because you'll notice there's no backing field. In this case CSLA is actually managing the property value in the background and that incurs a little overhead. You can compromise if you'd like:

    private static PropertyInfo<string> NameProperty =
      RegisterProperty<string>(typeof(CertificationEdit), new PropertyInfo<string>("Name"));
    private string _name = NameProperty.DefaultValue;
    public string Name
    {
      get { return GetProperty<string>(NameProperty, _name); }
      set { SetProperty<string>(NameProperty, ref _name, value); }
    }

    Nearly the same code, but now with a private backing field so CSLA doesn't have to manage the value. Slightly faster, with slightly more code.

    Either way, all the authorization, validation and data binding support works just like it did with the old syntax, so all the core features of CSLA .NET just keep working in your favor - with less code to write and maintain.

    Child Object Properties

    This new syntax works for child objects as well. A child used to look like this:

    private ChildType _child;
    public ChildType Child
    {
      [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
      get
      {
        CanReadProperty(true);
        return _child;
      }
    }

    The new syntax requires that CSLA manage the property value for child objects:

    private static PropertyInfo<ChildType> ChildProperty =
      RegisterProperty<ChildType>(typeof(CertificationEdit), new PropertyInfo<string>("Child"));
    public ChildType Child
    {
      get { return GetProperty<ChildType>(ChildProperty); }
    }

    The really cool part isn't the minor code savings in the property - it is the code savings elsewhere. Prior to 3.5 a parent object had to override IsDirty and IsValid, and had to hook and re-hook child data binding events. None of that code is required now! Because CSLA is managing the child object value, it can entirely handle IsDirty, IsValid and all data binding events automatically. This saves a lot of code in every parent object.

    Even better, this eliminates code that a lot of people forgot to write, or forgot to update when adding a new child. In short, this eliminates a primary source of bugs/pain when dealing with parent-child object relationships.

    There are other areas in 3.5 where I've reduced the code required, and I'll blog about others (like reducing data access code, eliminating many criteria classes and more) in future posts.

    Thursday, February 28, 2008 9:25:11 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [10]  | 

     Wednesday, February 27, 2008

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

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

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

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

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

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

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

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

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

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

     Friday, February 22, 2008

    CSLA .NET version 3.5 is for Visual Studio 2008 and .NET 3.5 only.

    If you are using .NET 3.0 or .NET 2.0 then CSLA .NET version 3.0.x is for you. Version 3.0.4 is a maintenance release incorporating some important bug fixes, especially around data binding.

    Version 3.0.4 will release concurrently with version 3.5, and I have put a refresh of the 3.0.4 code online for download at www.lhotka.net/cslanet/download.aspx.

    This release is quite stable, and you should consider using it if the bug fixes apply to you. See the change log for details.

    Friday, February 22, 2008 10:20:15 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

    CSLA .NET version 3.5 Beta 2 is now available for download from www.lhotka.net/cslanet/download.aspx.

    Please read the change log prior to installing/using this release. If you are coming from version 3.0 or lower there are a few potential breaking changes. If you are coming from 3.5 Beta 1 there is one potential breaking change.

    There are numerous bug fixes and feature tweaks from Beta 1 to Beta 2. These are thanks to the great feedback and help I've recieved from numerous people on the CSLA forum (http://forums.lhotka.net/) - thank you all for your help!!!

    I am excited to release Beta 2, because we're narrowing in on a final release of version 3.5 and any changes now will be bug fixes or stabilization. Any testing you can do on this new release is appreciated and will help ensure high quality in the final release.

    Friday, February 22, 2008 10:06:52 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [2]  | 

     Monday, January 28, 2008

    Just to let everyone know, there's a CSLA .NET training class coming up in Atlanta Feb 18-20. The class is organized by Dunn Training, who has been delivering this quality training for over a year now, with great feedback from attendees!

    Click here for details.

    Monday, January 28, 2008 9:32:49 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

     Thursday, January 24, 2008

    I reader recently sent me an email asking why the PTWebService project in the CSLA .NET ProjectTracker reference app has support for using the data portal to talk to an application server. His understanding was that web services were end points, and that they should just talk to the database directly. Here's my answer:

    A web service is just like any regular web application. The only meaningful difference is that it exposes XML instead of HTML.

     

    Web applications often need to talk to application servers. While you are correct – it is ideal to build web apps in a 2-tier model, there are valid reasons (mostly around security) why organizations choose to build them using a 3-tier model.

     

    The most common scenario (probably used by 40% of all organizations) is to put a second firewall between the web server and any internal servers. The web server is then never allowed to talk to the database directly (for security reasons), and instead is required to talk through that second firewall to an app server, which talks to the database.

     

    The data portal in CSLA .NET helps address this issue, by allowing a web application to talk to an app server using several possible technologies. Since different organizations allow different technologies to penetrate that second firewall this flexibility is important.

     

    Additionally, the data portal exists for other scenarios, like Windows Forms or WPF applications. It would be impractical for me to create different versions of CSLA for different types of application interface. In fact that would defeat the whole point of the framework – which is to provide a consistent and unified environment for building business layers that support all valid interface types (Windows, Web, WPF, Workflow, web service, WCF service, console, etc).

    Thursday, January 24, 2008 8:01:56 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [1]  | 

     Tuesday, January 15, 2008

    I have refreshed the CSLA .NET 3.5 download with much more recent code. (www.lhotka.net/cslanet/download.aspx)

    The C# and VB versions of the framework and ProjectTracker are now very comparable. The only difference is that the VB framework doesn't have the LINQ extensions yet (though the C# version doesn't have the coolest parts yet either).

    Some highlights:

    1. All the new property/field/child management code is in both versions. The result is code reduction of ~35% per property and no more string literals for property names.
    2. All the new child object code is in both versions. The result is no more plumbing code for child objects, "automatic" lazy loading support and consistent persistence for root and child objects.
    3. Both versions have seriously enhanced type coercion that is used by the new property scheme and by DataMapper.
    4. Both versions have much improved type casting for SmartDate, allowing much more flexible use of this type.
    5. Check out the new ConnectionManager and ContextManager classes in Csla.Data for simplification of data access code with ADO.NET or LINQ.
    6. ProjectTracker.Library now uses an external data access assembly, which was created using LINQ to SQL.

    There are many other changes/enhancements/fixes - check out the change log for details. Or look at all the green items in the wish list, because that's all in 3.5.

    I am still planning to do a beta release around January 25, so this is probably the last preview release before the beta.

    I'm still working on a number of issues, and have more testing to do in general, but this is getting reasonably close to the final 3.5 feature set.

    If you have comments/questions/concerns, please voice them now! Once the beta starts I'll be doing bug fixes only.

    Tuesday, January 15, 2008 2:50:53 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [3]  | 

     Wednesday, December 19, 2007

    Way back at Tech Ed last year I was interviewed by my friend Ted Neward. The topic is CSLA .NET, and the interview ranges all over the place, from architecture, to the origin of the "CSLA" acronym to some of my thoughts on service-oriented architecture. It was long enough that they broke it into two parts. You can view or download them using the links below.

    OnMicrosoft (Video)subscribeRSS Details

    Component Based Scalable Logical Architecture - Part 1 (video)

    Component Based Scalable Logical Architecture - Part 2 (video)

    Wednesday, December 19, 2007 5:24:14 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

     Friday, December 07, 2007

    I rather expected this - a bit of confusion around .NET versions and related CSLA .NET versions.

    Microsoft started the whole thing by calling .NET 2.5 version 3.0. Oops, did I say that out loud? :)

    But it is true. From a .NET programming perspective, 3.0 is purely additive over 2.0. Thus it is really hard to see why it is a major version.

    Especially when .NET 3.5 has a much bigger impact on day-to-day use of .NET, but is just a point release... If anything, this should have been .NET 4.0, but it isn't and so now we're all royally stuck in the land of confusion.

    Nothing to do but make the best of it.

    I know several people and organizations who ignored .NET 3.0, but are now looking to move to .NET 3.5. Effectively "skipping" 3.0, though the reality is that their move to 3.5 is also a move to 3.0. Personally I think that's smart - they saved themselves a year of pain by not trying to use .NET 3.0 with the limited tools available, and can now move to 3.0/3.5 with Visual Studio 2008 - so they have decent tool support for the technology.

    When it comes to CSLA .NET, here's my take on it:

    • CSLA .NET 1.5.3 - latest version for .NET 1.x
    • CSLA .NET 2.1.4 - effectively obsolete
    • CSLA .NET 3.0.3 - latest version for .NET 2.0 and .NET 3.0
    • CSLA .NET 3.5.0 - in-progress version supporting .NET 3.5

    At this time I do not anticipate being able to make CSLA 3.5 work without .NET 3.5, primarily due to use of new compiler features as well as LINQ and features in .NET 2.0a and 3.0a (aka .NET 2.0 SP1 and 3.0 SP1).

    Friday, December 07, 2007 2:29:51 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [6]  | 

     Wednesday, December 05, 2007

    There's been a lot of activity in CSLA .NET, moving toward version 3.5.

    Aaron (my colleague at Magenic) has implemented indexed queries over CSLA collections in LINQ to Objects. So when you run a LINQ query against a CSLA collection (BusinessListBase, ReadOnlyListBase) and the where clause uses an indexed property the query will be much faster. You control which of your properties are indexed by using an attribute in the child business class on each property.

    Aaron is now working on ensuring that non-projection queries against a CSLA collection result in a live updatable "view" of the original collection. Much like the way SortedBindingList and FilteredBindingList work today. So a non-projection query will not result in a simple, disconnected IEnumerable<T>, but will result in something richer and more natural to use.

    In the meantime, I've been tackling items off the wish list. If you look at the list, you'll see quite a bit of green, indicating items that are (or will be) complete in 3.5.

    Some highlights include:

    • The code to declare a property has been reduced by more than 30% per property, and I've minimized the use of string literal property names for maintainability of code.
    • Added a child management concept so parent objects can automatically manage their children so you don't have to override IsValid/IsDirty, cascading events or resetting edit levels when using lazy loading. The result is code that is smaller and more maintainable.
    • SmartDate now supports type conversion, making it far easier to get values to/from string, DateTime and the new DateTimeOffset type.
    • DataMapper now does much richer type coercion, using IConvertible and value converters if they exist (like they now do for SmartDate). This is just the start of the DataMapper enhancements - watch for more.
    • A variety of small, but often important, changes and enhancements around validation rules and broken rules. These changes enable several important scenarios, especially around the consumption of broken rule data.
    Wednesday, December 05, 2007 9:23:59 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [2]  | 

     Thursday, November 15, 2007

    I'm busy getting my work and home life in order, as I head off to Barcelona with my oldest son for a week. I'm speaking at the Barcelona .NET user group on Wednesday, 21 November, so if you are in the area stop by and say hello! Otherwise, we'll be around the Barcelona area, enjoying Spain - I really love Spain!

    Some of what I'm busy trying to get organized are some of the upcoming changes to CSLA .NET in version 3.5. Thematically of course, the focus is on support for LINQ, primarily LINQ for Objects (like CSLA objects) and LINQ for SQL. As usual however, I'm also tackling some items off the wish list, and making other changes that I think will make things better/easier/more productive - and some that are just fun for me :)

    When talking about LINQ for Objects, there are a couple things going on. First, Aaron Erickson, a fellow Magenicon, is incorporating his i4o concepts into CSLA .NET to give CSLA collections the ability to support indexed queries. Second, there are some basic plumbing things that need to happen for LINQ to play well with CSLA objects, most notably ensuring that a result (other than a projection) from a query against a CSLA collection results in a live, updatable view of the original collection.

    By default LINQ just creates a new IEnumerable list with the selected items. But this can be horribly unproductive, because a user might add a new item or remove an existing item from that list - which would have no impact at all on the original list. Aaron has devised an approach by which a query against a BusinessListBase or ReadOnlyListBase will result in a richer resulting list, that is still connected to the original - much like SortedBindingList and FilteredBindingList are today. This way, when an item is removed from the view, it is also removed from the real list.

    Back to the i4o stuff, allowing indexing of properties on child objects contained in a list can make for much faster queries. If you only do a single query on a list it might not be worth building an index. But if you do multiple queries to get different views of a list (projections or not), having an index on one or more child object properties can make a very big performance difference!

    When talking about LINQ for SQL, the focus is really on data access. LINQ for SQL, in the CSLA world-view, is merely a replacement for ADO.NET. The same is true for the ADO.NET Entity Framework. Architecturally, both of these technologies simply replace the use of a raw DataReader or a DataSet/DataTable like you might use today. Alternately, you can say that they compete with existing tools like nHibernate or LLBLgen - tools that people already use instead of ADO.NET.

    In short, this means that your DataPortal_XYZ methods may make LINQ queries instead of using an ADO.NET SqlCommand. They may load the business object's fields from a resulting LINQ object rather than from a DataReader. In my testing thus far, I find that some of my DataPortal_Fetch() methods shrink by nearly 50% by using LINQ. That's pretty cool!

    Of course nothing is faster than using a raw DataReader. LINQ loads its objects using a DataReader too - so using LINQ does incur overhead that you don't suffer when using raw ADO.NET. However, many applications aren't performance-bound as much as they are maintenance-bound. That is to say that it is often more important to improve maintainability and reduce coding than it is to eek out that last bit of performance.

    To that end, I'm working on enhancing and extending DataMapper to be more powerful and more efficient. Since nHibernate, LINQ and ADO.NET EF all return data transfer objects or entity objects, it becomes important to be able to easily copy the data from those objects into the fields of your business objects. And that has to happen without incurring too much overhead. You can do the copies by hand with code that copies each DTO property into a field, which is fast, but is a lot of code to write (and debug, and test). If DataMapper can do all that in a single line of code that's awesome, but the trick is to avoid incurring too much overhead from reflection or other dynamic mapping schemes.

    One cool side-effect of this DataMapper work, is that it will work for LINQ and EF, but also for XML services and anything else where data comes back in some sort of DTO/entity object construct.

    There are also some issues with LINQ for SQL and context. Unfortunately, LINQ's context object wasn't designed to support n-tier deployments, and doesn't work well with any n-tier model, including CSLA. This means that LINQ doesn't/can't keep track of things like whether an object is new/old or marked for deletion. On the upside, CSLA already does all that. On the downside, it makes doing inserts/updates/deletes with LINQ for SQL more complex than if you used LINQ in the simpler 2-tier world for which it was designed. I hope to come up with some ways to bridge this gap a little so as to preserve some of the simpler LINQ syntax for database updates, but I'm not overly confident...

    I'm also doing a bunch of work to minimize and standardize the coding required to build a business object. Each release of CSLA has tended to standardize the code within a business object more and more. Sometimes this also shrinks the code, though not always. At the moment I'm incorporating some methods and techniques to shrink and standardize how properties are implemented, and how child objects (collections or single objects) are managed by the parent.

    By borrowing some ideas from Microsoft's DependencyProperty concept, I've been able to shrink the typical property implementation by about 35% - from 14 lines to 9:

    Private Shared NameProperty As PropertyInfo(Of String) = RegisterProperty(Of String, Customer)("Name")
    Private _name As String = NameProperty.DefaultValue
    Public Property Name() As String
      Get
        Return GetProperty(Of String)(NameProperty, _name)
      End Get
      Set(ByVal value As String)
        SetProperty(Of String)(NameProperty, _name, value)
      End Set
    End Property

    Unlike a DependencyProperty, this technique continues to use a strongly typed local field, which I think is a better approach (faster, though slightly less abstract).

    Child objects are similar:

    Private Shared LineItemsProperty As PropertyInfo(Of LineItems) = RegisterProperty(Of LineItems, Order)("LineItems")
    Public ReadOnly Property LineItems() As LineItems
      Get
        If Not ChildExists(LineItemsProperty) Then
          SetChild(Of LineItems)(LineItemsProperty, LineItems.NewList())
        End If
        Return GetChild(Of LineItems)(LineItemsProperty)
      End Get
    End Property

    In this case the implementation is more similar to a DependencyProperty, in that BusinessBase really does contain and manage the child object. There's value to that though, because it means that BusinessBase now automatically handles IsValid and IsDirty so you don't need to override them. The next step is to make BusinessBase automatically handle PropertyChanged/ListChanged/CollectionChanged events from the child objects and echo those as a PropertyChanged event from the parent. Along with that I'll also make sure that the child's Parent property is automatically set. This should eliminate virtually all the easy-to-forget code related to child objects - resulting in a lot less code and much more maintainable parent objects.

    As I noted earlier, there are a lot of things on the wish list, and I'll hit some of those as time permits.

    One item that I've done in VB and need to port to C# is changing authorization to call a pluggable IsInRole() provider method, allowing people to alter the algorithm used to determine if the current user is in a specific role. The default continues to do what it has always done by calling principal.IsInRole(), but for some advanced scenarios this extensibility point is very valuable.

    Beyond that I'll hit items on the wish list given time and energy.

    However, I need to have all major work done on 3.5 by the end of January 2008, because I'll start working on Expert 2008 Business Objects, the third edition of the Business Objects book for .NET, in January. The tentative plan is to have the book out around the end of June, which will be a tall order given that it will probably expand by 300 pages or so by the time I'm done covering .NET 3.0 and 3.5...

    Now I must do some packing, and get into the mindset required to survive 11 hours in the air - they just don't make airplane seats for people who are 6'5" tall.

    Thursday, November 15, 2007 9:34:59 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [8]  | 

     Tuesday, November 13, 2007

    I always encourage people to go with 2-tier deployments if possible, because more tiers increases complexity and cost.

    But it is important to recognize when the value of 3-tier outweighs that complexity/cost. The primary three motivators are:

    1. Security – using an app server allows you to shift the database credentials from clients to the server, adding security because a would-be hacker (or savvy end-user) would need to hack into the app server to get those credentials.
    2. Network infrastructure limitations – sometimes a 3-tier solution can help offload processing from CPU-bound or memory-bound machines, or it can help minimize network traffic over slow or congested links. Direct database communication is a chatty dialog, and using an app server allows a single blob of data to go across the slow link, and the chatty dialog to occur across a fast link, so 3-tier can result in a net win for performance if the client-to-server link is slow or congested.
    3. Scalability – using an app server provides for database connection pooling. The trick here, is that if you don’t need it, you’ll harm performance by having an app server, so this is only useful if database connections are taxing your database server. Given the state of modern database hardware/software, scalability isn’t a big deal for the vast majority of applications anymore.

    The CSLA .NET data portal is of great value here, because it allows you to switch from 2-tier to 3-tier with a configuration change - no code changes required*. You can deploy in the cheaper and simpler 2-tier model to start with, and if one of these motivators later justifies the complexity of moving to 3-tier, you can make that move with relative ease.

    * disclaimer: if you plan to make such a move, I strongly suggest testing in 3-tier mode during development. While the data portal makes this 2-tier to 3-tier switch seamless, it only works if the code in the business objects follows all the rules around serialization and layer seperation. Testing in a 3-tier mode helps ensure that none of those rules get accidentally broken during development.

    Tuesday, November 13, 2007 4:37:50 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [5]  | 

    Magenic is producing a series of webcasts on various IT related topics. One of them is CSLA .NET, and I'll be the speaker for that webcast. Click here for details on the date/time and how to register.

    Tuesday, November 13, 2007 2:49:57 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

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

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

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

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

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

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

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

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

     Monday, November 05, 2007

    I was recently asked how to get the JSON serializer used for AJAX programming to serialize a CSLA .NET business object.

    From an architectural perspective, it is better to view an AJAX (or Silverlight) client as a totally separate application. That code is running in an untrusted and terribly hackable location (the user’s browser – where they could have created a custom browser to do anything to your client-side code – my guess is that there’s a whole class of hacks coming that most people haven’t even thought about yet…)

    So you can make a strong argument that objects from the business layer should never be directly serialized to/from an untrusted client (code in the browser). Instead, you should treat this as a service boundary – a semantic trust boundary between your application on the server, and the untrusted application running in the browser.

    What that means in terms of coding, is that you don’t want to do some sort of field-level serialization of your objects from the server. That would be terrible in an untrusted setting. To put it another way - the BinaryFormatter, NetDataContractSerializer or any other field-level serializer shouldn't be used for this purpose.

    If anything, you want to do property-level serialization (like the XmlSerializer or DataContractSerializer or JSON serializer). But really you don’t want to do this either, because you don’t want to couple your service interface to your internal implementation that tightly. This is, fundamentally, the same issue I discuss in Chapter 11 of Expert 2005 Business Objects as I talk about SOA.

    Instead, what you really want to do (from an architectural purity perspective anyway) is define a service contract for use by your AJAX/Silverlight client. A service contract has two parts: operations and data. The data part is typically defined using formal data transfer objects (DTOs). You can then design your client app to work against this service contract.

    In your server app’s UI layer (the aspx pages and webmethods) you translate between the external contract representation of data and your internal usage of that data in business objects. In other words, you map from the business objects in/out of the DTOs that flow to/from the client app. The JSON serializer (or other property-level serializers) can then be used to do the serialization of these DTOs - which is what those serializers are designed to do.

    This is a long-winded way of saying that you really don’t want to do JSON serialization directly against your objects. You want to JSON serialize some DTOs, and copy data in/out of those DTOs from your business objects – much the way the SOA stuff works in Chapter 11.

    Monday, November 05, 2007 11:53:58 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

     Wednesday, October 17, 2007

       

    Now available in both VB and C# editions!

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

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

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

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

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

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

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

    Get the book at store.lhotka.net.

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

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

     Wednesday, October 10, 2007

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

    Here are the links to the video of the session.

    Real World Experiences Building Applications Using WPF and Silverlight

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

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

    I recently branched the CSLA .NET codebase in the svn repository (www.lhotka.net/cslacvs for a web view).

    Version 3.0.3, which is the maintenance branch for the current 3.0.2 version, is on a branch now. This is a VS 2005 solution (though ProjectTracker does include some VS 2008 projects for .NET 3.0 concepts).

    Active development is still on the trunk, and is for version 3.5. I'll be switching that version to a VS 2008 solution in the near future.

    Switching to VS 2008 is a big deal. I realize that many people will be using VS 2005 for a long time to come, and so I don't do this lightly.

    However, CSLA .NET 3.5 will include features around LINQ and other .NET 3.5 concepts. As such, I must use VS 2008 to do that work, because that is the tool for .NET 3.5 (and really for .NET 3.0).

    If possible, I'll continue to use the compiler directive approach to allow building Csla.dll for .NET 2.0, 3.0 and 3.5. Whether this is realistic or not depends on the level at which LINQ ends up integrating into the framework. If LINQ gets too deep, the complexity introduced by the compiler directive approach may become higher than I'm willing to deal with, at which point I'll drop that idea. But for now, my goal is to continue to allow backward targeting of the framework.

    Fortunately VS 2008 itself also supports backward targeting, so it is possible to use VS 2008 to build assemblies for .NET 2.0, 3.0 or 3.5. This may help mitigate some of the pain of having the Csla project switch to 2008, because you can still use 2008 to build for a .NET 2.0 deployment environment.

    Wednesday, October 10, 2007 11:02:08 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

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

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

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

    Windows Presentation Foundation SDK : Data Validation in 3.5

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

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

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

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

     Wednesday, October 03, 2007

    The VB version of CSLA .NET 3.0.2 is now officially available. For details see this post, and to download the code go to www.lhotka.net/cslanet/download.aspx.

    The VB edition of Using CSLA .NET 3.0 is in final review and should be available within a few days.

    Wednesday, October 03, 2007 7:32:10 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

     Friday, September 28, 2007

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

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

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

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

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

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

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

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

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

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

     Saturday, September 22, 2007

    I recently received this email, and wanted to share my reply.

    Rocky,

    Our company is going through a transformation in the way we do software.  We’re a very large company with offices all over the world, and it’s only my location that is using CSLA at this point.  We’ll now we’re faced with defending our decisions to use CSLA as the rest of the company attempts to create a “toolbox” of approved methodologies for development.  Normally I would think this is a good idea, but it seems to me that the people providing the recommendations, who interviewed us, don’t seem to have things right, especially when it comes to CSLA.

    Now, I figure I can create my arguments just fine… however, I think your help would be very valuable.  Here is a list of comments made about CSLA that I feel I have to clarify or defend.  Personally, I know they are blatantly wrong, but nevertheless, they seem to be common misconceptions about CSLA.  What do you think?  Again, these are not my comments, just misconceptions that I’m hearing from the rest of the company that I need to clear up.  Also, one of the key misconceptions here is that we should use Enterprise Library as a replacement for CSLA, again, they don’t understand what CSLA  .NET is for

    Misconceptions:

    1. CSLA .NET is an older concept, ported to .Net, unlike Enterprise Library which was written for .Net.

    2. Many CSLA features can be accomplished with Enterprise Library.

    3. CSLA .NET is a “niche” framework, when compared to the widely accepted Enterprise Library.

    4. CSLA .NET was not built with new technologies like WPF or WCF in mind.

    5. CSLA .NET is component based and wasn’t designed to take advantage/or be compatible with SOA.

    6. CSLA .NET, tied to its legacy, looks at the future of .NET and the adoption of SOA as merely an afterthought.

    Those are the key misconceptions that I feel I have to address… any help you can provide in formulating my arguments would be greatly appreciated.

    Thanks!

    Jimbo

    My reply follows:

    Jimbo,

    1. CSLA .NET is an older concept, ported to .Net, unlike Enterprise Library which was written for .Net.

    That is not strictly true. There is a strong and complete break between the COM-based CSLA and CSLA .NET. No code carried forward, and realistically the concepts in CSLA .NET were enabled by .NET itself, and have little to do with the limited world of COM.

    It is true that CSLA uses some OO concepts that have been around for a long time. These concepts have stood the test of time, and have proven to be very valuable for designing and building software. It would be foolish to discard great ideas just because they've had time to age. That'd be like discarding the wheel because it is an older concept...

    It is also important to recognize that CSLA .NET and Enterprise Library are entirely complementary. CSLA .NET solves a set of problems not addressed by EntLib, and EntLib solves a set of problems not addressed by CSLA .NET.

    2. Many CSLA features can be accomplished with Enterprise Library.

    Again, EntLib is complimentary to CSLA .NET. Things like logging, caching, data access, configuration and logging are outside the scope of CSLA .NET.

    Things like validation, authorization, data binding support and location transparency for n-tier development are the focus of CSLA .NET.

    While EntLib does have a validation module, it is architecturally unsound, putting the business logic into the UI layer rather than encapsulating it in a separate business layer.

    3. CSLA .NET is a “niche” framework, when compared to the widely accepted Enterprise Library.

    There is no doubt that using a niche framework is a risk. And any organization using CSLA .NET must be aware of the nature of the framework in that regard.

    However, it is also important to realize that CSLA .NET is the most widely used framework of its kind in .NET. Yes, EntLib is more widely used, but it does not duplicate or replace what CSLA .NET provides.

    If you don’t use CSLA .NET, you still need to solve the problems it addresses. Like it or not, there are gaps in .NET around data binding, validation, authorization and so forth. Gaps that CSLA .NET solves. As do other products like NetTiers, LLBLGen, Ideablade and others. Some commercial, some not.

    But none have the broad user base of CSLA .NET at this point in time.

    I’ve had several people approach me at conferences to point out that they replicated CSLA .NET. They’d read my book, didn’t want to use a “niche framework” and set out to do their own thing. Months later they looked at their app and realized that they’d re-solved all those same problems. Addressed all those same gaps. And that they’d largely recreated CSLA .NET. Usually they are sad about this, realizing just how much time they wasted recreating a framework that already exists.

    4. CSLA .NET was not built with new technologies like WPF or WCF in mind.

    This is patently untrue. Sorry, but CSLA .NET 2.0 was written specifically with WCF and WPF in mind. I am on steering groups within Microsoft, and so help shape the nature of many of these developer-oriented products. I knew years ahead of time the basic shape and nature of .NET 3.0, and so in 2005 CSLA .NET was already prepared for these new technologies.

    While most of the other bullets in the assessment are reasonable and well-considered (though I clearly dispute some conclusions), this bullet is simply absurd and discounts the many hundreds of hours of work I’ve put in over the past four or so years ensuring that CSLA .NET provides a seamless and transparent upgrade path from Windows Forms and Web Forms to WPF, and from Web services or Remoting to WCF.

    I challenge you to find another framework that will allow a switch from Web services or Remoting to WCF through a simple configuration file change. And yet I accomplished this in CSLA .NET by preparing for these technologies way back in 2004 and 2005.

    5. CSLA .NET is component based and wasn’t designed to take advantage/or be compatible with SOA.

    There are two aspects here.

    First, CSLA is a brand. Whether “component-based scalable logical architecture” is still accurately descriptive (it isn’t) doesn’t even matter anymore, because the brand is what it is. In other words, don’t read too much into the name – I’m stuck with it.

    Second, there is no doubt that CSLA is designed to support n-tier client/server architectures. Such architectures are currently the best way to build interactive applications with WPF, Windows Forms and Web Forms interfaces. Like it or not, SOA simply has too much overhead and is too high-cost to be effective for most interactive application development.

    It would be foolish to consider that object-oriented design is dead in the face of SOA. Or workflow. In fact, they are highly complimentary.

    A service or a workflow activity are, by definition, both atomic units of functionality. If they aren’t, then you are doing them wrong.

    Effectively every service and every activity are “mini-applications”. They are also effectively a use case, from an OOD perspective.

    Thus you can (and often should) design and implement your services and activities using OO concepts. And CSLA .NET is all about making it easier to apply OOD/P when building applications.

    As a result, whether you are building applications that consume services or that provide services or activities, CSLA .NET is a great help.

    6. CSLA .NET, tied to its legacy, looks at the future of .NET and the adoption of SOA as merely an afterthought.

    The reality is that CSLA .NET has been able to largely shield its users from the rapidly increasing rate of change and chaos in the Microsoft platform space. By enforcing a clear delineation between UI and business code, and by supporting .NET standard interfaces for data binding and other .NET features, CSLA .NET continues to act as a valuable buffer, allowing valuable business logic to easily move forward through time, even as interface technologies change and change and change.

    More time is spent on “future-proofing” both CSLA .NET, and more importantly the users of CSLA .NET, from changes to Microsoft’s platform than any other feature of the framework. Clearly it is impossible to abstract all the changes Microsoft comes up with, but CSLA .NET strives to protect that which is most important and costly to build and maintain: your business rules and logic.

    Saturday, September 22, 2007 1:36:43 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [11]  | 

     Friday, September 21, 2007

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

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

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

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

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

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

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

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

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

     Thursday, August 23, 2007

    I am working on my Using CSLA .NET 3.0 ebook and wrote some content that I don't think I'm going to use in the book now. But I don't want to waste the effort, so I'm posting it here.

    The text discusses an answer to a common question: how do I get my read-only list of X to know that some X data has been changed. Obviously the following technique can't detect that some other user has changed some data, but at least it detects and handles the case where the current user changes some data that would impact an existing read-only list in that same process.

     

    Another common example occurs when there is a read-only list that should be updated when an associated editable object is saved. For instance, you might have a CustomerList object that should be updated any time a Customer is saved.

    To solve that issue, the CustomerList object needs to subscribe to an event that is raised any time a Customer is saved. Such an event should be a static event on the Customer class:

      public class Customer : BusinessBase<Customer>

      {

        public static event EventHandler<Csla.Core.SavedEventArgs> CustomerSaved;

     

        protected static virtual void OnCustomerSaved(Customer sender, Csla.Core.SavedEventArgs e)

        {

          if (CustomerSaved != null)

            CustomerSaved(sender, e);

        }

     

        // ...

     

        protected override Customer Save()

        {

          Customer result = base.Save();

          OnCustomerSaved(this, new Csla.Core.SavedEventArgs(result));

          return result;

        }

      }

    The CustomerSaved event is declared using the standard EventHandler<T> model, where the argument parameter is of type Csla.Core.SavedEventArgs. The reason for the use of this type is that it includes a reference to the new object instance created as a result of the Save() call.

    Then the Save() method is overridden so the CustomerSaved event can be raised after the call to base.Save().

    The CustomerList class can then handle this static event to be notified as any Customer object is saved:

      public class CustomerList : ReadOnlyListBase<CustomerList, CustomerInfo>

      {

        private CustomerList()

        {

          Customer.CustomerSaved += new EventHandler<Csla.Core.SavedEventArgs>(Customer_Saved);

        }

     

        private void Customer_Saved(object sender, Csla.Core.SavedEventArgs e)

        {

          // find item corresponding to sender

          // and update item with e.NewObject

          Customer old = (Customer)sender;

          if (old.IsNew)

          {

            // it is a new item

            IsReadOnly = false;

            Add(CustomerInfo.LoadInfo((Customer)e.NewObject));

            IsReadOnly = true;

          }

          else

          {

            // it is an existing item

            foreach (CustomerInfo child in this)

              if (child.Id == old.Id)

              {

                child.UpdateValues((Customer)e.NewObject);

                break;

              }

          }

        }

      }

    The final requirement is that the read-only CustomerInfo business object implement a LoadInfo() factory method, and an UpdateValues() method.

    The LoadInfo() factory method is used to initialize a new instance of the read-only object with the data from the new Customer object. Loading the data from the Customer object avoids having to reload the data from the database when it is already available in memory:

      internal static CustomerInfo LoadInfo(Customer cust)

      {

        CustomerInfo info = new CustomerInfo();

        info.UpdateValues(cust);

        return info;

      }

    The UpdateValues() method sets the read-only object’s fields based on the values from the Customer object:

      internal void UpdateValues(Customer cust)

      {

        _id = cust.Id;

        _name = cust.Name;

        // and so on ...

      }

    The end result is that the CustomerList object is updated to reflect changes to the saved Customer object. The CustomerSaved event notifies CustomerList of the change, and (in most cases) CustomerInfo can update itself without hitting the database by loading the data from the Customer object that is already in memory.

    Thursday, August 23, 2007 3:35:30 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [10]  | 

     Thursday, August 09, 2007

    I just spent the past few days pulling my hair out trying to get a custom principal to work in WCF.

    Google returned all sorts of interesting, but often outdated and/or overly complex results. I kept looking at the techniques people were using, thinking this can't be so hard!!!

    Well, it turns out that it isn't that hard, but it is terribly obscure... Fortunately I was able to get help from various people, including Clemens Vasters, Juval Lowy and (in this case most importantly) Christian Weyer. Even these noted WCF experts provided an array of options rather than a unified, simple answer like I'd expected.

    My conclusion: while WCF really is cool as can be, it is also a deep plumbing technology that begs for abstraction for use by "normal" people.

    Anyway, as a result of my queries, Christian got one of his colleagues to write the blog post I wish I had found a few days ago: www.leastprivilege.com - Custom Principals and WCF.

    One of my motivations in researching this issue was for the WCF chapter in my upcoming Using CSLA .NET 3.0 ebook. There's now a comprehensive discussion of the topic in that chapter, starting with the creation and use of X.509 certificates and walking through the whole process of implementing custom authentication and using a custom principal in a WCF service. Dominick's blog post is great, but only covers about a third of the overall solution in the end.

    The ebook should be out toward the end of September, for those who are wondering.

    Thursday, August 09, 2007 2:28:24 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

     Wednesday, August 01, 2007

    I wrote the following for the Using CSLA .NET 3.0 ebook, but I don't think I'm going to use it now, because I've wrapped most of this into a new class in CSLA .NET. Rather than letting this go to waste though, I thought I'd post it here. Remember that it is just draft content, so it may have typos or errors, but perhaps it will be useful to someone:

    Basic Workflow Execution

    Executing a workflow is a little tricky, because workflows default to running on a background thread. That means you must take steps to ensure that the workflow completes before the host process terminates.

    One way to solve this issue is to always execute a workflow synchronously. Another is to use a thread synchronization object to prevent the process from terminating until the workflow completes.

    Note: It is also possible to suspend and resume workflows, and even to unload them from memory so they store their state in a database. Later you can reload that workflow instance and resume it. These advanced scenarios are outside the scope of this book

    Synchronous Execution

    The code to synchronously execute a workflow follows a standard pattern:

    1.      Create an instance of the WorkflowRuntime.

    2.      Create a synchronization object.

    3.      Set up event handlers.

    4.      Create workflow instance.

    5.      Ensure you have a valid principal object.

    6.      Start the workflow.

    7.      Wait for the workflow to complete.

    The only step unique to CSLA .NET is number 5, and that is only required if you are using custom authentication. The WF runtime will automatically ensure that the background thread that executes the workflow has the same principal as the thread that calls the workflow’s Start() method, but you must ensure that the principal is set on the current thread before calling Start().

    The following code implements these steps to execute the ProjectWorkflow implemented earlier in this chapter:

          using (WorkflowRuntime workflowRuntime = new WorkflowRuntime())

          {

            Exeception error = null;

     

            AutoResetEvent waitHandle = new AutoResetEvent(false);

            workflowRuntime.WorkflowCompleted +=

              delegate(object sender, WorkflowCompletedEventArgs e)

              {

                 waitHandle.Set();

              };

            workflowRuntime.WorkflowTerminated +=

              delegate(object sender, WorkflowTerminatedEventArgs e)

              {

                error = e.Exception;

                waitHandle.Set();

              };

     

            // create workflow instance

            Dictionary<string,object> parameters = new Dictionary<string,object>();

            parameters.Add("ProjectId", projectId);

            WorkflowInstance instance =

              workflowRuntime.CreateWorkflow(

                typeof(PTWorkflow.ProjectWorkflow),

                parameters);

     

            // login before starting WF instance

            ProjectTracker.Library.Security.PTPrincipal.Login("pm", "pm");

     

            // execute workflow

            instance.Start();

     

            // wait for workflow to complete

            waitHandle.WaitOne();

     

            // throw any workflow exception

            if (error != null)

              throw error;

          }

    Creating the workflow instance involves setting up a Dictionary<string, object> that contains name/value pairs for any parameters to be passed into th workflow instance:

            // create workflow instance

            Dictionary<string,object> parameters = new Dictionary<string,object>();

            parameters.Add("ProjectId", projectId);

            WorkflowInstance instance =

              workflowRuntime.CreateWorkflow(

                typeof(PTWorkflow.ProjectWorkflow),

                parameters);

    The name in the dictionary must correspond to the name of a dependency property defined by the workflow, and of course the type of the value must match the dependency property type.

    Keep in mind that creating an instance of a workflow does not start the workflow. The workflow won’t start executing until the Start() method is called later in the code.

    The waitHandle synchronization object is the key to making this process synchronous. The waitHandle object starts out unset because false is passed to its constructor as its initial state:

            AutoResetEvent waitHandle = new AutoResetEvent(false);

    At the bottom of the code is a line that calls WaitOne(), thus blocking the current thread until waitHandle is set:

            // execute workflow

            instance.Start();

     

            // wait for workflow to complete

            waitHandle.WaitOne();

    While the current (starting) thread is blocked, the workflow is busy executing on a background thread. In other words, the Start() call returns immediately, having just started the workflow instance executing on a background thread. Without the WaitOne() call, the current thread would exit the code block, which would dispose the WF engine instance while it is executing the workflow. The result would be an exception.

    Notice how the event handlers for the WorkflowCompleted and WorkflowTerminated events both call waitHandle.Set(). These events are raised by the WF engine when the workflow either completes or terminates unexpectedly. Either way, by calling the Set() method, the current thread is released so it can continue running.

    In the case of a workflow terminating unexpectedly, the exception from the workflow is made available to the WorkflowTerminated event handler. You can choose what to do with this information as appropriate for your application. One technique is shown here, which is to store the Exception object in a field:

              delegate(object sender, WorkflowTerminatedEventArgs e)

              {

                error = e.Exception;

                waitHandle.Set();

              };

    And then have the current thread throw the exception once it is unblocked:

            // wait for workflow to complete

            waitHandle.WaitOne();

     

            // throw any workflow exception

            if (error != null)

              throw error;

    The result of this code is that the workflow appears to run synchronously, even though it really executes on a background thread.

    Asynchronous Execution

    Allowing a workflow to run asynchronously is just a slightly more complex version of running the workflow synchronously. The important thing is to ensure that your process doesn’t exit until the workflow is complete. This means that the synchronization object must be available at a broader scope so you can write code to prevent the application from closing if the workflow is still running.

    You also must come up with a way to deal with any exception object in the case that the workflow terminates unexpectedly. One solution is to elevate the error field from the previous example to a broader scope as well.

    Finally, the WorkflowRuntime instance must remain in memory until the workflow completes.

    This means that you must define these fields so they exist at an application level, for instance using static fields:

      private static AutoResetEvent _waitHandle = null;

      private static Exception _workflowError = null;

      private static WorkflowRuntime _workflowRuntime = null;

    Then you can create a method to start the workflow:

        public static void BeginWorkflow(Guid projectId)

        {

          _workflowRuntime = new WorkflowRuntime();

          _waitHandle = new AutoResetEvent(false);

          _workflowRuntime.WorkflowCompleted +=

            delegate(object sender, WorkflowCompletedEventArgs e)

            {

               _waitHandle.Set();

            };

          _workflowRuntime.WorkflowTerminated +=

            delegate(object sender, WorkflowTerminatedEventArgs e)

            {

              _workflowError = e.Exception;

              _waitHandle.Set();

            };

     

          // create workflow instance

          Dictionary<string,object> parameters = new Dictionary<string,object>();

          parameters.Add("ProjectId", projectId);

          WorkflowInstance instance =

            _workflowRuntime.CreateWorkflow(

              typeof(PTWorkflow.ProjectWorkflow),

              parameters);

     

          // login before starting WF instance

          ProjectTracker.Library.Security.PTPrincipal.Login("pm", "pm");

     

          // execute workflow

          instance.Start();

        }

    Notice that the WorkflowRuntime object is no longer in a using block, so it can remain in memory, not disposed, while the workflow instance is running on the background thread.

    The workflow instance is created the same as before, and its Start() method is called. At that point this method simply ends, returning to the caller.

    Once you call BeginWorkflow() the workflow is started on a background thread, but your current thread (often the UI thread) is free to continue working.

    The final piece to the puzzle is a method your application can call before it exits, or when it otherwise can’t continue without the workflow having completed:

        public static void EndWorkflow()

        {

          // wait for workflow to complete

          _waitHandle.WaitOne();

     

          // dispose runtime

          _workflowRuntime.Dispose();

     

          if (_workflowError != null)

            throw _workflowError;

        }

    It is important to realize that this method will block the current thread until _waitHandle is set. If the workflow completes before this method is called, then _waitHandle is already set, and this method runs immediately, but if the workflow is still running, this method will block until the workflow completes or terminates.

    For this to work, you must call EndWorkflow() before your process terminates to properly dispose the runtime and to determine if the workflow terminated unexpectedly.

     

    Wednesday, August 01, 2007 4:15:26 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

     Tuesday, July 10, 2007

    CSLA .NET Version 3.0 is now available for download! Listen to the official announcement on .NET Rocks!

    CSLA .NET 3.0 includes numerous enhancements and features of value to all CSLA .NET users, and of course version 3.0 adds support for Microsoft .NET 3.0 features like WCF and WPF.

    You can use CSLA .NET 3.0 on either Microsoft .NET 2.0 or Microsoft .NET 3.0.

    Features for everyone

    CSLA .NET 3.0 includes enhancements useful to all CSLA .NET 2.1.4 users, including these highlights:

    Validation rules

    • PropertyFriendlyName – specify a friendly name to use when displaying broken rule text
    • Format – specify a format mask to use when displaying broken rule numeric values
    • StringMinLength – new validation rule method
    • DecoratedRuleArgs – useful for code generation of AddBusinessRules() methods
    • Fix bug with stopProcessing and rule priorities
    • RegEx – rule method now supports options for dealing with null values

    Authorization

    • New CanExecuteMethod() functionality, similar to CanReadProperty() and CanWriteProperty()

    Undo and Data binding

    • If edit levels get out of sync an exception is thrown, making debugging of Windows Forms data binding much easier

    Interfaces

    • Cleaned up and rearranged interfaces to provide more consistency – making it easier to create UI frameworks on top of CSLA business layers

    SmartDate

    • Added TryParse() method
    • Fix bug with CompareTo() method

    SortedBindingList and FilteredBindingList

    • Allow access to underlying source list

    BusinessListBase

    • Fix some bugs where ListChanged/CollectionChanged events were raised when they shouldn't have been. The result is that some data binding scenarios now work where they didn't, and in other cases performance is improved.

    ProjectTracker\PTWin

    • Reworked data binding code to address all known issues

    See the change log for a complete list of changes.

    Again, CSLA .NET 3.0 can be used without Microsoft .NET 3.0. If you want to build CSLA .NET 3.0 without installing the Microsoft .NET 3.0 runtime, you must define the NET20 symbol in project properties.

    Microsoft .NET 3.0 Features

    Of course the primary focus of CSLA .NET 3.0 is support for Microsoft .NET 3.0. Highlights include:

    CSLA .NET

    • WcfProxy – a data portal channel that uses WCF. You can transparently move from any existing data portal channel to WCF by using this new proxy.
    • DataContract – support for using the WCF DataContract and DataMember attributes in your business classes
    • WPF
      • CslaDataProvider – a data provider control that can create, fetch, save and cancel edits on a CSLA .NET business object. In some cases this can lead to code-less data entry forms!
      • Validator – a control that provides Windows Forms ErrorProvider-like behavior to WPF forms that are data bound to CSLA .NET objects.
      • Authorizer – a control that provides Windows Forms AuthorizeReadWrite-like behaviors to WPF forms that are data bound to CSLA .NET objects.
      • ObjectStatus – a control that exposes IsValid, IsSavable and other properties from a CSLA .NET business object so they can be used by XAML data binding.
      • IdentityConverter – a value converter that can be used to work around an issue with data binding and refreshing the UI.

    The Csla solution is a Visual Studio 2005 solution. You can open and build the solution in Visual Studio 2005 if you have the Microsoft .NET 3.0 runtime installed on your workstation. Or you can use the NET20 symbol to allow compilation without the Microsoft .NET 3.0 runtime.

    The Csla solution automatically upgrades when opened in Visual Studio 2008, and you can build the solution in Visual Studio 2008 if you are using that environment.

    ProjectTracker\PTWpf

    • Added new WPF UI with equivalent functionality to PTWin.

    Note that this project is built using Visual Studio 2008 (Orcas) Beta 1.

    ProjectTracker\PTWorkflow

    • Added new Workflow UI to illustrate how a workflow can use CSLA .NET business objects

    Note that this project is built using Visual Studio 2008 (Orcas) Beta 1.

    ProjectTracker\PTWcfClient and PTWcfService

    • Added a WCF service illustrating how to expose CSLA .NET objects through WCF/SOA
    • Added a WCF client app illustrating how to call a WCF service

    Note that these projects are built using Visual Studio 2008 (Orcas) Beta 1.

    ProjectTracker\WcfHost

    • Added a WCF host for the data portal

    Note that this project is built using Visual Studio 2005 with the WCF extensions installed.

    The ProjectTracker solution includes WcfHost, but does not include the other new projects. The reason for this is that the ProjectTracker solution is still a Visual Studio 2005 solution, while these other projects are built using Visual Studio 2008. The ProjectTracker solution upgrades automatically when opened in Visual Studio 2008, and in that environment you can add the remaining projects to the solution.

    Migration

    Migrating from version 2.1.4 to 3.0 should be relatively painless.

    The only place you may encounter issues is that version 3.0 throws an exception if your edit levels get out of sync when using n-level undo. This may highlight pre-existing bugs in your UI code (especially in Windows Forms apps) that you should resolve. Look at the ProjectTracker\PTWin code for examples of the correct way to interact with Windows Forms data binding.

    Migrating from 2.0.x to 3.0 has the same challenges as moving from 2.0 to 2.1. Version 2.1 introduced some significant, but important, changes to the handling of validation and authorization rules that can impact your business object code. See the CSLA .NET Version 2.1 Handbook for detailed information about version 2.1.

    Migrating from 1.x to 3.0 will require some effort. There are many new features in 2.1 and 3.0 as compared to 1.x, and taking advantage of those features requires changes to your business objects and your UI code. You can look at the Expert C#/VB 2005 Business Objects books and the CSLA .NET Version 2.1 Handbook to get details around the scope of the changes.

    Futures

    I plan to write an ebook showing how to use the new features and enhancements in CSLA .NET 3.0. This ebook should be available in the third quarter of 2007 (probably September).

    I’m working on CSLA .NET 3.5, based on Microsoft .NET 3.5 and focused on LINQ and various other new .NET features. Look for this in the first quarter of 2008.

    I am also planning to update my Expert Business Objects books for Visual Studio 2008 and CSLA .NET version 3.5. This will probably come out in the second quarter of 2008.

    You can see the roadmap here.

    Tuesday, July 10, 2007 8:56:10 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

     Sunday, June 24, 2007

    Just a quick reminder that the official 3 day CSLA .NET training roadshow continues through the summer. You can still attend in one of these cities:

    • Orlando
    • Chicago
    • Washington, DC
    • Dallas

    The feedback from the classes so far has been excellent! I sat in on part of the class last week in Minneapolis, and I can see why. Miguel is a very good teacher, and his hands-on, continual lab style is a refreshing change from traditional powerpoint-heavy training.

    Sunday, June 24, 2007 8:14:13 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [3]  | 

     Friday, June 22, 2007

    CSLA .NET Version 3.0 Beta 2 is now available for download.

    This is the final test release of version 3.0. Any changes between now and release will be bug fixes.

    If you plan to upgrade please consider helping yourself and the community at large by downloading this version and testing it before July 5. Let me know about any issues through the forum.

    CSLA .NET 3.0 provides support for Microsoft .NET 2.0 and 3.0.

    If you want to build CSLA .NET 3.0 without .NET 3.0, you must define the NET20 symbol in the project properties.

    CSLA .NET 3.0 includes enhancements useful to all 2.1.4 users, including these highlights:

    Validation rules

    ·         PropertyFriendlyName – specify a friendly name to use when displaying broken rule text

    ·         Format – specify a format mask to use when displaying broken rule numeric values

    ·         StringMinLength – new validation rule method

    ·         DecoratedRuleArgs – useful for code generation of AddBusinessRules() methods

    ·         Fix bug with stopProcessing and rule priorities

    ·         RegEx – rule method now supports options for dealing with null values

    Authorization

    ·         New CanExecuteMethod() functionality, similar to CanReadProperty() and CanWriteProperty()

    Undo and Data binding

    ·         If edit levels get out of sync an exception is thrown, making debugging of Windows Forms data binding much easier

    Interfaces

    ·         Cleaned up and rearranged interfaces to provide more consistency – making it easier to create UI frameworks on top of CSLA business layers

    SmartDate

    ·         Added TryParse() method

    ·         Fix bug with CompareTo() method

    SortedBindingList and FilteredBindingList

    ·         Allow access to underlying source list

    ProjectTracker\PTWin

    ·         Reworked data binding code to address all known issues

    See the change log for a complete list of changes.

    Of course the primary focus of CSLA .NET 3.0 is support for Microsoft .NET 3.0. Highlights include:

    ·         WcfProxy – a data portal channel that uses WCF. You can transparently move from any existing data portal channel to WCF by using this new proxy.

    ·         DataContract – support for using the WCF DataContract and DataMember attributes in your business classes

    ·         WPF

    o   CslaDataProvider – a data provider control that can create, fetch, save and cancel edits on a CSLA .NET business object. In some cases this can lead to code-less data entry forms!

    o   Validator – a control that provides Windows Forms ErrorProvider-like behavior to WPF forms that are data bound to CSLA .NET objects.

    o   Authorizer – a control that provides Windows Forms AuthorizeReadWrite-like behaviors to WPF forms that are data bound to CSLA .NET objects.

    o   ObjectStatus – a control that exposes IsValid, IsSavable and other properties from a CSLA .NET business object so they can be used by XAML data binding.

    o   IdentityConverter – a value converter that can be used to work around an issue with data binding and refreshing the UI.

    ProjectTracker\PTWpf

    ·         Added new WPF UI with equivalent functionality to PTWin.

    ProjectTracker\PTWorkflow

    ·         Added new Workflow UI to illustrate how a workflow can use CSLA .NET business objects

    ProjectTracker\PTWcfClient and PTWcfService

    ·         Added a WCF service illustrating how to expose CSLA .NET objects through WCF/SOA

    ·         Added a WCF client app illustrating how to call a WCF service

    ProjectTracker\WcfHost

    ·         Added a WCF host for the data portal

    Friday, June 22, 2007 3:30:47 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

     Wednesday, June 20, 2007

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

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

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

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

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

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

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

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

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

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

    The CslaDataProvider gets declared like this:

        <csla:CslaDataProvider x:Key="ChildList"

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

                               FactoryMethod="GetList"

                               IsAsynchronous="False"

                               ManageObjectLifetime="True">

        </csla:CslaDataProvider>

     

    Then the button controls get declared like this:

                <Button

                  Command="ApplicationCommands.Save"

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

                                  Path=CommandManager, BindsDirectlyToSource=True}"

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

                <Button

                  Command="ApplicationCommands.Undo"

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

                                  Path=CommandManager, BindsDirectlyToSource=True}"

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

     

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

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

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

     Monday, June 11, 2007

    I posted previously about an issue where the WCF NetDataContractSerializer was unable to serialize a SecurityException object. Microsoft provided some insight.

    It turns out that the constructor of the SerializationException object doesn't set the Action property to anything valid. Before you can serialize a SerializationException with NDCS you must explicitly set the Action property to a valid SecurityAction.

    This does mean that NDCS is not compatible with the BinaryFormatter in this case, but at least there's a workaround/solution.

    I've now updated CSLA .NET 3.0 to explicitly set the Action property any time a SecurityException is thrown, thus allowing the WCF data portal channel to return valid details about the nature of any exception.

    Monday, June 11, 2007 9:07:53 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

     Friday, June 01, 2007

    The WCF NetDataContractSerializer is an almost, but not quite perfect, replacement for the BinaryFormatter.

    The NDCS is very important, because without it WCF could never be viewed as a logical upgrade path for either Remoting or Enterprise Services users. Both Remoting and Enterprise Services use the BinaryFormatter to serialize objects and data for movement across AppDomain, process or network boundaries.

    Very clearly, since WCF is the upgrade path for these core technologies, it had to include a serialization technology that was functionally equivalent to the BinaryFormatter, and that is the NDCS. The NDCS is very cool, because it honors both the Serializable model and the DataContract model, and even allows you to mix them within a single object graph.

    Unfortunately I have run into a serious issue, where the NDCS is not able to serialize the System.Security.SecurityException type, while the BinaryFormatter has no issue with it.

    The issue shows up in CSLA in the data portal, because it is quite possible for the server to throw a SecurityException. You'd like to get that detail back on the client so you can tell the user why the server call failed, but instead you get a "connection unexpectedly closed" exception instead. The reason is that WCF itself blew up when trying to serialize the SecurityException to return it to the client. So rather than getting any meaningful result, the client gets this vague and nearly useless exception instead.

    By the way, if you want to see the failure, just run this code:

        Dim buffer As New System.IO.MemoryStream
        Dim formatter As New System.Runtime.Serialization.NetDataContractSerializer
        Dim ex As New System.Security.SecurityException("a test")
        formatter.Serialize(buffer, ex)

    And if you want to see it not fail run this code:

        Dim buffer As New System.IO.MemoryStream
        Dim formatter As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
        Dim ex As New System.Security.SecurityException("a test")
        formatter.Serialize(buffer, ex)

    I've been doing a lot of work with the NDCS over the past several months. And this is the first time I've encountered a single case where NDCS didn't mirror the behavior of the BinaryFormatter - which is why I do think this is a WCF bug. Now just to get it acknowledged by someone at Microsoft so it can hopefully get fixed in the future...

    The immediate issue I face is that I'm not entirely sure how to resolve this issue in the data portal. One (somewhat ugly) solution is to catch all exceptions (which I actually do anyway), and then scan the object graph that is about to be returned to the client to see if there's a SecurityException in the graph. If so perhaps I could manually invoke the BinaryFormatter and just return a byte array. The problem with that is in the case where the object graph is a mix of Serializable and DataContract objects - in which case the BinaryFormatter won't work because it doesn't understand DataContract...

    In the end I may just have to leave it be, and people will need to be aware that they can never throw a SecurityException from the server...

    Friday, June 01, 2007 11:34:14 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

     Thursday, May 31, 2007

    The CSLA .NET community has been very fortunate, in that people from all over the world have contributed their time and effort to build CSLA resource files for many languages. In CSLA 3.0 I added some new resource strings, and so there is a need to add some new translations to each language's resx file.

    If you are willing to update (or create a new) resx file for your language that is very kind. You will gain the benefit of having the proper translations, as will your fellow countrymen.

    You can also get the resx files from here:

    http://www.lhotka.net/cslacvs/viewvc.cgi/trunk/cslavb/Csla/My%20Project/

    The English file is called Resources.resx, and it is the master list.

    For most language files, this view should give the differences since version 2.0:

    http://www.lhotka.net/cslacvs/viewvc.cgi/trunk/cslavb/Csla/My%20Project/Resources.resx?r1=1282&r2=1465

    Knut Vonheim kindly put together a spreadsheet listing the new, obsolete and continued values for the resource file. It may be helpful for anyone doing more translations. You can get it from:

    http://www.lhotka.net/files/csla30/CSLAValues2.xvs3.0.xls

    Not all language files have been kept in sync at all times, so you may want to check your specific language to make sure it is completely correct and complete.

    Once you have updated your language's resx file, please EMAIL THE RESX to rocky (at) lhotka (dot) net.

    For reference purposes, I have created a wiki page with the list of languages for CSLA 2.0 and 3.0

    http://www.lhotka.net/wiki/default.aspx/LhotkaWiki/GlobalLanguages.html

    I'll keep updating this location as I get translations from people and add them to CSLA 3.0. Right now, the following languages are complete:

    CSLA 3.0

    CSLA 2.0

    ·       en (default)

    ·       da

    ·       es-ES

    ·       nl

    ·       ca-ES

    ·       no

    ·       pt

    ·       fr

    ·       de

    ·       km-KH

     

    ·       en (default)

    ·       bs

    ·       de

    ·       es

    ·       hr

    ·       it

    ·       pt-br

    ·       ro

    ·       ru

    ·       sr

    ·       sv

    ·       zh-CHS

    ·       il

    ·       da

    ·       es-ES

    ·       nl

    ·       ca-ES

    ·       no

    ·       pt

    ·       fr

    Thank you for helping the CSLA community!

    Thursday, May 31, 2007 7:44:02 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

     Monday, May 21, 2007

    I have made CSLA .NET 3.0 Beta 1 available for download from the CSLA download page.

    The changes in CSLA .NET version 3.0 are primarily focused on adding support for .NET 3.0 features: specifically WCF and WPF. No extra work was required to allow business objects to invoke WF workflows or to be used from activities in a WF workflow. There are also some very important bug fixes and feature enhancements that most people will want even when not using .NET 3.0.

    There are no major or intentional breaking changes from version 2.1.4 to version 3.0.

    CSLA 3.0 will work on .NET 2.0. You do not need .NET 3.0 to use this version. Obviously the WCF/WPF/WF features are only available to you if you have .NET 3.0.

    The WCF support comes in two forms: a data portal channel, and comprehensive support for the DataContract/DataMember attributes. The data portal support comes in the form of a new data portal proxy, which is functionally equivalent to the CSLA 2.0 channels. In other words, upgrading to WCF is entirely transparent. The DataContract support is an optional configuration switch you can set in app.config/web.config to tell CSLA to use the WCF serializer rather than the BinaryFormatter. This affects n-level undo and cloning. If you want to use DataContract instead of Serializable on your business classes you must use this config switch.

    The WPF support comes as a set of controls. These controls provide support for validation (like the Windows Forms ErrorProvider), authorization and a couple other key features. There is also a CSLA data provider control, allowing the creation of codeless XAML forms in some cases (for read-only data).

    In addition to the .NET 3.0 support, there are some other functional enhancements to various areas. Here are some highlights:

    1. Validation RuleArgs are now more sophisticated, allowing for more expressive human-readable rule descriptions, and providing a better model for code generators when specifying arguments to be passed into a rule method.
    2. A number of bugs in BusinessListBase related to data binding scenarios have been fixed. Event handling for other list classes has been standardized as well. You will likely find that data binding to grids is much more reliable in 3.0 than in 2.1.4.
    3. SmartDate has some minor enhancements and bug fixes.
    4. N-level undo now detects when edit levels are out of sync and throws an exception. This helps locate and debug problems where nested begin/cancel/apply calls are out of order. While this feature will most likely cause some short-term pain as you find these issues, the result is that your code will behave properly.

    For the complete list of changes, see the change log.

    My plan is to leave this beta online for 2-3 weeks, followed by a second beta in mid-June and a release at the end of June. If you plan to move to CSLA .NET 3.0 within the next few months, please consider downloading and testing this beta. Let me know about any issues you find so I can resolve them for Beta 2.

    Thank you!

    Monday, May 21, 2007 7:00:02 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [3]  | 

     Friday, May 04, 2007

    I have put a test version of CSLA .NET version 3.0 up for download from the download page.

    This release includes both VB and C# versions of CSLA .NET 3.0, though the WPF support in the VB version has undergone relatively little testing.

    The C# ProjectTracker sample is relatively complete, though I'm still chasing down some WPF navigation issues, and may change it over to a Windows-based approach.

    The VB ProjectTracker sample isn't as complete, but I've included it in the download nonetheless.

    I expect that this is the last pre-release of the CSLA .NET 3.0 framework itself - the next release will be a beta release, and it is my hope to be done with 3.0 by the end of June. If you have the time and inclination, please download the framework and give it a try.

    You should be aware that CSLA .NET 3.0 should work just fine on machines with only .NET 2.0, or with .NET 2.0 and 3.0 installed. It also works fine on Orcas Beta 1 (with .NET 2.0, 3.0 and 3.5 installed), though you'll have to upgrade the solution if you try to open it in VS Orcas.

    Obviously if you only have .NET 2.0 installed, you can't use WCF or WPF. Attempting to use those features in CSLA .NET will result in compile or runtime errors. However, there are numerous bug fixes and enhancements to other areas of CSLA .NET that may benefit .NET 2.0 users. If you find that CSLA .NET 3.0 doesn't work for you under .NET 2.0 (without .NET 3.0 installed) please let me know so I can address any issues.

    I am not aware of any breaking changes from CSLA .NET 2.1, so switching an existing project to use CSLA .NET 3.0 should be straightforward. If it is not, please let me know so I can either address or document any issues.

    Friday, May 04, 2007 10:14:37 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

     Tuesday, May 01, 2007

    This week Microsoft fully disclosed their plans for Silverlight. It is not only a way to build rich internet applications (RIAs), but it is a way to build them with .NET! This is very exciting news, and I hope that Microsoft follows through on their vision for Silverlight!!

    With the support of Magenic, I've been researching the possibility of creating a CSLA Light which would run in an Internet zone sandbox, and in the even more restrictive Silverlight environment. The Silverlight 1.1 alpha available today doesn't have enough functionality to even come close to hosting something like CSLA, but Microsoft's plan for Silverlight should provide enough functionality to create a stripped down, client only version of CSLA.

    That means no data portal, no Clone() method, and the requirement to implement GetState() and SetState() methods to support n-level undo (thanks to no private reflection). But it does mean that I should be able to provide the full validation, authorization, data binding and n-level undo capabilities of CSLA .NET in the CSLA Light version.

    I also plan to provide the data portal interface so factory methods can remain consistent, but the back-end implementation will be quite different. (I can't do mobile objects due to no serialization, and I can't do the strongly-typed DP_XYZ calls due to no private reflection). The lack of a real data portal is pretty hard to take, but I haven't figured out a way to do it, so it is probably unavoidable...

    I anticipate that around 80% of the code you'd write in a business object today will be the same in CSLA Light, perhaps even more.

    Thanks to the compatibility between Silverlight and WPF/.NET itself, there are some other interesting possiblities for CSLA Light. Code written for Silverlight should always run in a less restrictive environment like WPF on Windows, or even XBAP/WPF in a browser. Due to this, CSLA Light will almost certainly work in those settings as well.

    In any case, this will be a somewhat slow moving initiative, because I have to wait until Microsoft comes out with a release of Silverlight that supports key WPF features like data binding before I can get too far with the project...

    Tuesday, May 01, 2007 4:25:03 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [8]  | 

     Friday, April 27, 2007

    The third pre-beta test release of CSLA .NET 3.0 is now available for download.

    This release doesn't include any major changes from the previous release, but does include a set of bug fixes and stabilization.

    This release does include an updated ProjectTracker application, which now includes:

    • PTWpf - the almost completed WPF UI for ProjectTracker
    • PTWorkflow - a simple workflow that makes use of CSLA-style objects in the activities
    • WcfPortal - a data portal host for the WCF data portal channel
    • PTWcfService - a WCF service interface, much like the older web service interface
    • PTWcfServiceClient - a Windows Forms client app for PTWcfService

    Plus, of course, all the pre-existing Windows, ASP.NET and web service interfaces and data portal hosts.

    This release is only available in C# at the moment. The WCF data portal channel for VB is complete, and is available directly from the svn repository. I'll port the remainder of the changes to VB once I'm more confident that they are stable (which should be in the relatively near future).

    Friday, April 27, 2007 8:48:44 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [2]  | 

     Tuesday, April 24, 2007

    I am building a WPF UI for my ProjectTracker CSLA .NET sample app. On the whole this is going pretty well, and I anticipate being done within the next couple days. I’ve found and fixed a couple bugs in CSLA – one in BusinessListBase that’s been there forever, and one in ValidationPanel that caused a null reference exception. While I fixed that last one, I optimized the code a bit, which does seem to make the control a bit faster.

    But one thing I spent a ridiculous amount of time on was the simple process of getting a ComboBox control to bind to one data source to get its list of items, and to the business object property for the key value. Google turned up a number of search results, none of which really addressed this particular scenario – which seems odd to me given how common a scenario it is…

    In ProjectTracker, a person (resource) can be assigned to a project. If they are, they are given a role on that project. The Role property is numeric – a key into a name/value list, and a foreign key into the Roles table in the database. In Windows Forms and Web Forms the UI handles translating this numeric value to a human-readable value through ComboBox controls, and obviously WPF can do the same thing. The trick is in figuring out the XAML to make it happen.

    Here’s the ComboBox XAML:

                <ComboBox

                  ItemsSource="{Binding Source={StaticResource RoleList}}"

                  DisplayMemberPath="Value"

                  SelectedValuePath="Key"

                  SelectedValue="{Binding Path=Role}"

                  Width="150" />

     

    Let’s break this down.

    The ItemsSource property specifies the data source for the data that will populate the display of the control. In my case it is referencing a data provider control defined like this:

      <Page.Resources>

        <csla:CslaDataProvider x:Key="RoleList"

                               ObjectType="{x:Type PTracker:RoleList}"

                               FactoryMethod="GetList"

                               IsAsynchronous="False" />

      </Page.Resources>

     

    This data provider control loads a name/value list object called RoleList (that inherits from Csla.NameValueListBase). The child objects in this collection expose properties Key and Value.

    You can see how the ComboBox uses the DisplayMemberPath to specify that the Value property from the name/value list should be displayed to the user, and the SelectedValuePath specifies that the Key value from the list should be used to select the current item (the Key value is not displayed to the user).

    Then notice that the SelectedValue property is used to bind to the main business object. This binding statement sets a path to a property on the overall DataContext for the ComboBox, which in my case is actually set through code at the Page object level:

          this.DataContext = project;

    So all controls on the entire page, by default, bind to a Project object, and this includes the ComboBox.

    Remember though, that the Role property on the Project is a numeric index value. And so is the Key value from the name/value list. The ComboBox control connects these two automatically. So when the business object’s Role property changes, the ComboBox automatically changes the displayed/selected item. Conversely, when the user changes the ComboBox selected item, that automatically causes the business object’s Role property to change.

    Tuesday, April 24, 2007 7:55:13 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [5]  | 

     Thursday, April 19, 2007

    I was out of touch for a while there, and so I couldn't post about this.

    But there's a recent .NET Rocks TV (DNR TV) show where I discuss various data access options for use with CSLA .NET. These include:

    1. Using the approach from my books: the datareader directly in the object
    2. Separating the database connection/command code into a different assembly
    3. Separating the whole data access into a different assembly and using data transfer objects (DTOs) to transfer the data into the business objects
    4. Calling a web service to get the DTOs into the objects (so putting the data access not only in a different assembly, but putting them behind a web service)

    Click here to get to the DNR TV show page. I also showed this demo at VS Live in San Franscisco, and will show it again in Orlando in May.

    Subsequent to that DNR TV show, I've enhanced the demo to also use LINQ to create the DTOs, and to use VB's late binding capability to make it possible to load the business object with data from the local DTO, the web service DTO and the LINQ DTO without any change to code (remember that web service proxies and LINQ create their own DTO types - so even though they are the same shape, they are actually different types - this is exactly where dynamic language features come in very handy!)

    I haven't put the LINQ code online yet, but I will within the next few weeks as I catch up on everything.

    Thursday, April 19, 2007 8:44:40 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

     Monday, March 26, 2007

    I have put an early test version of CSLA .NET version 3.0, along with some updates to the ProjectTracker app online for download at www.lhotka.net/cslanet/download.aspx.

    At this time the code is C# only. I'll port to VB once I'm more comfortable that the code is stable. And that statement alone should reinforce that this is early test code!! :)

    The CSLA framework code includes WCF and WPF support. I have not yet found a case where I've needed to do anything to CSLA itself to support WF - invoking workflows and using CSLA objects in activities works as-is. You can look at the change log document to see what I've done for WCF and WPF.

    The ProjectTracker folder now has a PTWpf project and a PTWorkflow project.

    Neither of these are in the solution! The reason they are not in the solution is because PTWpf is a March 2007 Orcas CTP project, and so it won't load under VS 2005, and PTWorkflow requires the WF additions for VS 2005, which not everyone has installed. To put this another way: if you have the WF additions installed on VS 2005, you can open the workflow project. But to open the PTWpf project you need to be running the March 2007 Orcas CTP.

    That said, if you want to play with the WPF forms under 2005, you can certainly use the xaml and cs files - just grab the bits you need and use them in whatever tool you are using (xamlpad, notepad, the Dec CTP or whatever). The PTWpf project isn't complete, but the ProjectList and ProjectEdit forms both work and illustrate a couple ways to interact with CSLA-style business objects for both read-only and read-write purposes.

    If you do try the 3.0 version, please let me know of any issues you find. I'm actively working on this code, and appreciate any bug reports or other input!

    Monday, March 26, 2007 12:18:02 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [2]  | 

     Thursday, March 15, 2007

    I’ve been spending a lot of time in WPF-land over the past few weeks, and thought I’d share some of what I’ve learned. I haven’t been learning styles or UI layout stuff – Microsoft says that’s the job of the turtleneck-wearing, metrosexual GQ crowd, so I’ll just roll with that. Instead, I’ve been learning how to write data source provider controls, and implement Windows Forms-like behaviors similar to the ErrorProvider and my Csla.Windows.ReadWriteAuthorization control.

    You know, manly programming J

    The data source provider control is, perhaps, the easiest thing I’ve done. Like ASP.NET, WPF likes to use a data control concept. And like ASP.NET, the WPF data provider controls are easy to create, because they don’t actually do all that much at runtime.  (I do want to say thank you to Abed Mohammed for helping to debug some issues with the CslaDataProvider control!)

    I’m sure, as designer support for data provider controls matures in tools like Visual Studio and Expression Blend, that life will get far more complex. Certainly the Visual Studio designer support for Csla.Web.CslaDataProvider has been the single most time consuming part of CSLA .NET, though I was able to create the runtime support in an afternoon…

    What I have today, is a Csla.Wpf.CslaDataProvider control that works similar to the ObjectDataProvider. The primary difference is that CslaDataProvider understands how to call Shared/static factory methods to get your objects, rather than calling a constructor method. The result is that you can create/fetch CSLA .NET business objects directly from your XAML.

    The really cool part of this, is that CslaDataProvider supports asynchronous loading of the data. To be fair, the hard work is done by the WPF base class, DataSourceProvider. Even so, supporting async is optional, and requires a bit of extra work in the control – work that is worth it though. If you construct a form that has multiple DataContext objects for different parts of the form, loading all of them async should give some nice performance benefits overall.

    On the other hand, if your form is bound to a single business object the value isn’t clear at all. Though the data load is async, the form won’t actually display until all the async loads are complete, so for a single data source on a form my guess is that async is actually counter-productive.

    The validation/ErrorProvider support is based on some work Paul Stovell published on the web. I conceptually based my work on similar concepts, and have created a ValidationPanel control that uses IDataErrorInfo to determine if any bindings of any controls contained in the panel are invalid.

    The panel control loops through all the controls contained inside the panel. On each control it loops through the DependencyProperty elements defined for that control (in WPF controls, normal properties aren’t bindable, only dependency properties). And it then loops through any Binding objects attached to each DependencyProperty. I discovered that those Binding objects are complex little buggers, and that there are different kinds of binding that I need to filter out. Specifically relative bindings and control-to-control bindings must be ignored, because they don’t represent a binding to the actual business object.

    To optimize performance the panel does a bunch of caching of binding information, and is relatively sparing in how often it refreshes the validation data – but it is comparable to ErrorProvider, in that changing one business object property does trigger rechecking of all other properties bound within the same ValidationPanel. I think this is necessary, because so many data source objects are constructed around the Windows Forms model. Not following that model would cause a lot of headache when moving to WPF.

    The authorization support is implemented in a manner similar to the validation. Csla.Wpf.AuthorizationPanel uses the CSLA .NET IAuthorizeReadWrite interface and scans all bindings for all controls contained in the panel to see if the business object will allow the current user to read or write to the bound property. If the user isn’t allowed to read the property, the panel either hides or collapses the data bound control (your choice). If the user isn’t allowed to write to the property, the panel sets the control’s IsReadOnly property to true, or if the control doesn’t have IsReadOnly, it sets IsEnabled to false.

    AuthorizationPanel doesn’t include the same level of caching as ValidationPanel, but I don’t think it is necessary. Where ValidationPanel refreshes on every property change, AuthorizationPanel only refreshes if the data source object is changed (replaced) or if you explicitly force a refresh – probably because the current user’s principal object has changed.

    I want to pause here and point out that I’ve had a lot of help in these efforts from Paul Czywczynski. He’s spent a lot of time trying these controls and finding various holes in my logic. And the next control addresses one of those holes...

    The IsValid, IsDirty, IsSavable, IsNew and IsDeleted properties on a CSLA .NET business object are marked as Browsable(false), meaning they aren’t available for data binding. In Windows Forms you can work around this easily by handling a simple event on the BindingSource object. But in WPF the goal is to write no code – to do everything through XAML (or at least to make that possible), so such a solution isn’t sufficient.

    Enter the ObjectStatusPanel, which takes the business object’s properties and exposes them in a way that WPF can consume. Using this panel, your object’s status properties (single object or collection) become available for binding to WPF controls, and if the object’s properties change those changes are automatically reflected in the UI. The most common scenario here is to bind a button’s enabled status to the IsSavable property of your editable root business object.

    Most recently I’ve started refactoring the code in these controls. For the most part, I’ve now consolidated the common code from all three into a base class: Csla.Wpf.DataPanelBase. This base class encapsulates the code to walk through and find relevant Binding objects on all child controls, and also encapsulates all the related event handling to detect when the data context, data object, object property, list or collection have changed. It turns out that a lot of things can happen during data binding, and detecting all of them means hooking, unhooking and responding to a lot of events.

    I wrote all these controls originally using the Dec 2006 CTP, and just started using them in the Mar 2007 CTP. As a pleasant surprise there was no upgrade pain – they just kept working.

    In fact, they work better in the MarCTP, because the Cider designer (WPF forms designer) is now capable of actually rendering my custom controls. What I find very interesting, is that the designer actually runs the factory method of the CslaDataProvider control, so the form shows real data from the real objects right there in Visual Studio. I’m not sure this is a good thing, but that’s what happens.

    There’s no doubt that I’ll find more issues with these controls, and they’ll change over the next few weeks and months.

    But the exciting thing is that I’m now able to create WPF forms that have functional parity with Windows Forms, including validation, authorization and object status binding. And it can all be done in either XAML or code, running against standard CSLA .NET business objects.

    People attending VS Live at the end of this month will be the first to see these controls in action – both in my workshop on Sunday the 25th and in my sessions during the week. And I plan to put a test version of CSLA .NET 3.0 online that week as well, so anyone who wants to play with it can give it a go.

    Right now, if you aren’t faint of heart, you can grab the live code from my svn repository. Keeping in mind, of course, that this is an active repository and so the code in trunk/ may or may not actually work at any given point in time.

    Thursday, March 15, 2007 9:37:24 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [4]  | 

     Friday, March 02, 2007

    Dunn Training has done a great job with the CSLA .NET 3 day training class, and the feedback so far has been very positive!

    Due to the success of the training, Dunn is taking the training on the road, bringing it to a number of cities across the US, including:

    • Boston
    • Minneapolis
    • San Francisco
    • Orlando
    • Washington, DC
    • Dallas
    • Seattle
    • San Diego
    • Las Vegas

    Click here for all the information.

    "I came to this class with two things, a very large problem to solve and a very modest knowledge of CSLA.  What I left with was a solution to the problem using CSLA and enough knowledge to create a prototype on my airplane trip home.  This class was worth every penny and every minute of time.  The instructor, Miguel Castro, was awesome.  DUNN Training Rocks!!"

    Leah Bialic, Cambridge Soft

    "The approach taken with this class was refreshing. Instead of the typical instructor/student environment, I felt like I was in a room of colleagues working together to learn; this was a definite plus.  I rate this class 10 out of 10.  Overall, this class was everything I needed.  Miguel's knowledge and passion for CSLA made it worth every penny."

    Alan Gamboa, CCG Systems

    "This class provides a wonderful, concrete clarification to the CSLA .Net Framework."

    Theo Moore, Magenic

    "This class was a huge help. Definitely money well spent. "

    Chris Williams, Magenic

    Friday, March 02, 2007 3:03:54 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

     Friday, February 23, 2007

    The release version of CSLA .NET version 2.1.4 is now available for download from www.lhotka.net/cslanet/download.aspx.

    This version addresses a set of ongoing issues with the CslaDataSource control for web development. Thanks to Andrés Villanueva, who put in a lot of work, the control is now able to find business types reliably as you rebuild your solution over time. Additionally, you can now put business classes directly in your web project and use them (though I don't encourage this, as it breaks down good layering of your application).

    Other than the changes to CslaDataSource, version 2.1.4 is documented by the CSLA .NET Version 2.1 Handbook available from http://store.lhotka.net, and of course by my Expert C# 2005 Business Objects and Expert VB 2005 Business Objects books.

    Friday, February 23, 2007 10:10:10 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

     Wednesday, February 07, 2007

    I get a lot of questions about the new ADO.NET Entity Framework and LINQ and how these technologies interact with CSLA .NET. I've discussed this in a few other blog posts, but the question recently came up on the CSLA .NET forum and I thought I'd share my answer:

    They are totally compatible, but it is important to remember what they are for.

    Both ADO.NET EF and LINQ work with entity objects - objects designed primarily as data containers. These technologies are all about making it an easy and intuitive process to get data into and out of databases (or other data stores) into entity objects, and then to reshape those entity objects in memory.

    CSLA .NET is all about creating business objects - objects designed primarily around the responsibilities and behaviors defined by a business use case. It is all about making it easy to build use case-derived objects that have business logic, validaiton rules and authorization rules. Additionally, CSLA .NET helps create objects that support a rich range of UI supporting behaviors, such as data binding and n-level undo.

    It is equally important to remember what these technologies are not.

    ADO.NET EF and LINQ are not well-suited to creating a rich business layer. While it is technically possible to use them in this manner, it is already clear that the process will be very painful for anything but the most trivial of applications. This is because the resulting entity objects are data-centric, and don't easily match up to business use cases - at least not in any way that makes any embedded business logic maintainable or easily reusable.

    CSLA .NET is not an object-relational mapping technology. I have very specifically avoided ORM concepts in the framework, in the hopes that someone (like Microsoft) would eventually provide an elegant and productive solution to the problem. Obviously solutions do exist today: raw ADO.NET, , the DAAB, nHibernate, Paul Wilson's ORM mapper, LLBLgen and more. Many people use these various technologies behind CSLA .NET, and that's awesome.

    So looking forward, I see a bright future. One where the DataPortal_XYZ methods either directly make use of ADO.NET EF and LINQ, or call a data access layer (DAL) that makes use of those technologies to build and return entity objects.

    Either way, you can envision this future where the DP_XYZ methods primarily interact with entity objects, deferring all the actual persistence work off to EF/LINQ code. If Microsoft lives up to the promise with EF and LINQ, this model should seriously reduce the complexity of data access, resulting in more developer productivity - giving us more time to focus on the important stuff: object-oriented design ;) .

    Wednesday, February 07, 2007 12:08:20 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [6]  | 

    I have a custom data source control as part of my CSLA .NET framework. It is somewhat like ObjectDataSource, but works with objects that are created through factory methods rather than default constructors (and some other variations).

     

    All is pretty well with this control, except one issue: it fails when adding a CslaDataSource control to a page as a new data source from a DetailsView or other control.

     

    In other words, you add a DetailsView to the page, then tell that control you want it to bind to a new data source and it brings up a wizard, where you pick CslaDataSource so a new one is added to the page.

     

    The problem I’m getting is a VERY odd exception: Csla.Web.CslaDataSource can not be cast to Csla.Web.CslaDataSource.

     

    Yes, that’s right – the type can’t be cast to itself.

     

    I believe this is because the wizard is loading its own copy of Csla.dll into memory, separate from the one used by the web forms designer. Or something like that. This even confuses the debugger – it can’t show details about the type because it says the type is loaded into two different GUIDs. I don’t know what the GUIDs represent (appdomains, versions?), but it is obviously not good.

     

    This is very weird, and after hours of time on this, I’m quite stumped. Any help, clues, pointers or ideas are VERY welcome!

     

    Thanks! Rocky

    Wednesday, February 07, 2007 12:40:18 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [10]  | 

     Sunday, February 04, 2007

    It seems that people are always looking for The Next Big Thing™, which isn’t surprising. What I do find surprising is that they always assume that TNBT must somehow destroy the Previous Big Thing™, which in the field of software development was really object-orientation (at least for most people).

     

    Over the past few years Web Services and then their reincarnation as SOA or just SO were going to eliminate the use of OO. As more and more people have actually implemented and consumed services I think it has become abundantly clear that SOA is merely a repackaging of EAI from the 90’s and EDI from before that. Useful, but hardly of the sweeping impact of OO, at least not in the near term.

     

    Though to be fair, OO took more than 20 years before it became remotely “mainstream”, and even today only around 30% of developers (based on my informal, but broad, polling over the past couple years) apply OOD in their daily work. So you could question whether OO is “mainstream” even today, when the vast majority of developers use procedural programming techniques.

     

    Even though the majority of .NET and Java developers don’t actually use OO themselves, both the .NET and Java platforms are OO throughout. So there’s no doubt that OO has had an incredible impact on our industry, and that it has shaped the major platforms and development styles used by almost everyone.

     

    So perhaps in 15-20 years SO really will have the sweeping impact that OO has had on software development. And I’m not sure that would be a bad thing, but it isn’t a near-term concern.

     

    However, I was recently confronted by a (so-called) newcomer: workflow. Yes, now workflow (WF) is going to kill OO, or so I’ve been told. In fact, Through indirect channels, my challenger suggested that the CSLA .NET framework is obsolete going forward because it is based on these “old-school” OO concepts.

     

    Obviously I beg to differ :)

     

    It is true that some of the concepts I employ in CSLA .NET are quite old, but I am not ready to through OO into the “old-school” bucket just yet... The idea is somewhat ironic however, because WF is being put up as The Next Big Thing™. Depressingly, there's virtually no technology today that isn't a rehash of something from 20 years ago. That's more true of SOA and WF than OO. Remember that SOA is just repacking of message-based architecture, only with XML, and workflow is an extension of procedural design and the use of flowcharts. At least OO can claim to be younger than either of those two root technologies.

     

    Personally, I very much doubt the use of objects as rich behavioral entities will go away any time soon. Sure, for non-interactive tasks procedural technologies like WF might be better than OO (though that's debatable). And certainly for connecting disparate systems you need to use loosely coupled architectures, of which SOA is one (but not the only one).

     

    But the question remains: how do you create rich, interactive GUI applications in a productive and yet maintainable manner?

     

    Putting your logic in a workflow reduces interactivity. Putting your logic behind a set of services reduces both interactivity and performance. Putting your logic in the UI is "VB3 programming". So what's left? For interactive apps you need a business layer that can run as close to the user as possible and using business objects is a particularly good way to do exactly that.

     

    Neither WF nor WCF/SOA are, to me, competitors to CSLA. Rather, I see them as entirely complimentary.

     

    Perhaps ADO.NET EF and/or LINQ are competitors - that depends on what they look like as they stabilize over the next several months. Everything I’ve seen thus far leads me to believe these technologies are complimentary as well. (And Scott Guthrie agrees – check out his recent interview on DNR) Neither of them addresses the issues around support for data binding, or centralization of business logic in a formal business layer.

     

    But when it comes to SOA I still think it is a “fad”. It is either MTS done over with XML - which is what 95% of the people out there are doing with "services", or it is EDI/EAI with XML - which is a good thing and a move forward, but which is too complex and has too much overhead for use in a typical application. I think that most likely in 5-10 years we'll have a new acronym for it – just adding to the EDI/EAI/SOA list.

     

    Just like "outsourcing" became ASP which became SaaS. The idea doesn't die, it just gets renamed so more money can be made by selling the same stuff over again - often to people who really don't need/want it.

     

    The point is, our industry is cyclical. And we're heading toward into a period where "procedural programming" is once again reaching a peak of usage. This time under the names SOA and workflow. But if you step back from the hype and look at it, what's proposed is that we create a bunch of standalone code blocks that exchange formatted data. A set of procedures that exchange parameters. Dress it up how you like, that's what is being proposed by both the SOA and WF crowds.

     

    And there's nothing wrong with that. Procedural design is well understood.

     

    And it could actually work this time around if we don't cheat. I still maintain that the reason procedural programming "failed" was because we cheated and used common blocks and global variables. Why? Because it was too inefficient and required too much code to formally package up all the data and send it as parameters.

     

    If we can stomach the efficiency and coding costs this time around - packing the data into XML messages - then I see no reason why we can't make procedural programming work in many cases. And by naming it something trendy, like SOA and/or workflow, we can avoid the negative backlash that would almost certainly occur if people realized they were abandoning OO to return to procedural programming.

     

    Having spent the first third of my career doing procedural programming, I wouldn't necessarily mind going back. In some ways it really was easier than using objects - though there are some very ugly traps that people will have to rediscover again on this go-round. Most notably the trap that a procedure can't be reused without introducing fragility into the system, not due to syntactic coupling or API changes, but due to semantic coupling (about which I've blogged).

     

    This is true for procedures and any other "reusable" code block like a workflow activity or a service. They all suffer the same limitation - and it is one that neither WSDL nor compilers can help solve...

     

    Anyway, kind of went on a rant here - but I find it amusing that, in some circles at least, OO is viewed as the "legacy" technology in the face of services or workflow, which are even more legacy than OO ;)

    Sunday, February 04, 2007 1:03:57 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [13]  | 

     Thursday, February 01, 2007

    Dunn Training has scheduled the next CSLA .NET class for Feb 26-28 in Atlanta. Feedback from the classes thus far has been very positive, for example:

    From Dave Boal from Denver, CO:

    I need to thank you once again for getting me committed to CSLA. I have always been interested in CSLA, but in the past, never actually made it to the point of applying the technology. I have never took the time required to understand, let alone evaluate the technology. Your course and enthusiasm, combined with chapters 6-8 of Rocky's book, burst me through this evaluation barrier in just 7 days, something I did not think was possible in less than 3 months.

    If you want to get a quick, solid, start using CSLA .NET I recommend you consider Dunn Training's class.

    Thursday, February 01, 2007 9:14:41 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

     Tuesday, January 30, 2007

    The CSLA .NET Version 2.1 Handbook is available NOW at http://store.lhotka.net for both C# and VB.

    Additionally, version 2.1.3 of CSLA .NET is now available for download from this location.

    Version 2.1.3 includes some bug fixes and minor enhancements. The enhancements are primarily around the CslaDataSource web control, which now provides more integrated support for paging and sorting.

    Most importantly, version 2.1.3 is the specific version described in my CSLA .NET Version 2.1 Handbook. I am releasing this as a ~160 page ebook, available in editions for both C# and VB, for purchase directly from my web site.

    This new book is best thought of as a sequel to my my Expert C# 2005 Business Objects and Expert VB 2005 Business Objects books. It covers the changes made since CSLA .NET 2.0 was released: how the framework has changed, and how to use the new features and capabilities. Please note that this is not a replacement for those books: it expands on them.

    I hope you enjoy CSLA .NET 2.1.3, and the new book. Thank you, code well, have fun!

    Tuesday, January 30, 2007 10:14:36 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [12]  | 

    Thanks to a lot of work by fellow Magenic consultant Chuck Macomber, my CSLA .NET code is now in Subversion (svn) rather than in cvs. Thank you Chuck!!

    I'm told that svn offers many advantages over cvs. Just at the moment all I see are the differences where I need to learn and adjust, but that will pass :)

    I've left cvs alive for the moment, but Chuck was able to port all the history into svn, so once things get settled I should be able to entirely drop cvs.

    The svn repository is at svn://svn.lhotka.net/csla, and it should be open for anonymous read. As with cvs, I'm allowing anyone to read the contents of the respository.

    Also, the web viewer (www.lhotka.net/cslacvs) remains alive, but now defaults to using the svn repository. The cvs repository is still visible there too, just use the drop-down in the upper right-hand corner of the page to switch to it. One known issue at this time, is that the diff function doesn't work in svn. I don't know why, but python seems unable to find the diff program under svn, though it works fine under cvs.

    If you have any idea how to solve this diff issue, I'm all ears. Google, thus far, has been of little value... (I am now guessing the diff issue was a caching problem, because it simply started working all by itself... Gotta love web development...)

    Going forward, all changes to CSLA .NET will occur in the svn repository.

    Tuesday, January 30, 2007 12:43:13 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [3]  | 

     Thursday, January 25, 2007

    Version 2.1.2 of CSLA .NET is now available for download from this location.

    Version 2.1.2 includes some bug fixes and minor enhancements. The enhancements are primarily around the CslaDataSource web control, which now provides more integrated support for paging and sorting.

    Most importantly, version 2.1.2 is the specific version described in my CSLA .NET Version 2.1 Handbook. I am releasing this as a ~160 page ebook, available in editions for both C# and VB, for purchase directly from my web site.

    The VB CSLA .NET Version 2.1 Handbook is available NOW at http://store.lhotka.net.

    Look for the C# edition in the very near future (it is in the final review stage).

    This new book is best thought of as a sequel to my Expert C# 2005 Business Objects and Expert VB 2005 Business Objects books. It covers the changes made since CSLA .NET 2.0 was released: how the framework has changed, and how to use the new features and capabilities. Please note that this is not a replacement for those books: it expands on them.

    Releasing this as an ebook in PDF format is a risk on my part. I put just as much time and effort into writing this book as I have any other book I've written, but I want to provide a more cost-effective way for you to purchase this material than through normal publishing channels. It is my sincere hope that you will purchase this book if you read it (even after a few people have purchased it and they start sharing it for free).

    I'm not giving up on traditional publishing channels necessarily. I'll most likely use a traditional publishing approach when I reach a point that CSLA .NET and/or my thinking changes to such a degree that there'd be value for you, as a reader, in me rewriting my books in a major way. But when I'm writing about extra functionality that rests on the existing work, it seems like I'm providing better value to you by selling a lower-cost sequel than forcing you to repurchase much of the same material to get at the new parts.

    But all this hinges on people's honesty. On your honesty.

    I hope you enjoy CSLA .NET 2.1.2, and the new book. Thank you, code well, have fun!

    Thursday, January 25, 2007 6:20:05 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [6]  | 

     Tuesday, January 09, 2007

    Here's an issue from Windows Forms that appears to have crept into WPF as well – along with a solution (thanks to Sam Bent and Kevin Moore from the WPF team):

     

    Consider a class with a property that enforces a business rule - such as that the value must be all upper case:

     

    public class Test : INotifyPropertyChanged

    {

      public event

        System.ComponentModel.PropertyChangedEventHandler

        PropertyChanged;

      // ...

     

      private string _data;

     

      public string Data

      {

        get

        {

          return _data;

        }

        set

        {

          _data = value.ToUpper();

          OnNotifyPropertyChanged("Data");

         }

      }

    }

     

    Bind this to a TextBox and type in a lower-case value. The user continues to see the lower-case value on the screen, even though the object obviously has an upper-case value. The PropertyChanged event is blissfully ignored by WPF data binding.

     

    I believe this is the same "optimization" as in Windows Forms, where the assumption is that since the value was put into the object by data binding that it can’t be different from what's on the screen - so no refresh is needed. Obviously that is a unfortunate viewpoint, as it totally ignores the idea than an object might be used to centralize business logic or behavior...

     

    In Windows Forms the solution to this issue is relatively simple: handle an event from the BindingSource and force the BindingSource to refresh the value. Bill McCarthy wrapped this solution into an extender control, which I included in CSLA .NET, making the workaround relatively painless.

     

    In WPF the solution is slightly different, but also relatively painless.

     

    It turns out that this optimization doesn’t occur if an IValueConverter is associated with the binding, and if the binding’s UpdateSourceTrigger is not PropertyChanged.

     

    For the TextBox control the UpdateSourceTrigger is LostFocus, so it is good by default, but you’ll want to be aware of this property for other control types.

     

    An IValueConverter object’s purpose is to format and parse the value as it flows to and from the target control and source data object. In my case however, I don’t want to convert the value at all, I just want to defeat this unfortunate “optimization”. What’s needed is an identity converter: a converter that does no conversion.

     

    namespace Csla.Wpf

    {

      public class IdentityConverter : IValueConverter

      {

        #region IValueConverter Members

     

        public object Convert(

          object value, Type targetType,

          object parameter, System.Globalization.CultureInfo culture)

        {

          return value;

        }

     

        public object ConvertBack(

          object value, Type targetType,

          object parameter, System.Globalization.CultureInfo culture)

        {

          return value;

        }

     

        #endregion

      }

    }

     

    Just configure this in your XAML:

     

    <Page x:Class="PTWpf.ProjectEdit"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        xmlns:csla="clr-namespace:Csla.Wpf"

        Title="Project Edit"

        >

      <Page.Resources>

        <csla:IdentityConverter x:Key="IdentityConverter" />

      </Page.Resources>

    ...

      <TextBox Text="{Binding Data, Converter={StaticResource IdentityConverter}}"></TextBox>

    ...

     

    Just like that, it all works as expected and the value from the object is reflected in the UI.

    Tuesday, January 09, 2007 3:08:23 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

     Wednesday, January 03, 2007

    I recently received an email that included this bit:

     

    “You are killing me. I wrote a rather scathing review of your Professional Business Objects with C# on Amazon.com and on my own blog. However, recently I read a transcription of an ARCast with Ron Jacobs where you talked about business objects. I believe I agreed with everything you said. What are you trying to do to me?

     

    I am just a regular shmoe developer, who preaches when listened to about the joys and benefits of OO design for the common business application. I feel too many develop every application like it is just babysitting a database. Every object’s purpose is for the CRUD of data in a table. I have developed great disdain for companies, development teams, and senior developers who perpetuate this problem. I felt Expert C# 2005 Business Object perpetuates this same kind of design, thus the 3 star rating on Amazon for your book.

     

    In the ARCast you mentioned a new book coming out. I am hoping it is the book I have been looking for. If I wrote it myself it would be titled something like, “Business Objects in the Real World.” It would address the problems of data-centric design and how some objects truly are just for managing data and others conduct a business need explained by and expert. These two objects would be pretty different and possibly even use a naming convention to explicitly differentiate the two. For example I don’t want my “true” business objects with getters, setters, isDirty flags or anything else that might make them invalid and popping runtime errors when trying to conduct their business.

     

    Anyway, I could ramble on (It’s my nature). However, I just want to drop you a line and say there is a real disconnect between us, but at the same time, I wanted to show everyone at my office what you were saying in your interview. You were backing me up! However, just months ago I was using your writings to explain what is wrong with software development. We seem to be on the same page, or close anyway, but maybe coming to different conclusions. I guess that’s what is bothering me.”

     

    The following is my response, which I thought I’d share here on my blog because I ended up rambling on more than I’d planned, and I thought it might be interesting/useful to someone:

     

    I would guess that the disconnect may flow from our experiences during our careers - what we've seen work and not work over time.

     

    For my part, I've become very pragmatic. The greatest ideas in the world tend to fall flat in real life because people don't get them, or they have too high a complexity or cost barrier to gain their benefit. For a very long time OO itself fit this category. I remember exploring OO concepts in the late 80's and it was all a joke. The costs were ridiculously high, and the benefits entirely theoretical.

     

    Get into the mid-90's and components show up, making some elements of OO actually useful in real life. But even then RAD was so powerful that the productivity barrier/differential between OO and RAD was ridiculously high. I spent untold amounts of time and effort trying to reconcile these two to allow the use of OO and RAD both - but with limited success. The tools and technologies simply didn't support both concepts - at least not without writing your own frameworks for everything and ignoring all the pre-existing (and established) RAD tools in existence.

     

    Fortunately by this time I'd established both good contacts and a good reputation within key Microsoft product teams. Much of the data binding support in .NET (Windows Forms at least) is influenced by my constant pressure to treat objects as peers to recordset/resultset/dataset constructs. I continue to apply this pressure, because things are still not perfect - and with WPF they have temporarily slid backwards somewhat. But I know people on that team too, and I think they'll improve things as time goes on.

     

    In the meantime Java popularizes the idea of ORM - but solutions exist for only the most basic scenarios - mapping table data into entity objects. While they claim to address the impedance mismatch problem, they really don't, because they aren't mapping into real OO designs, but rather into data-centric object models. Your disdain for today’s ORM tools must be boundless J

     

    For better or worse, Microsoft is following that lead in the next version of ADO.NET - and I don't totally blame them; a real solution is complex enough that it is hard to envision, much less implement. However, here too I hold out hope, because the current crop of "ORM" tools are starting to create nice enough entity objects that it may become possible to envision a tool that maps from entity objects to OO objects using a metadata scheme between the two. This is an area I've been spending some time on of late, and I think there's some good potential here.

     

    Through all this, I've been working primarily with mainstream developers (“Mort”). Developers who do this as a job, not as an all-consuming passion. Developers who want to go home to their families, their softball games, their real lives. Who don't want to master "patterns" and "philosophies" like Agile or TDD; but rather they just want to do their job with a set of tools that help them do the right thing.

     

    I embrace that. This makes me diametrically opposed to the worldviews of a number of my peers who would prefer that the tools do less, so as to raise the bar and drive the mainstream developers out of the industry entirely. But that, imo, is silly. I want mainstream developers to have access to frameworks and tools that help guide them toward doing the right thing - even if they don't take the time to understand the philosophy and patterns at work behind the scenes.

     

    I don't remember when I did the ARCast interview, but I was either referring to the 2005 editions of my business objects books which came out in April/May, or to the ebook I'm finishing now, which covers version 2.1 of my CSLA .NET framework. Odds are it is the former, and it isn't the book you are looking for - though you might enjoy Chapter 6.

     

    In general I think you can take a couple approaches to thinking about objects.

     

    One approach, and I think the right one, is to realize that all objects are behavior-driven and have a single responsibility. Sometimes that responsibility is to merely act as a data container (DTO or entity object). Other times it is to act as a rich binding source that implements validation, authorization and other behaviors necessary to enable the use of RAD tools. Yet other times it is to implement pure, non-interactive business behavior (though this last area is being partially overrun by workflow technologies like WF).

     

    Another way to think about objects is to say there are different kinds of object, with different design techniques for each. So entity objects are designed quasi-relationally, process objects are designed somewhat like a workflow, etc. I personally think this is a false abstraction that misses the underlying truth, which is that all objects must be designed around responsibility and behavior as they fit into a use case and architecture.

     

    But sticking with the pure responsibility/behavior concept, CSLA .NET helps address a gaping hole. ORM tools (and similar tools) help create entity objects. Workflow is eroding the need for pure process objects. But there remains this need for rich objects that support a RAD development experience for interactive apps. And CSLA .NET helps fill this gap by making it easier for a developer to create objects that implement rich business behaviors and also directly support Windows Forms, Web Forms and WPF interfaces – leveraging the existing RAD capabilities provided by .NET and Visual Studio.

     

    Whether a developer (mis)uses CSLA .NET to create data-centric objects, or follows my advice and creates responsibility-driven objects is really their choice. But either way, I think good support for the RAD capabilities of the environment is key to attaining high levels of productivity when building interactive applications.

    Wednesday, January 03, 2007 10:40:32 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [3]  | 

    In November Dunn Training held the first ever official CSLA .NET three day class. It was a smashing success, and resulted in a lot of great feedback and comments. Here are a couple quotes from attendees of the November class:

    "At first, I was not sold on the need for CSLA.  After attending this class and seeing the examples and proof, I'm on the bandwagon.  This class proved the usefulness of CSLA and sold me on giving up writing all the plumbing myself."

    "Miguel and Mark have provided one of the best ways to get up to speed using CSLA."

    "The best career enhancing training investment I have made in the last 10 years.  Rocky is lucky to have the DUNN team doing this training.  Great stuff - solid, professional and accurate."

    The next class is coming up soon: January 29-31, in Atlanta, GA. If you are looking for three days of intense and practical CSLA .NET training this is your chance!

    Wednesday, January 03, 2007 9:41:47 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

     Tuesday, January 02, 2007

    I you had a good holiday season and enjoyed the end of 2006!

     

    For my part, I want to thank everyone who contributed to the CSLA .NET forums, and to the CSLAcontrib project. The time and energy you have all put in over the past few months has been a great help to the CSLA .NET community, and I know there are many people out there who are grateful for your efforts!

     

    Most importantly though, I want to thank all the users of CSLA .NET and everyone who has purchased copies of my books. At the end of the year I received numerous emails thanking me for creating the framework (and I appreciate that), but I seriously want to thank all of you for making this a vibrant community. CSLA .NET is one of the most widely used development frameworks for .NET, and that is because each of you have taken the time to learn and use the framework. Thank you!

     

    For me 2006 was a year of change. Starting with CSLA .NET 2.0 I've been viewing CSLA .NET as not just an offshoot of my books, but as a framework in its own right. Of course many people have been treating it that way for years now, but I hope it has been helpful to have me treat point releases a bit more formally over the past number of months.

     

    This extends to version 2.1, which represents an even larger change for me. With version 2.1 I'm releasing my first self-published ebook to cover the changes. This ebook is not a standalone book, rather it is best thought of as a "sequel" to the 2005 book. However, it is well over 150 pages and covers both the changes to the framework itself, as well as how to use the changes in your application development. The ebook is undergoing technical review. That and the editing process should take 2-3 weeks, so the ebook will be available later this month.

     

    Looking at the rest of 2007 it is clear that I'll be spending a lot of time around .NET 3.0 and 3.5.

     

    I'll be merging the WcfChannel into CSLA .NET itself, as well as implementing support for the DataContract/DataMember concepts. This, possibly coupled with one WPF interface implementation for collections, will comprise CSLA .NET 3.0.

     

    It is not yet clear to me what changes will occur due to .NET 3.5, but I expect them to be more extensive. Some of the new C#/VB language features, such as extension methods and lambda expressions, have the potential to radically change the way we think about interacting with objects and fields. When you can add arbitrary methods to any type (even sealed types like String) many interesting options become available.

     

    Then there's the impact of LINQ itself, and integration with the ADO.NET Entity Framework in one manner or another.

     

    ADO EF appears, at least on the surface, to be YAORM (yet another ORM). If that continues to be true, then it is a great way to get table data into data entities, but it doesn't really address mapping the data into objects designed around use cases and responsibility. If you search this forum for discussions on nHibernate you'll quickly see how ADO EF might fit into the CSLA .NET worldview just like nHibernate does today: as a powerful replacement for basic ADO.NET and/or the DAAB.

     

    LINQ is potentially more interesting, yet more challenging. It allows you to run select queries across collections. At first glance you might think this eliminates the need for things like SortedBindingList or FilteredBindingList. I’m not sure that’s true though, because the result of any LINQ query is an IEnumerable<T>. This is the most basic type of list in .NET; so basic that the result must often be converted to a more capable list type.

     

    Certainly when you start thinking about n-level undo this becomes problematic. BusinessBase (BB) and BusinessListBase (BLB) work together to implement the undo capabilities provided by CSLA .NET. Running a LINQ query across a BLB results in an IEnumerable<T>, where T is your BB-derived child type. At this point you’ve lost all n-level undo support, and data binding (Windows Forms, and any WPF grid) won’t work right either.

     

    So at the moment, I’m looking at LINQ being most useful in the Data Access Layer, along with ADO EF, but time will tell.

     

    The point of all this rambling is this: I didn’t rush CSLA .NET 1.0 or 2.0. They came out when I felt I had good understanding of the issues I wanted to address in .NET 1.0 and .20 respectively. And when I felt I had meaningful solutions or answers to those issues. I’m treating .NET 3.5 (and presumably CSLA .NET 3.5) the same way. I won’t rush CSLA .NET to meet an arbitrary deadline, and certainly not to match Microsoft’s release of .NET 3.5 itself. There’s no point coming out with version of CSLA .NET that misses the mark, or that provides poor solutions to key issues.

     

    So in 2007 I’ll most certainly be releasing the version 2.1 ebook and CSLA .NET 3.0 (probably with another small ebook). Given that Microsoft’s vague plans are to have .NET 3.5 out near the end of 2007, I don’t expect CSLA .NET 3.5 to be done until sometime in 2008; but you can expect to see beta versions and/or my experiments around .NET 3.5 as the year goes on.

     

    Of course I’ll be doing other things beyond CSLA .NET in 2007. I’m lined up to speak at the SD West and VS Live San Francisco conferences in March. I’m speaking in Denver and Boulder later in January, and I’ll be doing other speaking around the country and/or world as the year goes on. Click here for the page where I maintain a list of my current speaking engagements.

     

    To close, thank you all for your support of the CSLA .NET community, and for your kind words over the past many months. I wish you all the best in 2007.

     

    Code well, have fun!

     

    Rocky

    Tuesday, January 02, 2007 9:52:48 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

     Wednesday, December 13, 2006

    I thought it would be a good idea to give a quick update on the progress/status of the CSLA .NET version 2.1 ebook. Version 2.1 includes some substantial new features and changes as compared to version 2.0, and I am working on an ebook (about 150 pages) that I'll be selling through my web site in the near future. This ebook covers those changes to the framework, both from the framework development perspective and from the perspective of someone who just wants to use the new or changed features.

    My original intent was for the ebook to be done in November. Obviously that hasn't happened, though I am very near completion of the book at this point - in the middle of December. There are many reasons for the delay, most notably some serious family health issues (which, unfortunately, are ongoing) and unexpected activities at work (I have a real job in addition to writing ebooks :) ). Those pushed things far enough into November that a number of other, planned, things impacted the schedule as well.

    I really didn't expect this project to be this big - I was thinking 75 pages, but it is more like 150. And self-publishing turns out to be more work than I'd thought. Fortunately, a colleague at Magenic is helping to do the technical review and my very talented wife is doing all the non-technical editing. Another Magenic colleague is kindly setting up the online store. And I found out from my tax guy that I need to get a sales tax ID from Minnesota because I have to actually collect sales tax on the ebook - much to my surprise.

    Regardless, what this means is that I now expect the ebook to be available for purchase within the first two weeks of 2007. I'm wrapping up the VB version this week, doing technical revisions and final editing and creating the C# version (swapping in different code bits) over the next couple weeks. This should mean the project is done by the end of the year so I can put it online very early in 2007.

    Wednesday, December 13, 2006 9:35:06 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [3]  | 

     Thursday, November 16, 2006

     CSLA .NET 2.1.1 is now available for download from the download page. This is a bug fix release, which addresses some issues in version 2.1. See the change log for details.

    Thursday, November 16, 2006 4:04:09 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [3]  | 

     Tuesday, October 17, 2006
    Dunn Training is now offering the first ever formal training for CSLA .NET. The beta class is November 20-22, and it is being held in Chattanooga, TN. The advantage to the beta class, is that it is heavily discounted, because it is the first public run of the materials, so this is the one chance to get heavily discounted CSLA .NET classroom training.

    The plan is for regular classes to start in early 2007.

    I've been working with Miguel Castro as he builds the content for the course, and this training should be a great way to get rolling fast with CSLA .NET.

    Tuesday, October 17, 2006 9:20:09 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

     Monday, October 16, 2006
    I recently participated in a panel discussion on open source software, which was recorded as a MSDN Webcast.

    Scott Hanselman even has a picture of the event.

    Though people might argue whether CSLA .NET is really "open source" (because it has a non-viral license), it is certainly the case that its source code is open for all to see and use with almost no restrictions. If you listen to the panel, you'll find that there's a strong belief by many of us in this space that open source is an important and valuable part of the software industry; and you'll find that many of us also believe that software development should lead (directly or indirectly) to being able to make a living. This leaves a delicate middle ground, which can be challenging in many ways.

    Monday, October 16, 2006 6:50:36 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

     Saturday, September 30, 2006

    CSLA .NET version 2.1 is now available for download from www.lhotka.net/cslanet/download.aspx

    Please make sure to read the Change log for this release, as there are substantial changes to validation, authorization and other parts of the framework. There are a limited number of breaking changes that may affect your code, so please review the document before attempting to upgrade from 2.0 to 2.1.

    The vast majority of the changes in version 2.1 are due to the community feedback from the great members of the online forum. I would like to thank everyone who provided feedback and input into the process!

    Saturday, September 30, 2006 11:20:17 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [3]  | 

     Tuesday, September 26, 2006
    Dunn Training continues to ready its official CSLA .NET training course, with plans for a beta of the course to be taught in November.

    http://www.dunntraining.com/CSLATraining.htm

    If you are in need of some classroom training on CSLA .NET, November is your first chance, probably followed by a class in January.
    Tuesday, September 26, 2006 8:33:13 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

     Friday, September 22, 2006
    Thanks to a lot of work by Chris Russi, there is now an official CSLA .NET logo graphic:



    and a corresponding "Powered by" logo for web sites or applications that are built on CSLA .NET:




    Note that the CSLA .NET license does not require any public display of this logo! But if you would like to use it to let people know that your application or site is built using CSLA .NET, that's wonderful! :)

    Chris very kindly created a range of different sizes, and you can download the entire set in one zip file.
    Friday, September 22, 2006 3:05:34 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [7]  | 

     Tuesday, September 12, 2006

    I just updated the download page (www.lhotka.net/cslanet/download.aspx) to make the BETA version of CSLA .NET 2.1 available.

    Make sure you read the Change Log document before going too far. I've tried to list all breaking changes as a summary at the top, with my estimate on the likely impact of each one. You can find more details further into the document.

    There will be no more functional changes to 2.1, so this download is complete. There obviously could be bugs, but enough people have been helping me find issues with the last couple pre-releases that I think it is pretty stable at this point.

    Barring anyone finding a major issue, I am still planning to release 2.1 by the end of September, so if you have any near-term plans to use 2.1 I strongly recommend trying this beta version on a non-production copy of your project over the next 10 days or so. That will allow you to provide me with any bug reports in enough time that I can try and address them.

    Tuesday, September 12, 2006 8:18:19 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [3]  | 

     Thursday, September 07, 2006

    I get many questions about CSLA .NET, and whether it is a good fit for various projects and needs. Many times I put the answers on my web site - building a FAQ of sorts. Here are some links to good articles there, and a copy of a Q&A I recently did for a prospective Magenic client.

    What is CSLA .NET?

    CSLA .NET technical requirements

    Why move from CSLA .NET 1.x to 2.x?

    CSLA .NET Roadmap

    CSLA .NET 2.0 download page (which includes a summary of breaking changes)

    CSLA .NET 2.0 change log (detailed list of changes from version 1.5)

    Now for the recent Q&A:

    What are the drawbacks to using the CSLA?

    This question is too vague to be answered directly. No framework is perfect for all types of application, and CSLA .NET is no exception.

    It is not particularly useful for creating non-interactive batch processing code - the .NET 3.0 WF technology is a better bet there. (though the activities in a WF can be created using CSLA, and that's a great model that the WF team really likes)

    It is also not particularly useful for reporting. A good reporting tool like SQL Reporting Services is the right answer.

    CSLA does require the use of good OO design. Where the DataSet works well (best?) when using VB3 style code-in-the-form architecture, CSLA really requires the application of OO design to build a true business layer. For some developers this can be a hurdle, because they are not used to doing OO design.

    CSLA also has some technical requirements. Depending on the transaction model you use, the DTC may be required. In all cases CSLA requires FullTrust code access security, so it can't be used in a partial trust environment (like on most commercially hosted web servers).

    Where do the CSLA and the Enterprise Library overlap?

    They don't. They are complimentary, see this article for details.

    What is the roadmap for the CSLA?

    CSLA .NET is a framework for creating a reusable, object-oriented business layer for .NET applications. As such, it continues to evolve based on the evolution of the .NET platform. This means its roadmap generally follows Microsoft's lead, with some exceptions around enhancements to CSLA itself. At the moment the roadmap looks like this:

    Version 2.0      - available now for .NET 2.0 and VS 2005

    Version 2.1      - available Q3-06 with performance and feature enhancements

    Version 3.0 (?) - available Q1-07 with full support for .NET 3.0 (WCF, WPF, WF)

    Version 3.x      - available Q?-07 with support for .NET 3.5 (LINQ technologies)

    Obviously the 3.x schedules are subject to change based on Microsoft's schedule.

    (updated road map can be found here)

    What is the model for integrating the CSLA with .NET 3.0\Windows Communication Foundation?

    I am working closely with the Connected Systems group in Redmond on this, and related technologies. Additionally, when I build CSLA .NET 2.0 I specifically designed it to allow for near-seamless integration of WCF.

    Right now you can get an early version of a data portal channel for WCF from here.

    This allows existing applications using Remoting, Web Services or Enterprise Services to transition to WCF with NO CODE CHANGES. This is a very compelling feature of CSLA in my view.

    Unfortunately that's not the whole story, and that's why a new version of CSLA will be required in the .NET 3.0 timeframe. CSLA uses the BinaryFormatter for some scenarios (n-level undo, cloning). To support the DataContract model, the NetDataContractSerializer is required instead, so the formatter needs to be pluggable. Again, I've been working with the PM who owns serialization, and this is not a major change to CSLA, and other than there being a new configuration switch this change should have NO IMPACT ON ANY APPLICATION CODE.

    How is the CSLA supported in production environments?

    CSLA is not a "product". I don't sell it, nor do I sell support for it. CSLA is part of my Expert VB/C# 2005 Business Objects books, and is covered under a very liberal, essentially open-source, license

    www.lhotka.net/cslanet/license.aspx

    As such, support in a production environment is the responsibility of the organization using the framework.

    What is the typical model for extending\enhancing the CSLA so that one can take advantages of new versions and migrate the custom enhancements easily to the new CSLA runtime?

    CSLA is designed to include numerous extensibility points, allowing organizations to customize the behavior of key functionality without altering the core framework. This is most often handled through inheritance, where an organization inherits from a CSLA base class to create their own custom base class that extends or alters the core CSLA behavior. In other cases a provider model is used to allow organizations to replace pre-supplied providers with their own custom providers.

    What Application Service Provider and\or 24x7x365 customer references exist for CSLA implementations?

    Magenic can provide various case studies around their implementation of projects using CSLA .NET.

    For my part, since I don't sell CSLA, I can't fund the process necessary to go through the legal hoops at most organizations to release their names as references. I do maintain this list of organizations who use CSLA. I can say that the framework is used in a wide range of applications, from small to very large and mission critical.

    Also, here are some unsolicited quotes from CSLA .NET users:

    "A day doesn't go by without me marveling at how elegant this CSLA is."

    "Rocky, I learned so much from your books. They had enlightened me on true OO practice, including David West's Object Thinking that you recommend. Thank you."

    "First, a huge thank you for an awesome business object framework. I've learned so much just by stepping through your code."

    "Having single handedly completed a rather major WinForms app, which has now been in operation for over a year at several sites, I can tell you that you absolutely cannot go wrong choosing CSLA."

    "I'd like to say that you did a great job on CSLA. I've found it very helpful in the creation of standardly developed and maintainable code among our teams."

    Are there any Visual Studio 2005 project templates available for using the CSLA within VS2005?

    CSLA includes a set of snippets and class templates for each object stereotype. Even more importantly, in my view, there are several code-generation templates available for CodeSmith and other code generators, and Kathleen Dollard's book on .NET code generation also includes a CSLA code generator. Additionally, Magenic has a very powerful and extensible code generator that we often use on CSLA projects.

    While project and file templates offer some short-term productivity, properly implemented code generation provides increased productivity over the lifetime of the entire project and should be a requirement for any large initiative (CSLA based or not).

    Thursday, September 07, 2006 9:31:32 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

     Thursday, August 10, 2006
    Yesterday I recorded two more DNR TV shows on CSLA .NET with Carl Franklin, so watch for those to go online in the next few weeks. Carl does a nice job of editing the recordings and cleaning up the audio, so it takes some time between recording and "airing", but it is well worth it!

    Thursday, August 10, 2006 1:57:00 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [9]  | 

     Wednesday, July 26, 2006

    Some exciting news! Dunn Training is building a formal training class around CLSA .NET, with plans for the class to be ready in September. I often get requests for CSLA .NET training, and now there'll be a great answer.

    Of course Magenic remains the premier source for consulting and mentoring around CSLA .NET. Training is important, but you can't underestimate the value of longer term mentoring!

    Given the combination of my books, a formal CSLA .NET class and longer term mentoring and consulting from Magenic, a full array of CSLA .NET resources is coming into being.

    And while I'm plugging Dunn Training, I should mention that they have an excellent BizTalk Server 2006 class - just tell them that Rocky sent you :)

    Update: Here is a link to the information page on the CSLA .NET class.

    Wednesday, July 26, 2006 11:56:44 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

     Tuesday, July 18, 2006

    Over the past few years the community around my CSLA .NET framework has become very large and very active. Recently the online forum for CSLA .NET, which is the center of the community in many ways, moved to a new home: http://forums.lhotka.net.

    Just this week another community effort has become reality: CSLAcontrib. CSLAcontrib is a "project of projects" into which the community can contribute tools, templates and add-ons for CSLA .NET. I assume no ownership over anything on CSLAcontrib - this is a pure community effort.

    This community effort has my full support, and the people involved have my gratitude. I find the community efforts around CSLA .NET to be both humbling and inspiring, and I appreciate each and every person who takes the time to get involved! Thank you!

    CSLAcontrib is hosted on Microsoft's CodePlex site: http://www.codeplex.com/Wiki/View.aspx?ProjectName=CSLAcontrib, and operates under an open-source license.

    The goal of CSLAcontrib is to provide a clear, powerful and friendly home for all the wonderful community contributions around CSLA .NET. There are many existing contributions out there, some of which can benefit by having a more visible home. Others were hosted on gotdotnet, and CodePlex offers a far superior environment in terms of performance, stability and ease of use.

    But I think this is just the tip of the iceberg. CSLA .NET 2.0 has some interesting extensibility points, including common validation rule methods, data portal channels, and sub-classes of the six core base classes. I think it would be very interesting and useful to see more advanced and powerful validation rule methods in particular. And a colleague of mine had, at one point, suggested building a data portal channel that ran over an IM protocol :-)

    So if you are looking for a way to contribute your cool tool, template or add-on, CSLAcontrib is a great option. If you are looking to use some great tools, templates or add-ons for CSLA .NET, CSLAcontrib should become the go-to place.

    Tuesday, July 18, 2006 8:54:10 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

     Friday, July 14, 2006

    CSLA .NET version 2.0.3 is now available for download at www.lhotka.net/cslanet/download.aspx. This is a bug fix update to address various errata and issues that readers have found since version 2.0.2.

    Most notably, this version (hopefully) fixes the issues with CslaDataSource, where it would sometimes fail to find the business assembly. Please note that the type name is case-sensitive and typos are now the primary reason the type/assembly can't be found.

    To give you some idea what's going on with CslaDataSource, here's the short story:

    In CSLA .NET 2.0 (and in the books), I implemented CslaDataSource so it loaded the business assembly at design time (in VS 2005) to get the assembly's metadata. The metadata is needed for the web forms designer so the GridView and DetailsView controls can show the right columns/rows. And that worked, but had the problem that changes to the business assembly during development weren't picked up by CslaDataSource.

    In 2.0.1 I altered CslaDataSource to load the business assembly in a temporary AppDomain. That allows me to unload the AppDomain and thus unload the assembly - so CslaDataSource can always reflect against the latest assembly. Which is a great idea, except that there's no supported (or even unsupported really) way to find the current business assembly. It turns out that VS 2005 puts the assemblies into a shadow directory, creating a new shadow directory each time you build your project or update an external assembly. To work around this, I am doing a sort of hack by inferring the shadow directory location and then finding the most recently created shadow directory (by date/time).

    Now, in 2.0.3 I altered CslaDataSource yet again, to better infer the shadow directory location. My previous approach didn't handle having Csla.dll in the GAC, and failed at other (seemingly random) times as well. The new approach infers the shadow directory inside the primary VS 2005 AppDomain, and using the business assembly/type as the source location (rather than Csla.dll). This change appears to have fixed the random failures and should allow Csla.dll to be in the GAC. I doubt it allows the business assembly to be in the GAC, but (imo) that's not a good idea anyway.

    Friday, July 14, 2006 8:02:57 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [3]  | 

     Saturday, June 17, 2006

    CSLA .NET version 2.0.2 is now available for download at www.lhotka.net/cslanet/download.aspx. This is a bug fix update to address various errata and issues that readers have found since version 2.0.1.

    This version also introduces one change, which allows you to call DataPortal.Fetch with no criteria.

    Saturday, June 17, 2006 9:53:34 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [2]  | 

     Wednesday, May 31, 2006

    CSLA .NET version 2.0.1 is now available for download at www.lhotka.net/cslanet/download.aspx. This is primarily a bug fix update to address various errata and issues that readers have found since the release of the original code. It does include a couple changes primarily geared toward simplification of code generation templates. You can see the change log here.

    At a high level the changes (other than bug fixes) include:

    • A new Initialize() method for use by code generation templates
    • A new IEditableBusinessObject interface to allow polymorphic child objects in BusinessListBase-derived collections
    • Better support for lazy loading of child collections (EditLevel property now visible from BusinessListBase, and null child object references now restored in UndoChanges)

     

    Wednesday, May 31, 2006 9:37:06 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [4]  | 

     Thursday, May 25, 2006

    I have two updates for CSLA .NET for those who are interested.

    CSLA .NET version 1.53 is now available from www.lhotka.net/cslanet/download10.aspx. This is a minor bug fix update to 1.52.

    A beta of CSLA .NET version 2.0.1 is now available from www.lhotka.net/cslanet/download.aspx. This includes fixes for a number of bugs and errata (which you can find at www.lhotka.net/cslanet), as well as some minor enhancements due to unforseen limitations around areas like threading and polymorphic child objects. If you get a chance to try 2.0.1 I would appreciate it. Barring any negative feedback from the community I expect to finalize it in about a week.

    Thursday, May 25, 2006 2:01:38 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [0]  | 

     Saturday, May 13, 2006

    I’ve run into a spot where I’m stuck, and I’m hoping someone has an idea.

     

    CSLA .NET 2.0 includes an ASP.NET data source control: CslaDataSource. This works well, except for one issue, which is that it doesn’t refresh the metadata for your business objects unless you close VS 2005 and reopen the IDE.

     

    The reason for this problem is that your business assembly gets loaded into memory so the data source control can reflect against it to gather the metadata. That part works fine, but once an assembly is loaded into an AppDomain it can’t be unloaded. It is possible to unload an entire AppDomain however, and so that’s the obvious solution: load the business assembly into a temporary AppDomain.

     

    So this is what I’m trying to do, and where I’m stuck. You see VS 2005 has a very complex way of loading assemblies into ASP.NET web projects. It actually appears to use the ASP.NET temporary file scheme to shadow the assemblies as it loads them. Each time you rebuild your solution (or a dependant assembly – like your business assembly), a new shadow directory is created.

     

    The CslaDataSource control is loaded into the AppDomain from the first shadow directory – and from what I can tell that AppDomain never unloads, so the control is always running from that first shadow directory. And then – even if I use a temporary AppDomain – the business assembly is also loaded from that same shadow directory, even if newer ones exist.

     

    And that’s where I’m stuck. I have no idea how to find out the current shadow directory, and even if I do odd things like hard-coding the directory, then I just get in trouble because the new AppDomain thinks it has a different Csla.dll than the AppDomain hosting the Web Forms designer.

     

    Here’s the code that loads the Type object within the temporary AppDomain:

     

        public IDataSourceFieldSchema[] GetFields()

        {

          List<ObjectFieldInfo> result =

            new List<ObjectFieldInfo>();

     

          System.Security.NamedPermissionSet fulltrust =

            new System.Security.NamedPermissionSet("FullTrust");

          AppDomain tempDomain = AppDomain.CreateDomain(

            "__temp",

            AppDomain.CurrentDomain.Evidence,

            AppDomain.CurrentDomain.SetupInformation,

            fulltrust,

            new System.Security.Policy.StrongName[] { });

          try

          {

            // load the TypeLoader object in the temp AppDomain

            Assembly thisAssembly = Assembly.GetExecutingAssembly();

            int id = AppDomain.CurrentDomain.Id;

            TypeLoader loader =

              (TypeLoader)tempDomain.CreateInstanceFromAndUnwrap(

                thisAssembly.CodeBase, typeof(TypeLoader).FullName);

            // load the business type in the temp AppDomain

            Type t = loader.GetType(

              _typeAssemblyName, _typeName);

           

            // load the metadata from the Type object

            if (typeof(IEnumerable).IsAssignableFrom(t))

            {

              // this is a list so get the item type

              t = Utilities.GetChildItemType(t);

            }

            PropertyDescriptorCollection props =

              TypeDescriptor.GetProperties(t);

            foreach (PropertyDescriptor item in props)

              if (item.IsBrowsable)

                result.Add(new ObjectFieldInfo(item));

          }

          finally

          {

            AppDomain.Unload(tempDomain);

          }

          return result.ToArray();

        }

     

    This replaces the method of the same name from ObjectViewSchema in the book.

     

    Notice that it creates a new AppDomain and then invokes a TypeLoader class inside that AppDomain to create the Type object for the business class. The TypeLoader is a new class in Csla.dll that looks like this:

     

    using System;

    using System.Collections.Generic;

    using System.Text;

     

    namespace Csla.Web.Design

    {

      /// <summary>

      /// Loads a Type object into the AppDomain.

      /// </summary>

      public class TypeLoader : MarshalByRefObject

      {

        /// <summary>

        /// Returns a <see cref="Type">Type</see> object based on the

        /// assembly and type information provided.

        /// </summary>

        /// <param name="assemblyName">(Optional) Assembly name containing the type.</param>

        /// <param name="typeName">Full type name of the class.</param>

        /// <remarks></remarks>

        public Type GetType(

          string assemblyName, string typeName)

        {

          int id = AppDomain.CurrentDomain.Id;

          return Csla.Web.CslaDataSource.GetType(

            assemblyName, typeName);

        }

      }

    }

     

    Since this object is created in the temporary AppDomain, the business assembly is loaded into that AppDomain. The Type object is [Serializable] and so is serialized back to the main AppDomain so the data source control can get the metadata as needed.

     

    This actually all works – except that it doesn’t pick up new shadow directories as they are created.

     

    Any ideas on how to figure out the proper shadow directory are appreciated.

     

    Honestly, I can’t figure out how this works in general – because obviously some part of the VS designer picks up the new shadow directory and uses it – even though the designer apparently doesn’t. I am quite lost here.

     

    To make matters worse, things operate entirely differently when a debugger is attached to VS than when not. When a debugger is attached to VS then nothing appears to pick up the new shadow directories – so I assume the debugger is interfering somehow. But it makes tracking down the issues really hard.

    Saturday, May 13, 2006 12:53:49 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [14]  | 

     Monday, May 01, 2006

    One of the most important "features" of CSLA .NET is the vibrant community that surrounds it. I am humbled by, and very appreciative of, the amount of time and effort people put into this community - helping other people more effectively learn and use the concepts from my books.

    The most recent examples? Updates to several of the major community contributions for CSLA .NET 2.0:

    Permanent links to these contributions are, along with general errata and other information, at the CSLA .NET 2.0 home page: www.lhotka.net/cslanet.

    Monday, May 01, 2006 7:21:14 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [1]  | 

     Wednesday, March 22, 2006

    I have sent off the final code for the book to Apress, which officially means that I have RTM code at this point. You can go here to download the release code for VB or C#.

    As a bonus, I also put a test release of a WCF data portal channel up for download - you can get if from this page.

    Update: Today (March 22) I recieved my author's copies of the Expert C# 2005 Business Objects book - so it is most certainly in print. What a joy it is to actually see the results of the past several months of work!!

    Wednesday, March 22, 2006 12:38:56 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [11]  | 

     Wednesday, March 01, 2006

    I was recently asked whether I thought it was a good idea to avoid using the Validation events provided by Microsoft (in the UI), in favor of putting the validation logic into a set of objects. I think the answer to the question (to some degree) depends on whether you are doing Windows or Web development.

     

    With Windows development, Windows Forms provides all the plumbing you need to put all your validation in the business objects and still have a very rich, expressive UI - with virtually no code in the UI at all. This is particularly true in .NET 2.0, but is quite workable in .NET 1.1 as well.

     

    With Web development life isn't as nice. Of course there's no way to run real code in the browser, so you are stuck with JavaScript. While the real authority for any and all business logic must reside on the web server (because browsers are easily compromised), many web applications duplicate validation into the browser to give the user a better experience. While this is expensive and unfortunate, it is life in the world of the Web.

     

    (Of course what really happens with a lot of Web apps is that the validation is only put into the browser - which is horrible, because it is too easy to bypass. That is simply a flawed approach to development...)

     

    At least with ASP.NET there are the validation controls, which simplify the process of creating and maintaining the duplicate validation logic in the browser. You are still left to manually keep the logic in sync, but at least it doesn't require hand-coding JavaScript in most cases.

     

     

    Obviously Windows Forms is an older and more mature technology (or at least flows from an older family of technologies), so it is no surprise that it allows you to do more things with less effort. But in most cases the effort to create Web Forms interfaces isn't bad either.

     

    In any case, I do focus greatly on keeping code out of the UI. There's nothing more expensive than a line of code in the UI - because you _know_ it has a half-life of about 1-2 years. Everyone is rewriting their ASP.NET 1.0 UI code to ASP.NET 2.0. Everyone is tweaking their Windows Forms 1.0 code for 2.0. And all of it is junk when WinFX comes out, since WPF is intended to replace both Windows and Web UI development in most cases. Thus code in the UI is expensive, because you'll need to rewrite it in less than 2 years in most cases.

     

    Code in a business object, on the other hand, is far less expensive because most business processes don't change nearly as fast as the UI technologies provided by our vendors... As long as your business objects conform to the basic platform interfaces for data binding, they tend to flow forward from one UI technology to the next. For instance, WPF uses the same interfaces as Windows Forms, so reusing the same objects from Windows Forms behind WPF turns out to be pretty painless. You just redesign the UI and away you go.

     

    A co-worker at Magenic has already taken my ProjectTracker20 sample app and created a WPF interface for it – based on the same set of CSLA .NET 2.0 business objects as the Windows Forms and Web Forms interfaces. Very cool!

     

    So ultimately, I strongly believe that validation (and all other business logic) should be done in a set of business objects. That’s much of the focus in my upcoming Expert VB 2005 and C# 2005 Business Objects books. While you might opt to duplicate some of the validation in the UI for a rich user experience, that’s merely an unfortunate side-effect of the immature (and stagnant) state of the HTML world.

    Wednesday, March 01, 2006 3:44:33 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [12]  | 

     Tuesday, February 07, 2006

    A few people have asked how the book is coming along, so here’s an update.

     

    I touch each chapter a minimum of four times: to write it (AU), to revise it based on tech review comments (TR), to revise it based on copyedit questions (CE) and to do a final review after layout/typesetting (TS).

     

    I am writing both the VB and C# books “concurrently”. What this really means is that I’m writing the book with one language, then skimming back through to change all language keywords, code blocks and diagrams to match the other language.

     

    To practice what I preach (which is that you should be competent, if not fluent, in at least two languages) I am doing the book in C# and then converting to VB. It takes around 8 hours per chapter to do that conversion, 12 if there are a lot of diagrams to convert (code is easy – the damn graphics are the hard part…).

     

    So, here’s the status as of this evening:

     

    Chapter

    C#

    VB

    Cover

    AU done

    -

    Front matter

    AU done

    -

    1

    TS done

    TR done

    2

    TS done

    AU

    3

    TS done

    AU

    4

    TS

    -

    5

    CE done

    -

    6

    CE done

    -

    7

    CE done

    -

    8

    CE done

    -

    9

    CE done

    -

    10

    CE done

    -

    11

    TR done

    -

    12

    TR done

    -

     

    People have also asked how much I expect the CSLA .NET 2.0 public beta code to change between now and the book’s release at the end of March. Chapters 2-5 cover the framework, and as you can see those chapters are into the final editing stages. As such, I certainly don’t anticipate much change.

     

    While I’ve made every effort to keep the VB and C# code in sync, there may be minor tweaks to the code as I roll through the VB chapters 2-5. But I’ve used both in projects and at conferences like VS Live last week, and both pass my unit tests, so those changes should be cosmetic, not functional.

     

    In other words, the beta is pretty darn close to the final code that’ll be provided for download with the book.

    Tuesday, February 07, 2006 9:05:15 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [2]  | 

     Thursday, February 02, 2006

    It is fairly common for people to focus so much on the CSLA .NET “feature list” that they forget that the purpose of the framework is merely to enable the implementation of good OO designs. Many times I’ll get questions or comments asking why CSLA .NET “only” supports certain types of objects, and why it doesn’t support others.

     

    The thing is, CSLA .NET doesn't dictate your object model. All it does is enable a set of 10 or so stereotypes (in CSLA .NET 2.0), providing base classes to simplify the implementation of those stereotypes:

     

    ·         Editable root

    ·         Editable child

    ·         Editable root collection

    ·         Editable child collection

    ·         Read-only root

    ·         Read-only child

    ·         Read-only root collection

    ·         Read-only child collection

    ·         Name-value list

    ·         Command

    ·         Process

     

    CSLA .NET provides base classes to minimize the code a business developer must write to implement this set of common stereotypes. But the fact is that most systems will have objects that fit into other stereotypes, and that's great! CSLA .NET doesn’t stop you from implementing those objects, and it may help you.

     

    If you have objects that don’t fit the stereotypes listed above, you may still find that specific CSLA .NET features are useful. For instance, if your object must move between the client and application server, the data portal is extremely valuable. This is true even for objects that don’t actually use “data” (as in a database), but may have other reasons for moving between client and server. In other cases, an object may benefit from the Security functionality in CSLA .NET, such as authorization.

     

    The point is that you can pick and choose the features that are of use for your particular object stereotype. If you’ll be creating multiple objects that fit this new stereotype, I recommend creating your own base class to support their creation (not necessarily by altering the Csla project itself, as that complicates updates). As much as possible, I’ve tried to keep the framework open so you can extend it by creating your own base classes – either from scratch, or inheriting from something like Csla.Core.BusinessBase, or Csla.Core.ReadOnlyBindingList.

     

    The key point, is that you should develop your object model based on behavioral object design principles. Then you should determine how (and if) those objects map into the existing CSLA .NET stereotypes, thus identifying where you can leverage the pre-existing base classes and tap into the functionality they provide. For objects that simply don’t fit into one of these stereotypes you can decide what (if any) CSLA .NET functionality those objects should use and you can go from there.

     

    In short, the starting point should be your object model, not the “feature list” of CSLA .NET itself.

    Thursday, February 02, 2006 2:06:08 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [1]  | 

     Monday, January 30, 2006

    A public beta of CSLA .NET 2.0 is now available at www.lhotka.net/cslanet/csla20.aspx

    The Expert C# 2005 Business Objects and Expert VB 2005 Business Objects books are still due out around the end of March. That is also the point at which the framework with "RTM".

    The public beta should be reasonable stable. I am nearly done with technical reviews of the chapters, and so am basically done with the framework updates. The ProjectTracker sample application is still under review at this point.

    Monday, January 30, 2006 2:44:08 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [6]  | 

     Tuesday, January 24, 2006

    Next week at VS Live in San Francisco I’ll release a public beta of CSLA .NET 2.0.

     

    This will include both VB 2005 and C# 2005 editions of the framework code, along with a sample application in both languages, showing how the framework can be used to create Windows, Web and Web service interfaces on top of a common set of business objects.

     

    Those business objects are substantially more powerful than their CSLA .NET 1.x counterparts, while preserving the same architectural concepts and benefits. These objects leverage new .NET 2.0 features such as generics. They also bring forward features from CSLA .NET 1.5, but in a more integrated and elegant manner. There are additional features as well, including support for authorization rules, a more flexible data portal implementation and more.

     

    Watch www.lhotka.net for the release of the beta next week.

     

    Click here to see Jim Fawcette's blog entry about the upcoming beta release.

    Tuesday, January 24, 2006 1:43:25 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [4]  | 

     Tuesday, January 17, 2006

    In a recent entry there was a comment pointing to this article, which discusses the way ASP.NET uses threads – a fact that has serious ramifications on software design.

     

    It made me do some serious thinking/research, because CSLA .NET uses various elements of the Thread object, including the CurrentPrincipal, thread-local storage and (in 2.0) the culture properties. My fear was that if the thread can switch “randomly” during page processing, then how can you count on any of these elements from the Thread object?

     

    Scott Guthrie from Microsoft clarified this for me on a couple key points.

     

    First, ASP.NET doesn’t change your thread at “random” or “without warning” (phrases I’d used in describing my worries). It changes it only in a clearly defined scenario. Specifically, when your thread performs an async IO operation. Scott points out that this is perhaps most common in a page that takes advantage of the new async page capability, or within a HttpModule that uses any async IO.

     

    In other words, normal web pages really aren’t subject to this issue at all. It only occurs in relatively advanced scenarios. And you, as the developer, should know darn well when you invoke an async operation; thus you know when you open yourself up for thread switching.

     

    Still, I wanted to make sure the Business Objects book didn’t go down a bad path with the Thread object. But Scott clarified further.

     

    ASP.NET ensures that, even if they switch your thread, the CurrentPrincipal and culture properties from the original thread carry forward to the new thread. This is automatic, and you don’t need to worry about losing those values. Whew!

     

    However, thread-local storage doesn’t carry forward. If you use that feature of the Thread object in ASP.NET code you could be in trouble. This did cause me to rework some code in the book and in CSLA .NET. Specifically CSLA .NET 2.0 now detects whether it is running in ASP.NET or not and uses either thread-local storage or HttpContext.Current.Items to maintain its context data.

     

    I also went the rest of the way and created a Csla.ApplicationContext.User property that gets and sets the user’s principal on either the Thread or HttpContext based on whether the code is running in ASP.NET or not. This allows you to write code in your UI and objects and other libraries without worrying about whether it might run inside our outside ASP.NET at some point.

     

    Certainly for mobile business objects this is very important! They can (and often do) run in both a smart client and ASP.NET environment within the same application.

    Tuesday, January 17, 2006 2:48:29 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [4]  | 

     Tuesday, December 13, 2005
    I am at the point now where I think the resource.resx file for CSLA .NET 2.0 is stable. Of course it is only in English at this point, and so I am putting out a call to anyone willing to translate the file to other languages.
     
    Thanks to volunteer efforts, CSLA .NET 1.x has resources in a total of 11 languages, which is simply wonderful!
     
    If you are willing to translate the resources to your language, many people would appreciate your help.
     
    The English resource.resx file can be downloaded here: www.lhotka.net/files/csla20-resources.zip
     
    If you are able to translate the file, please email me the resulting translation and I'll incorporate it into the solution so it is available when the book comes out (anticipated for the end of March 2006).
     
    I'll keep a log of the languages as part of the CSLA .NET 2.0 Change Log, so you can check there to see if your language already has a translation.
     
    Thank you!
     
    Rocky
    Tuesday, December 13, 2005 4:55:14 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [5]  | 

     Friday, November 18, 2005

    I’ve posted a couple times before about what a business class will look like in the next edition of my business objects books and thus in CSLA .NET 2.0. One of those times Jason Bock (a fellow Magenicon) sent me an email asking why the DataPortal_Create/Fetch/Delete methods aren’t strongly typed.

     

    If you look at the current approach and what I’ve posted thus far for the next edition you’ll see code like this:

     

    Protected Overrides Sub DataPortal_Fetch(ByVal criteria As Object)

    or

    protected override void DataPortal_Fetch(object criteria)

     

    Jason’s comment got me thinking. The DataPortal uses reflection to invoke this method, so why not be a bit more thorough in identifying the method’s parameters and invoke a strongly typed version like this:

     

    Private Overloads Sub DataPortal_Fetch(ByVal criteria As Criteria)

    or

    void DataPortal_Fetch(Criteria criteria)

     

    Where Criteria is the actual type of the criteria object provided when calling the DataPortal.Fetch() method back in the factory.

     

    (the Overloads keyword is required because the base class still implements the default protected version)

     

    As with many things, this sounded relatively trivial but turned out to be somewhat harder than expected. It is always the edge cases that make things hard… In this case the hard part is that parameters could be Nothing – in which case you don’t know what type they would be if they weren’t Nothing...

     

    After working through that issue all is well.

     

    This (in my opinion) is better than the alternative, which was to go with an interface-based approach and formalize the late-bound concept. That has its attraction, and people have altered CSLA .NET 1.0 along that line, but I really prefer strong typing if I can get it.

     

    In particular this is nice for collections, where you may have multiple criteria classes for different views – now you can just implement a strongly-typed DataPortal_Fetch() method for each criteria class. Very clean and nice.

     

    I’m still deliberating over whether to leave the default protected implementations in the base classes. They are nice because VS helps you override those methods, but they aren’t optimal. Given that VS has such nice snippet support it may be better to drop the protected defaults and just rely on snippets to insert the DataPortal_XYZ methods.

     

    If you have an opinion, feel free to comment :)

    Friday, November 18, 2005 6:02:25 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [20]  | 

    This link was posted to the CSLA .NET discussion forum. It uses Google Maps and superimposes the locations of CSLA .NET users who've entered themselves on the site.

    That's just way too cool! :)

    Friday, November 18, 2005 12:16:08 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [1]  | 

     Tuesday, November 15, 2005

    The ADO Guy expresses his frustration that the ObjectDataSource doesn't work with typed DataSets in ADO.NET 2.0. In an earlier post I expressed my frustration about using it with business objects.

    In the case of CSLA .NET 2.0 I'm writing my own CslaDataSource that understands how to work nicely with CSLA .NET business objects. In conferring with the ASP.NET team it seems like this is the best option. It turns out that writing a DataSource control isn't overly difficult - it is writing the designer support (for VS 2005) that is the hard part...

    Tuesday, November 15, 2005 9:55:10 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [7]  | 

     Wednesday, November 02, 2005

    Quite a few people have asked me about the effort that will be required to move an application from CSLA .NET 1.0 to CSLA .NET 2.0. The list of changes in the change log can look daunting after all…

     

    Fortunately most of the changes in the change log are internal – they don’t directly impact your code in a business class all that much, at least for code written using more recent versions of the framework (1.3 or higher).

     

    In fact, the closer your code is to version 1.51 (the current version) the easier the port will be. The closer to the original 1.0 version in the books the harder.

     

    The three big change areas are generics, BrokenRules and the DataPortal.

     

    Generics mean there are new and different base classes from which you inherit. In most cases changing to the new base class means removing some now unneeded code from your business class. The following table lists the base classes:

     

    Old

    New

    BusinessBase

    BusinessBase(Of T)

    BusinessBase<T>

    T = your business object type

    BusinessCollectionBase

    BusinessListBase(Of T, C)

    BusinessListBase<T, C>

    T = your collection type

    C = child object type

    NameValueCollectionBase

    NameValueListBase(Of K, V)

    NameValueListBase<K, V>

    K = type of the key or name

    V = type of the value

    ReadOnlyBase

    ReadOnlyBase(Of T)

    ReadOnlyBase<T>

    T = your business object type

    ReadOnlyCollectionBase

    ReadOnlyListBase(Of T)

    ReadOnlyListBase<T>

    T = child object type

     

    The only place where you need to add code is BusinessBase(Of T), where there’s a new GetIdValue method you must implement (typically with one line of code). In all cases you will remove code such as the System.Objects overrides region and tons of code in collections.

     

    A much bigger changes is that BrokenRules has been replaced by ValidationRules and now only supports the idea of rule methods. The BrokenRules.Assert() concept is gone. This will be the biggest change for most people, as all Assert calls must be converted to rule methods. Fortunately that's not terribly hard, but it is work.

     

    DataPortal used to call DataPortal_Update, forcing you to write a nested If..Then statement inside DataPortal_Update. It now calls DataPortal_Insert, DataPortal_Update or DataPortal_DeleteSelf as appropriate. So now you write 3 methods instead of 1, but each method is very focused and requires no conditionals. Also, DataPortal now calls MarkNew and MarkOld automatically so you don't need to make those calls (or forget to make them like I typically did...).

     

    The end result is that all properties in a BusinessBase(Of T) business object will now look like this:

     

    private string _name = string.Empty;

     

    public string Name

    {

      get

      {

        if (CanReadProperty())

          return _name;

        else

          throw new System.Security.SecurityException(

            "Property get not allowed");

      }

      set

      {

        if (CanWriteProperty())

          if (_name != value)

          {

            _name = value;

            PropertyHasChanged();

          }

        else

          throw new System.Security.SecurityException(

            "Property set not allowed");

      }

    }

     

    Or

     

    Private mName As String = ""

     

    Public Property Name() As String

      Get

        If CanReadProperty() Then

          Return mName

        Else

          Throw New System.Security.SecurityException( _

            "Property get not allowed")

        End If

      End Get

      Set(ByVal value As String)

        If CanWriteProperty() Then

          If mName <> value Then

            mName = value

            PropertyHasChanged()

          End If

        Else

          Throw New System.Security.SecurityException( _

            "Property set not allowed")

        End If

      End Set

    End Property

     

     

    The new Expert VB/C# 2005 Business Objects books and thus the CSLA .NET 2.0 framework are slated for public release in Mar/Apr 2006.

    Wednesday, November 02, 2005 10:08:19 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [9]  | 

     Thursday, October 13, 2005

    ASP.NET 2.0 has bi-directional data binding, which is a big step forward. This means you can bind the UI to a data source (DataTable, object, etc.) and not only display the data, but allow the user to do “in-place” editing that updates the data source when the page is posted back.

     

    The end result is very cool, since it radically reduces the amount of code required for many common data-oriented web pages.

     

    Unfortunately the data binding implementation isn’t very flexible when it comes to objects. The base assumption is that “objects” aren’t intelligent. In fact, the assumption is that you are binding to “data objects” – commonly known as Data Transfer Objects or DTOs. They have properties, but no logic.

     

    In my case I’m working with CSLA .NET 2.0 objects – and they do have logic. Lots of it, validation, authorization and so forth. They are “real” objects in that they are behavior-based, not data-based. And this causes a bit of an issue.

     

    There are two key constraints that are problematic.

     

    First, ASP.NET insists on creating instances of your objects at will – using a default constructor. CSLA .NET follows a factory method model where objects are always created through a factory method, providing for more control, abstraction and flexibility in object design.

     

    Second, when updating data (the user has edited existing data and clicked Update), ASP.NET creates an instance of your object, sets its properties and calls an Update method. CSLA .NET objects are aware of whether they are new or old – whether they contain a primary key value that matches a value in the database or not. This means that the object knows whether to do an INSERT or UPDATE automatically. But when a CSLA .NET object is created out of thin air it obviously thinks it is new – yet in the ASP.NET case the object is actually old, but has no way of knowing that.

     

    The easiest way to overcome the first problem is to make business objects have a public default constructor. Then they play nicely with ASP.NET data binding. The drawback to this is that anyone can then bypass the factory methods and incorrectly create the objects with the New keyword. That is very sad, since it means your object design can’t count on being created the correct way, and a developer consuming the object might use the New keyword rather than the factory method and really mess things up. Yet at present this is how I’m solving issue number one.

     

    I am currently solving issue number two through an overloaded Save method in BusinessBase: Save(forceUpdate) where forceUpdate is a Boolean. Set it to True and the business object forces its IsNew flag to False, thus ensuring that an update operation occurs as desired. This solution works wonderfully for the web scenario, but again opens up the door to abuse in other settings. Yet again a consumer of the object could introduce bugs into their app by calling this overload when it isn’t appropriate.

     

    The only way out of this mess that I can see is to create my own ASP.NET data control that understands how CSLA .NET objects work. I haven’t really researched that yet, so I don’t know how complex it is to write such a control. I did try to subclass the current Object control, but they don’t provide extensibility points like I need, so that doesn’t work. The only answer is probably to subclass the base data control class itself…

    Thursday, October 13, 2005 6:17:12 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [16]  | 

     Thursday, October 06, 2005

    Here's a "basic" CSLA .NET 2.0 editable root class. It pretty much illustrates all the things you can do in a class under the upcoming version of the framework. In particular note the way validation rules are handled and all the transactional options in the DataPortal_XYZ methods (presumably you'd pick one for your app :) ).

    A CustomerTypes class is also included at the bottom, illustrating how to implement a name-value list that works with data binding.

    Imports CSLA

     

    <Serializable()> _

    Public Class Customer

      Inherits BusinessBase(Of Customer)

     

    #Region " Business Methods "

     

      Private mID As Integer

      Private mLastName As String = ""

      Private mFirstName As String = ""

      Private mLastActivity As SmartDate

      Private mType As Integer

      Private mCity As String = ""

     

      Private Shared mCustomerTypes As CustomerTypes

     

      Public Property City() As String

        Get

          If CanReadProperty() Then

            Return mCity

          Else

            Throw New System.Security.SecurityException( _

              "Property read not allowed")

          End If

        End Get

        Set(ByVal value As String)

          If CanWriteProperty() Then

            If Not mCity.Equals(value) Then

              mCity = value

              PropertyHasChanged()

            End If

          Else

            Throw New System.Security.SecurityException( _

              "Property write not allowed")

          End If

        End Set

      End Property

     

      Public Shared ReadOnly Property CustomerTypes() As CustomerTypes

        Get

          If mCustomerTypes Is Nothing Then

            mCustomerTypes = Library.CustomerTypes.GetCustomerTypes

          End If

          Return mCustomerTypes

        End Get

      End Property

     

      Public ReadOnly Property ID() As Integer

        Get

          Return mID

        End Get

      End Property

     

      Public Property LastName() As String

        Get

          If CanReadProperty() Then

            Return mLastName

          Else

            Throw New System.Security.SecurityException( _

              "Property read not allowed")

          End If

        End Get

        Set(ByVal value As String)

          If CanWriteProperty() Then

            If mLastName <> value Then

              mLastName = value.ToUpper

              PropertyHasChanged()

            End If

          Else

            Throw New System.Security.SecurityException( _

              "Property write not allowed")

          End If

        End Set

      End Property

     

      Public Property FirstName() As String

        Get

          If CanReadProperty() Then

            Return mFirstName

          Else

            Throw New System.Security.SecurityException( _

              "Property read not allowed")

          End If

        End Get

        Set(ByVal value As String)

          If CanWriteProperty() Then

            If mFirstName <> value Then

              mFirstName = value

              PropertyHasChanged()

            End If

          Else

            Throw New System.Security.SecurityException( _

              "Property write not allowed")

          End If

        End Set

      End Property

     

      Public Property LastActivity() As String

        Get

          If CanReadProperty() Then

            Return mLastActivity.Text

          Else

            Throw New System.Security.SecurityException( _

              "Property read not allowed")

          End If

        End Get

        Set(ByVal value As String)

          If CanWriteProperty() Then

            If mLastActivity <> value Then

              mLastActivity.Text = value

              PropertyHasChanged()

            End If

          Else

            Throw New System.Security.SecurityException( _

              "Property write not allowed")

          End If

        End Set

      End Property

     

      Public Property CustomerType() As Integer

        Get

          If CanReadProperty() Then

            Return mType

          Else

            Throw New System.Security.SecurityException( _

              "Property read not allowed")

          End If

        End Get

        Set(ByVal value As Integer)

          If CanWriteProperty() Then

            If mType <> value Then

              mType = value

              PropertyHasChanged()

            End If

          Else

            Throw New System.Security.SecurityException( _

              "Property write not allowed")

          End If

        End Set

      End Property

     

      Public ReadOnly Property CustomerTypeText() As String

        Get

          If CanReadProperty() Then

            Return CustomerTypes.Value(mType)

          Else

            Throw New System.Security.SecurityException( _

              "Property read not allowed")

          End If

        End Get

      End Property

     

    #End Region

     

    #Region " Business Rules "

     

      Protected Overrides Sub AddBusinessRules()

        AddRule(AddressOf Validation.CommonRules.StringRequired, _

          "FirstName")

        AddRule(AddressOf Validation.CommonRules.StringRequired, _

          "LastName")

      End Sub

     

    #End Region

     

    #Region " Object ID Value "

     

      Protected Overrides Function GetIdValue() As Object

        Return mID

      End Function

     

    #End Region

     

    #Region " Constructors "

     

      Private Sub New()

     

        ' don't allow a Guest to see or change city data

        AuthorizationRules.DenyRead("City", "Guest")

        AuthorizationRules.DenyWrite("City", "Guest")

     

      End Sub

     

    #End Region

     

    #Region " Factory Methods "

     

      Public Shared Function NewCustomer() As Customer

        Return DataPortal.Create(Of Customer)(Nothing)

      End Function

     

      Public Shared Function GetCustomer(ByVal id As Integer) As Customer

        Return DataPortal.Fetch(Of Customer)(New Criteria(id))

      End Function

     

      Public Shared Sub DeleteCustomer(ByVal id As Integer)

        DataPortal.Delete(New Criteria(id))

      End Sub

     

    #End Region

     

    #Region " Criteria "

     

      <Serializable()> _

      Private Class Criteria

        Public ID As Integer

     

        Public Sub New(ByVal id As Integer)

          Me.ID = id

        End Sub

      End Class

     

    #End Region

     

    #Region " Data Access "

     

      ' Forced to run on client

      <RunLocal()> _

      Protected Overrides Sub DataPortal_Create(ByVal criteria As Object)

     

        ' get default values from db

        ' we get here via DataPortal.Create()

     

        mID = New System.Random().Next(100, 999)

        mType = CustomerTypes.DefaultKey

        CheckRules()

     

      End Sub

     

      ' Runs on client or server based on DataPortal config

      Protected Overrides Sub DataPortal_Fetch(ByVal criteria As Object)

     

        ' get data from db

        ' we get here via DataPortal.Fetch()

     

        Dim crit As Criteria = DirectCast(criteria, Criteria)

        mID = crit.ID

        mType = CustomerTypes.Key("Hybrid")

        mLastName = "Lhotka"

        mFirstName = "Rocky"

        CheckRules()

     

      End Sub

     

      ' COM+ transactions

      <Transactional()> _

      Protected Overrides Sub DataPortal_Insert()

     

        ' insert data into db

        ' we get here via obj.Save()

     

      End Sub

     

      ' System.Transactions namespace

      Protected Overrides Sub DataPortal_Update()

     

        ' update data in db

        ' we get here via obj.Save()

     

        Using tr As New System.Transactions.TransactionScope

          ' do updates

          tr.Complete()

        End Using

     

      End Sub

     

      ' ADO.NET transactions

      Protected Overrides Sub DataPortal_DeleteSelf()

     

        ' do deferred delete of self

        ' we get here via obj.Save()

     

        Using cn As New SqlClient.SqlConnection

          Using tr As SqlClient.SqlTransaction = cn.BeginTransaction

            ' do delete

          End Using

        End Using

     

      End Sub

     

      ' No transactions

      Protected Overrides Sub DataPortal_Delete(ByVal criteria As Object)

     

        Dim crit As Criteria = DirectCast(criteria, Criteria)

     

        ' do immediate delete based on criteria

        ' we get here via DataPortal.Delete()

     

      End Sub

     

    #End Region

     

    End Class

     

    ======================================================

    Imports CSLA

     

    Public Class CustomerTypes

      Inherits NameValueListBase(Of Integer, String)

     

      Public Function DefaultKey() As Integer

        Return 1

      End Function

     

      Public Function DefaultValue() As String

        Return Value(DefaultKey)

      End Function

     

      Private Sub New()

     

      End Sub

     

      Public Shared Function GetCustomerTypes() As CustomerTypes

        Return DataPortal.Fetch(Of CustomerTypes) _

          (New Criteria(GetType(CustomerTypes)))

      End Function

     

      Protected Overrides Sub DataPortal_Fetch(ByVal criteria As Object)

        Me.IsReadOnly = False

        Add(New NameValuePair(1, "Domestic"))

        Add(New NameValuePair(2, "International"))

        Add(New NameValuePair(3, "Hybrid"))

        Me.IsReadOnly = True

      End Sub

     

    End Class

     

    Thursday, October 06, 2005 2:18:16 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [7]  | 

     Wednesday, September 07, 2005
    I have started a document where I have and will post changes to CSLA .NET from version 1.5 to 2.0.
    Wednesday, September 07, 2005 9:04:39 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [1]  | 

     Thursday, July 21, 2005

    I am often asked whether n-tier (where n>=3) is always the best way to go when building software.

     

    Of course the answer is no. In fact, it is more likely that n-tier is not the way to go!

     

    By the way, this isn’t the first time I’ve discussed this topic – you’ll find previous blog entries on this blog and an article at www.devx.com where I’ve covered much of the same material. Of course I also cover it rather a lot in my Expert VB.NET and C# Business Objects books.

     

    Before proceeding further however, I need to get some terminology out of the way. There’s a huge difference between logical tiers and physical tiers. Personally I typically refer to logical tiers as layers and physical tiers as tiers to avoid confusion.

     

    Logical layers are merely a way of organizing your code. Typical layers include Presentation, Business and Data – the same as the traditional 3-tier model. But when we’re talking about layers, we’re only talking about logical organization of code. In no way is it implied that these layers might run on different computers or in different processes on a single computer or even in a single process on a single computer. All we are doing is discussing a way of organizing a code into a set of layers defined by specific function.

     

    Physical tiers however, are only about where the code runs. Specifically, tiers are places where layers are deployed and where layers run. In other words, tiers are the physical deployment of layers.

     

    Why do we layer software? Primarily to gain the benefits of logical organization and grouping of like functionality. Translated to tangible outcomes, logical layers offer reuse, easier maintenance and shorter development cycles. In the final analysis, proper layering of software reduces the cost to develop and maintain an application. Layering is almost always a wonderful thing!

     

    Why do we deploy layers onto multiple tiers? Primarily to obtain a balance between performance, scalability, fault tolerance and security. While there are various other reasons for tiers, these four are the most common. The funny thing is that it is almost impossible to get optimum levels of all four attributes – which is why it is always a trade-off between them.

     

    Tiers imply process and/or network boundaries. A 1-tier model has all the layers running in a single memory space (process) on a single machine. A 2-tier model has some layers running in one memory space and other layers in a different memory space. At the very least these memory spaces exist in different processes on the same computer, but more often they are on different computers. Likewise, a 3-tier model has two boundaries. In general terms, an n-tier model has n-1 boundaries.

     

    Crossing a boundary is expensive. It is on the order of 1000 times slower to make a call across a process boundary on the same machine than to make the same call within the same process. If the call is made across a network it is even slower. It is very obvious then, that the more boundaries you have the slower your application will run, because each boundary has a geometric impact on performance.

     

    Worse, boundaries add raw complexity to software design, network infrastructure, manageability and overall maintainability of a system. In short, the more tiers in an application, the more complexity there is to deal with – which directly increases the cost to build and maintain the application.

     

    This is why, in general terms tiers should be minimized. Tiers are not a good thing, they are a necessary evil required to obtain certain levels of scalability, fault tolerance or security.

     

    As a good architect you should be dragged kicking and screaming into adding tiers to your system. But there really are good arguments and reasons for adding tiers, and it is important to accommodate them as appropriate.

     

    The reality is that almost all systems today are at least 2-tier. Unless you are using an Access or dBase style database your Data layer is running on its own tier – typically inside of SQL Server, Oracle or DB2. So for the remainder of my discussion I’ll primarily focus on whether you should use a 2-tier or 3-tier model.

     

    If you look at the CSLA .NET architecture from my Expert VB.NET and C# Business Objects books, you’ll immediately note that it has a construct called the DataPortal which is used to abstract the Data Access layer from the Presentation and Business layers. One key feature of the DataPortal is that it allows the Data Access layer to run in-process with the business layer, or in a separate process (or machine) all based on a configuration switch. It was specifically designed to allow an application to switch between a 2-tier or 3-tier model as a configuration option – with no changes required to the actual application code.

     

    But even so, the question remains whether to configure an application for 2 or 3 tiers.

     

    Ultimately this question can only be answered by doing a cost-benefit analysis for your particular environment. You need to weigh the additional complexity and cost of a 3-tier deployment against the benefits it might bring in terms of scalability, fault tolerance or security.

     

    Scalability flows primarily from the ability to get database connection pooling. In CSLA .NET the Data Access layer is entirely responsible for all interaction with the database. This means it opens and closes all database connections. If the Data Access layer for all users is running on a single machine, then all database connections for all users can be pooled. (this does assume of course, that all users employ the same database connection string include the same database user id – that’s a prerequisite for connection pooling in the first place)

     

    The scalability proposition is quite different for web and Windows presentation layers.

     

    In a web presentation the Presentation and Business layers are already running on a shared server (or server farm). So if the Data Access layer also runs on the same machine database connection pooling is automatic. In other words, the web server is an implicit application server, so there’s really no need to have a separate application server just to get scalability in a web setting.

     

    In a Windows presentation the Presentation and Business layers (at least with CSLA .NET) run on the client workstation, taking full advantage of the memory and CPU power available on those machines. If the Data Access layer is also deployed to the client workstations then there’s no real database connection pooling, since each workstation connects to the database directly. By employing an application server to run the Data Access layer all workstations offload that behavior to a central machine where database connection pooling is possible.

     

    The big question with Windows applications is at what point to use an application server to gain scalability. Obviously there’s no objective answer, since it depends on the IO load of the application, pre-existing load on the database server and so forth. In other words it is very dependant on your particular environment and application. This is why the DataPortal concept is so powerful, because it allows you to deploy your application using a 2-tier model at first, and then switch to a 3-tier model later if needed.

     

    There’s also the possibility that your Windows application will be deployed to a Terminal Services or Citrix server rather than to actual workstations. Obviously this approach totally eliminates the massive scalability benefits of utilizing the memory and CPU of each user’s workstation, but does have the upside of reducing deployment cost and complexity. I am not an expert on either server environment, but it is my understanding that each user session has its own database connection pool on the server, thus acting the same as if each user has their own separate workstation. If this is actually the case, then an application server would have benefit by providing database connection pooling. However, if I’m wrong and all user sessions share database connections across the entire Terminal Services or Citrix server then having an application server would offer no more scalability benefit here than it does in a web application (which is to say virtually none).

     

    Fault tolerance is a bit more complex than scalability. Achieving real fault tolerance requires examination of all failure points that exist between the user and the database – and of course the database itself. And if you want to be complete, you just also consider the user to be a failure point, especially when dealing with workflow, process-oriented or service-oriented systems.

     

    In most cases adding an application server to either a web or Windows environment doesn’t improve fault tolerance. Rather it merely makes it more expensive because you have to make the application server fault tolerant along with the database server, the intervening network infrastructure and any client hardware. In other words, fault tolerance is often less expensive in a 2-tier model than in a 3-tier model.

     

    Security is also a complex topic. For many organizations however, security often comes down to protecting access to the database. From a software perspective this means restricting the code that interacts with the database and providing strict controls over the database connection strings or other database authentication mechanisms.

     

    Security is a case where 3-tier can be beneficial. By putting the Data Access layer onto its own application server tier we isolate all code that interacts with the database onto a central machine (or server farm). More importantly, only that application server needs to have the database connection string or the authentication token needed to access the database server. No web server or Windows workstation needs the keys to the database, which can help improve the overall security of your application.

     

    Of course we must always remember that switching from 2-tier to 3-tier decreases performance and increases complexity (cost). So any benefits from scalability or security must be sufficient to outweigh these costs. It all comes down to a cost-benefit analysis.

     

    Thursday, July 21, 2005 3:51:17 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [15]  | 

     Monday, January 24, 2005

    Sahil has some interesting thoughts on the web service/DataSet question as well.

     

    He spends some time discussing whether “business objects” should be sent via a web service. His definition of “business object” doesn’t match mine, and is closer to Fowler’s data transfer object (DTO) I think.

     

    It is important to remember that web services only move boring data. No semantic meaning is included. At best (assuming avoidance of xsd:any) you get some limited syntactic meaning along with the data.

     

    When we talk about moving anything via a web service, we’re really just talking about data.

     

    When talking about moving a “business object”, most people think of something that can be serialized by web services – meaning by the XmlSerializer. Due to the limitations of the XmlSerializer this means that the objects will have all their fields exposed as public fields or read-write properties.

     

    What this means in short, is that the “business objects” can not follow good OO design principles. Basically, they are not “business objects”, but rather they are a way of defining the message schema for the web service. They are, at best, data transfer objects.

     

    In my business objects books and framework I talk about moving actual business objects across the wire using remoting. Of course the reality here is that only the data moves – but the code must exist on both ends. The effective result is that the object is cloned across the network, and retains both its data and the semantic meaning (the business logic in the object).

     

    You can do this with web services too, but not in a “web service friendly” way. Cloning an object implies that you get all the data in the object. And to do this while still allowing for encapsulation means that the serialization must get private, friend/internal and protected fields as well as public ones. This is accomplished via the BinaryFormatter. The BinaryFormatter generates and consumes streams, which can be thought of as byte arrays. Thus, you end up creating a web service that moves byte arrays around. Totally practical, but the data is not human-readable XML – it is Base64 encoded binary data. I discuss how to do this in CSLA .NET on my web site.

     

    Now we are talking about moving business objects. Real live, OO designed business objects.

     

    Of course this approach is purely for n-tier scenarios. It is totally antithetical to any service-oriented model!

     

    For an SO model you need to have clearly defined schemas for your web service messages, and those should be independent from your internal implementation (business objects, DataSets or whatever). I discuss this in Chapter 10 of my business objects books.

    Monday, January 24, 2005 10:10:21 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [17]  | 

     Friday, June 11, 2004

    I recently had a reader of my business objects book ask about combining CSLA .NET and SOA concepts into a single application.

     

    Certainly there are very valid ways of implementing services and client applications using CSLA such that the result fits nicely into the SOA world. For instance, in Chapter 10 I specifically demonstrate how to create services based on CSLA-style business objects, and in some of my VS Live presentations I discuss how consumption of SOA-style services fits directly into the CSLA architecture within the DataPortal_xyz methods (instead of using ADO.NET).

     

    But the reader put forth the following, which I wanted to discuss in more detail. The text in italics is the reader’s view of Microsoft’s “standard” SOA architecture. My response follows in normal text:

     

    1. Here is the simplified MS’s “standard” layering,

     

    (a) UI Components

    (b) UI Process Components [UI never talk to BSI/BC directly, must via UIP]

     

    (c) Service Interfaces

    (d) Business Components [UIP never talk to D directly, must via BC]

    (e) Business Entities

     

    (f) Data Access Logic Components

     

    I’m aware of its “transaction script” and “anemic domain model” tendency, but it is perhaps easier for integration and using tools.

     

    To be clear, I think this portrayal of ‘SOA’ is misleading and dangerous. SOA describes the interactions between separate applications, while this would lead one into thinking that SOA is used inside an application between tiers. I believe that is entirely wrong – and if you pay attention to what noted experts like Pat Helland are saying, you’ll see that this approach is invalid.

     

    SOA describes a loosely-coupled, message-based set of interactions between applications or services. But in this context, the word ‘service’ is synonymous with ‘application’, since services must stand alone and be entirely self-sufficient.

     

    Under no circumstance can you view a ‘tier’ as a ‘service’ in the context of SOA. A tier is part of an application, and implements part of the application’s overall functionality. Tiers are not designed to stand alone or be used by arbitrary clients – they are designed for use by the rest of their application. I discussed this earlier in my post on trust boundaries, and how services inherently create new trust boundaries by their very nature.

     

    So in my view you are describing at least two separate applications. You have an application with a GUI or web UI (a and b or ab), and an application with an XML interface (c, d, e and f or cdef).

     

    To fit into the SOA model, each of these applications (ab and cdef) is separate and must stand alone. They are not tiers in a single application, but rather are two separate applications that interact. The XML interface from cdef must be designed to service not only the ab application, but any other applications that need its functionality. That’s the whole point of an SOA-based model – to make this type of functionality broadly available and reusable.

     

    Likewise, application ab should be viewed as a full-blown application. The design of ab shouldn’t necessarily eschew business logic – especially validation, but likely also including some calculations or other data manipulation. After all, it is the job of the designer of ab to provide the user with a satisfactory experience based on their requirements – which is similar, but not the same, as the set of requirements for cdef.

     

    Yes, this does mean that you’ll have duplicate logic in ab and cdef. That’s one of the side-effects of SOA. If you don’t like it, don’t use SOA.

     

    But there’s nothing to stop you from using CSLA .NET as a model to create either ab or cdef or both.

     

    To create ab with CSLA .NET, you’d design a set of business objects (with as little or much logic as you felt was required). Since ab doesn’t have a data store of its own, but rather uses cdef as a data store, the DataPortal_xyz methods in the business objects would call the services exposed by cdef to retrieve and update data as needed.

     

    To create cdef with CSLA .NET, you’d follow the basic concepts I discuss in Chapter 10 in my VB.NET and C# Business Objects books. The basic concept is that you create a set of XML web services as an interface that provides the outside world with data and/or functionality. The functionality and data is provided from a set of CSLA .NET objects, which are used by the web services themselves.

     

    Note that the CSLA-style business objects are not directly exposed to the outside world – there is a formal interface definition for the web services which is separate from the CSLA-style business objects themselves. This provides separation of interface (the web services) from implementation (the CSLA-style business objects).

     

    Friday, June 11, 2004 6:25:44 PM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [2]  |