Monday, November 23, 2009

Silverlight 3, RIA services, and Resource (RESX) Files

One of the advantages of using RIA services is that you can build your domain entity tier independently from the rest of the application tiers and then wire it in as needed, whether as LINQ or simple POCO classes.

If you decide to annotate your entities with resources, it can get a little dicey. Most examples online focus on resource files within Silverlight or entities defined within Silverlight. However, it is quite common to have existing POCO objects that point to a resource file. For example, I might declare a user entity like this:

public class User
    {
        [Key]
        [ReadOnly(true)]
        public int ID { get; set; }

        [Display(Name="UserName", Description="UserNameDescription", ResourceType=typeof(EntityResource))]
        [Required]
        [RegularExpression("^([A-Za-z0-9])+$", ErrorMessageResourceName="BadUserName", ErrorMessageResourceType=typeof(EntityResource))]
        public string UserName { get; set; }
    }

In this example, my resources are defined in the same project as the user entity, in a EntityResource.resx file.

When I build my DomainService to use this object, the first thing I get is an error related to accessing the resource file. I'm told it needs to be flagged as public. This is simple enough: I go into the designer and switch the access the modifier.

RIA Services with Resource File

Now we can compile again, but again, we get an error. This time it's in one of those auto-generated files that ends with .g and it says that my LOB.Entity.EntityResource type doesn't exist! What happened? I marked my domain service with EnableClientAccess, but the resource type doesn't make it to the Silverlight client.

It turns out the magic of RIA (for Silverlight 3) only goes so far ... we need to go ahead and manually bring the resource file over. Fortunately, we can do it in a way that prevents us from having to duplicate code.

In the silverlight project, figure out where you want the resource files to reside. I chose a folder called Links to keep all of my cross-linked resources in one place. On the folder, I right-click and choose "Add Existing Item." I then navigate to the resource file in my server side project, and add it ... as a link.

RIA Services with Resource File

Be sure to add the Designer.cs file as well, and you should be good.

Jeremy Likness