This is a mirror of official site: http://jasper-net.blogspot.com/

Share code between client and server

| Tuesday, April 12, 2011
One of the challenges of writing managed components for Silverlight is the fact that it is not possible to use a normal .NET assembly in Silverlight projects. One way to get around this issue is to use linked and partial classes in Silverlight projects.

How to use linked classes in Silverlight

Let’s say I have a solution with 3 projects: a Silverlight client (client), a web application (web) and a .NET class library (lib). The lib contains entities and business logic that I wish to share between the client and the web.

It would be great to reference the lib from the client but that is not an option in Silverlight. Of course I can copy the content of the lib to the client, but that is really not an option either; nobody wants to maintain to sets of the same business logic.

Instead I can link the files from the lib to the client. In this sample I have a Person entity in the lib project that I wish to share with the client. In the client I choose to add an existing item and find the class from the lib project I wish to add. I click on the arrow next to the add button and select "Add as link".

clip_image001_thumb.png?w=353&h=236

This will add the Person entity class to my client project and it’s nothing more then a link to the class from the lib project. The link will make sure that the class is compiled into both projects at compile time.

The downside of this solution is that even though I can share the classes, it’s not possible to put logic into the classes that is server side or client side only. One way to get around that is to use partial classes.

Partial classes on the client and the server

In the lib project I can create a server side partial class of our business logic and I can do the same on the client. In this sample I have create a server side only version of the Person entity classes "Person.server.cs" and a client side only version of the Person entity called "Person.client.cs". The Person entity itself is still linked between the client and the server. Remember that for this to work the namespace must be the same between all partial files! This enables the separation of logic running only server or client side.

Read more: XAMLGEEK

Posted via email from Jasper-net

0 comments: