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

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

 Tuesday, March 31, 2009

CSLA .NET 3.6.2 is now available for download.

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

Highlights include:

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

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

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

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

     Wednesday, March 25, 2009

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

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

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

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

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

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

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

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

    Here’s the control code:

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

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

      private object _selection;

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

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

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

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

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

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

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

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

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

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

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

     Wednesday, March 11, 2009

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

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

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

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

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

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

    This patch solved my problem. Just like that.

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

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

     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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    Some enhancements of note on the Windows side include:

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

    Some enhancements of note on the Silverlight side include:

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

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

     

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

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

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

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

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

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

     Wednesday, January 28, 2009

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

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

    I wish I’d known about this months ago.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

     Friday, October 31, 2008

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

     Wednesday, September 03, 2008

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

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

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

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

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

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

     Monday, September 01, 2008

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

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

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

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

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

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

     Thursday, July 17, 2008

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

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

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

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

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

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

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

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

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

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

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

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

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