.Net RIA Services: Sharing Code between the Client and Server

.Net RIA Services: Sharing Code between the Client and Server

This is another post in a series of posts about building applications with Microsoft .Net RIA Services and Silverlight 3 and ASP.Net.

In this I’ll talk about how to share code between the server side and the Silverlight client application.

One of the great things in .Net RIA Services is that code that we wrote in the server side can be resued in the client side. To do that, create a new class in the server side called with .shared.cs or .shared.vb suffix (CustomerValidation.shared.cs in this sample).

.Net RIA Services Sharing Code between Client and Server

In this class, code what you’d live to share with the client side, under the rational limitations. To make the code sections shared between the server and the client, decorate them with System.Web.Ria.Data.SharedAttribute. For example:

[Shared]

public class CustomerValidation

{

  [Shared]

  public static bool IsEmailEndsWithDotCom(string email)

  {

    if (email.EndsWith(".com"))

      return true;

    return false;

  }

}

After you build the solution, Visual Studio will copy this file to the Silverlight client application:

.Net RIA Services Sharing Code between Client and Server

and now, you can use this code in the client application, as you did in the server side. Here is an example of me using the shared code in the HomePage class in the Silverlight client application.

.Net RIA Services Sharing Code between Client and Server

Enjoy!