Tuesday, July 29, 2008

Silverlight 2: Sharing Code Between Client and Server

One of the first things that came to mind when I heard that silverlight was going to be adding managed code support, was the potential to reuse code between the server and the client. I had been successfully following this methodology for my compact framework development, and now it was possible for silverlight web applications as well! [Insert happy dance here]

One of the main areas I like to reuse code has to do with the object model, and the validation thereof. Just as a reference, when I say "object model", I mean dumb data carriers for my entities. ie: Classes that contain only properties, not behavioural methods. Not that you can't add methods to your OM classes, I just prefer to keep them simple, and let other classes take care of behaviour / validation etc.

Okay - enough blog waffle, let's get straight into sharing your code between server and client!

Here's a picture of a typical basic silverlight architecture:


The idea is to share code between the .NET application layer and the silverlight client layer, and even allowing the classes for the shared code to be serialized over the wire.
NOTE: For the last bit (code sharing that involve "over-the-wire" serialization), you'll need to wait for the release of Silverlight 2 RTW. I can confirm that RTW release does allow the re-use of types in referenced assemblies. :)

Step 1: Define the code

Typically, there are 2 strategies for defining the canonical source of the code: 1) Place it in a shared location, and link it to projects that need it, or 2) Define it in the project with least namespace dependencies, and link it up to other projects.
If you're sharing code across the compact framework, silverlight, and the full .NET framework, I recommend 1), but if you only plan on using the code for one of the subset frameworks, I recommend 2), which is the one I'll describe in detail here.

The reason for defining the class in the silverlight class library is purely due to maintenance reasons. When modifying the source code, always modify it at it's source. That way you know you're not adding any code that depends on framework namespaces that do not exist.
eg: If I open the class where it is defined in the silverlight class library, and try and add a DataSet property, the designer will immediately tell me that this is not possible. If the class was defined in the server assembly, I would only find the dependency error at compile time when the client assembly compiles.

One final note on the class definition: It may be helpful to mark your classes with the "partial" keyword, as you may wish to extend the defined class into server and client specific implementations. That, or you could define new client and server types which inherit from the shared base implementation - whichever makes more sense in the underlying design.

Step 2: Link the Code to the Server Assembly

The idea is that there is only one version of the code on disk, otherwise it's just code duplication, and not code sharing / reuse.
To reuse the code defined in Step 1 in your server class library, do the following:
From the server assembly project menu, select "Add Existing Item", and navigate to the class file defined in Step 1. Instead of clicking the Add button (which would just duplicate the code) select the arrow next to the add button, and select "Add As Link"

AddAsLink   ShortCutIcon

You will notice that there is a little shortcut mark on the class icon in the solution explorer. This indicates that the file is declared elsewhere (your silverlight assembly in this case).
ie: Whenever you make changes to the class definition, it will automatically be reflected in all the places where the source code file is linked.
NOTE: Be careful not to open the file from the shortcut, as Visual Studio will open it assuming you are in the current project, and you will have access to all the .NET namespaces. ALWAYS edit the code by opening it from the canonical source.

Step 3: Share the Code Over WCF Services

If your code is going to be "traversing the wire", then mark it with the usual [DataContract] and [DataMember] attributes. (NOTE: Since the release of SP1, you don't need to explicitly mark your data members - only do so if you want to explicitly exclude certain properties from serialization. ) Make sure that System.Runtime.Serialization is referenced in all projects making use of the shared code file.
From the Silverlight client project, right click and select "Add Service Reference". Add a reference to the WCF service you would like to consume, making sure that the checkbox "reuse types in referenced assemblies" is checked in the advanced options (as displayed below).

 AddServiceReference AddServiceReferenceAdvanced

When reusing types (which will only be available from silverlight 2 RTW), the svcutil, which is used to generate the client proxy class definitions for the DataContracts, will add references to the client versions of the code (the class created in Step 1)  instead of generating them in the Reference.cs file of the service.

...And that's it - now you're sharing C# code between server and client.
I'm currently finding this very handy for executing common business rules on object classes on the client in order to prevent unnecessary round tripping to the server.
It's also become very handy for generic framework implementations using the common base classes. Also, If you have the same DataContract defined in two separate services, instead of them being defined twice (once for each service reference), both services reference the existing client-side class, allowing the generic code implementation mentioned above.

I'm working on posting some (simple) sample source code - watch this space.

Another handy post on the subject


Daily Links 29/07/2008

Visual Studio Item Templates
create custom file templates to give you a head start in implementing derived classes / patterns

Create PDF Files on the fly with C# and PDFSharp

Agilo for Scrum
Demo movie
"Agilo for Scrum is a simple, web-based and straightforward tool to support the Scrum"
"Agilo is distributed as Open Source Software"

Default Architecture: Layers
Interesting article by Ayende touching on most common architecture layering implementations.

Patterns I Hate #1: Singleton
I'm one of the guilty - singletons seem to spread like a virus in my code :|. One of the most convincing arguments not to use them is testability, so if you're going TDD, singletons are going to give you some roadblocks.

In-State Animation with Silverlight
One of the best things about silverlight is how it makes control animation so easy, even non-designers can use it :)

Friday, July 25, 2008

Daily Links 25/07/2008

Lutz Roeder has some pretty handy .NET utility applications
...the most popular being the .NET reflector for inspecting the contents of .NET assemblies (reverse engineering them to code again)

New Silverlight Learn page
much improved/organised learning resource/links for Silverlight 2

Using a DSL to create a fluent interface for unit testing your domain model
English: Create object builders with Domain Specific Language methods in order to provide mock objects with specific data to your unit tests. Highly recommended for TDD.

Table variables v temporary tables in SQL Server
Handy article on the difference between table variables and temporary tables in SQL Server. Both are very handy in optimising your database transactions.

10 Principles of Agile Project Time Management

Managing an Agile Software Project

Example Product Backlog & Sprint Backlog

Unit Test Boundaries
What makes good / defines unit tests? Highlights that they really should be separated from integration tests (which include DAL "unit" tests)

WPF Tutorial - Using MultiBindings

WPF Links - 21 July 2008

Free books on Version Control with SVN

Comparing Objects For Equality in .NET

Arrange Act Assert and BDD specifications
New RhinoMocks 3.5 syntax making AAA (Arrange / Act / Assert) testing pattern more clear and discernible.

.Net Threads - 10 Best Practices

Google WebMaster Tools (free)
" - Automatically inform Google when you update your pages
- Discover your links and see how users are reaching your site
- Enhance and increase traffic to your site
- Learn more at Webmaster Central "

Tuesday, July 15, 2008

Daily Links 15/07/2008

"PostSharp is an free, open-source and extensible platform for enhancement of .NET assemblies"
"provides aspect-oriented programming (AOP) to .NET Developers without the learning curve"

Silverlight, Blend and WPF Tutorials

Using a value converter to bind to Visibility in the Silverlight data grid

Pushing Data to a Silverlight Client with a WCF Duplex Service

Getting started with WPF

Differences between SharePoint Services (WSS 3.0) and Office SharePoint Server (MOSS 2007)

Can someone tell me why i shouldn’t drop WCF?
More on the previous "batching WCF calls" post.

NDepend: code metrics at your service
Good summary article on NDepend functionality
"analyze code structure, specify design rules, plan massive refactoring, do effective code reviews and master evolution by comparing different versions of the code"

July '08 TFS Power Tool Preview
Now has filtered alerts for TFS work items.

Theme Controls in Silverlight

Billy Hollis on Getting Smart with WPF
Excellent presentation on how developing with WPF / Silverlight changes the way we think about UI design.

7 Steps to completing your project on time

101 Linq Examples - C#

Scale Cheaply - Memcached
Distributed cacheing solution for .NET

Wednesday, July 9, 2008

Daily Links 09/07/2008

UI Automation of a Silverlight Custom Control
"Silverlight supports UI Automation through a tree of peer automation objects that parallels the tree of user interface elements."

You should learn sharepoint
In job ads, I'm increasingly seeing adverts for MOSS developer skills - maybe something to consider in your skills development plan.

Telerik RadEditor
Nice WYSIWYG Editor you can use to replace the cr@ppy one that comes with Sharepoint (MOSS)
Apparently the full-featured one is really cool, but you're going to have to fork out $799 for it (worth it if you're running an enterprise MOSS environment)

User Story Estimation Techniques
Excellent article on estimation techniques (or do's and don'ts) of scrum sprint estimation

ScrumForTeamSystem has just released a BETA of TaskBoard
"interactive desktop utility that interfaces with Team Foundation Server projects created from version 2 of the Scrum for Team System process template. It enables you and your team to easily interact with the project work items without the need to run quires and navigate the Team Explorer user interface"
"Sprint backlog tasks can be dragged and dropped from one state to another, team member assignment and work remaining adjustments can be made via context menu manipulation. Activity logging is greatly reduced to give you more time to work on what’s important, the project!"
Looks like it makes scrum administration a breeze - essential for team member motivation and adoption of the scrum methodologies.

Visual Studio Command Shell
"provides users with a shell window inside the Visual Studio IDE that can be used for Visual Studio commands as well. Current version allows user to use either Windows Command Shell (cmd.exe) or Windows PowerShell"

Blog Editors of note:
some nice advertisement add-in functionality that support multiple on-line advert suppliers
Windows Live Writer
Probably best if you have a Live Spaces blog (although it will work with other blog sites)

PicLens Firefox plugin
quick and easy image / video search with cool GUI via firefox browser

Monday, July 7, 2008

Daily Links 07/07/2008

How to display a dataset in a silverlight dataGrid
really handy stuff for those who were used to exposing datasets (which are not available in silverlight) to the UI.

Batching WCF calls
...what was also cool in this article was the code snippet to generically build a list of knownTypes on the base service interface

LINQ Farm: Lambdas
"Lambdas are a simple technology with an intimidating name. They sound like they are going to be difficult to understand, but in practice prove to be relatively trivial."

Ordering Code Construction Tasks
Excellent article on general strategies to follow when embarking on a new project.

Extension Methods + Attributes = A Whole New World!
The article title is a bit over-zealous, but the content is interesting non-the-less.

Getting Things Done with TodoList
Software that will maintain your tasks: everything from a simple todo list, to complicated task dependancy projection (ala M$ Project)

New to NUnit 2.5 - Generic Test Fixtures
Use the same code to test classes of a base type, or that share a common interface

Building classes at runtime using TypeBuilder
"TypeBuilder provides a set of routines that are used to define classes, add methods and fields, and create the class inside the runtime"
There are some security concerns if you're going to attempt this on a silverlight client
see here for a sample silverlight implementation

Fun with Continuous-Integration. Introducing: BILTONS
Customize the sounds that CC.NET makes when passes / fails per author.

StudioTools for Visual Studio
Some FREE plugin tools for VS, including Code Metrics, Smart Go-TO, Open File by Name, Tear-Off Editor Window, Incremental Search, and File Explorer
The same company also has a handy MSTest NUnit adapter
Microsoft Team System NUnit Adapter

Investing in a Quality Programming Chair
One of developer "must-haves"

Wednesday, July 2, 2008

Daily Links 02/07/2008

Silverlight Desktop
"A framework that allows you to dynamically load Silverlight modules into resizable draggable windows."

Silverlight 2 reference poster

Query Controls using LinQ

Scale Databases Cheaply - Sharding

How to implement SCRUM in 10 easy steps

Disadvantages of Agile Software development
Basically agile is an intense process requiring a high level commitment from everyone involved, without which it will most likely fail and lead to those "agile didn't work for us" comments.

Writing Good User Stories
"User Stories are a simple way of capturing user requirements throughout a project - an alternative to writing lengthy requirements specifications all up-front."

State Machines in C# 3.0 using T4 Templates
Some interesting code making use of partial methods and classes to implement a state machine

Free chat program which includes video conferencing features