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

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