Silverlight and RIA: Sharing Your Business Object Files
Tue, Nov 10 2009 12:23
So I have read in dozens of places that you can easily share a source code file between your business objects and your Silverlight project. So I thought I would try it. No go.
[To begin with an overview of Silverlight, RIA, and your business objects, start here.]
Supposedly, if you created a file in your business object of the form myName.shared.vb or myName.shared.cs the compiler will automatically generate the file in your Silverlight project as well. This allows you to share the same code between the business object and Silverlight.
Many hours of trying, Bing'ing, and reading later … still no go.
Then I re-read the RIA Services Overview document that is provided with the RIA download. Reading it carefully, it starts to become clear that there are TWO things that a file needs before it will be shared with your Silverlight project:
- It must be named appropriately: myName.shared.vb or myName.shared.cs
- It must exist in the project that is linked to the Silverlight project.
This second item is the more challenging item because in most cases, your Silverlight project is linked to a Web project.
As far as I know, it is not possible to re-point the link from a Web project to a business object class library component because Silverlight cannot reference a standard class library. It can only reference a Silverlight class library or a Web project.
So I did the following:
- Named the file using the .shared.vb/.shared.cs syntax.
- Used the Add Link feature of Visual Studio projects to manually define a link between the shared file and the Web project.
The second step required the following:
1. Right click on the Web project and select Add | Existing Item.
2. In the Add Existing Item dialog, select the file and select Add As Link from the Add button drop down menu.
This adds the file as a link to the Web project.
Now that the shared file is in the Web project, when you compile Silverlight will generate the copy. You can confirm this by following these steps:
1. Select the Silverlight project.
2. Click the Show All Files button in the Solution Explorer toolbar.
3. Open the Generated_Code node.
The shared file should exist under this node.
Use this technique any time you have code in your business objects that you want to share "as is" with the Silverlight project.
[For a more detailed example of using this technique to share a file, see this post.]