How to use "ErrorMessageResourceType" in DataAnnotations in a Windows Store app (Metro)

In my Windows Store (Metro) application, I use DataAnnotations for my objects. Everything is working fine.

Now I am trying to place my lines in Resource.resw files. For DataAnnotations, 2 properties must be populated: ErrorMessageResourceName and ErrorMessageResourceType . How to use ErrorMessageResourceType for new resource types?

 public class Person : Entity { private string _firstName; [Required( ErrorMessageResourceName = "GenericFieldRequired", ErrorMessageResourceType = typeof( ??? ))] public string FirstName { get { return _firstName; } set { SetPropertyChanged( ref _firstName, value, this ); } } } 

Any suggestions?

UPDATE: I found a Visual Studio tool that automatically creates a Resources.cs file:

Resw generator

+4
source share
1 answer

After a lot of digging, I think I understand why you have problems.

In other types of projects, the resource file is automatically converted to a class with static methods called the name of the resource key.

It is not possible to do this automatically, so I wrote a T4 template that will help you with this.

 <#@ template debug="false" hostspecific="True" language="C#" #> <#@ assembly name="System.Core" #> <#@ import namespace="System.Linq" #> <#@ import namespace="System.Text" #> <#@ import namespace="System.Xml" #> <#@ assembly name="System.Xml" #> <#@ import namespace="System.IO" #> <#@ import namespace="System.Collections.Generic" #> <#@ output extension=".cs" #> using Windows.ApplicationModel.Resources; <# var namespaceName = System.Runtime.Remoting.Messaging.CallContext.LogicalGetData("NamespaceHint"); #> namespace <#= namespaceName #> { public class ResourceHelper { private static readonly ResourceLoader resourceLoader = new ResourceLoader("Resources"); <# using (XmlReader reader = XmlReader.Create(Host.ResolvePath("Resources.resw"))) { bool found=reader.ReadToFollowing("data"); while(found) { reader.MoveToFirstAttribute(); string name = reader.Value; #> public static string <#= name #> { get { return resourceLoader.GetString("<#= name #>"); } } <# found=reader.ReadToFollowing("data"); } }#> } } 

If you place the template in the same folder as the resource file, it will output the ResourceHelper.cs file. This can then be used in your object model: -

  [Required(ErrorMessageResourceName = "validation_string", ErrorMessageResourceType = typeof(ResourceHelper))] 

Please note that there are several limitations. Firstly, I am not very good at T4 templates, so the code can probably be greatly improved. For now, you need to make sure that the name you give to your resource will result in a valid method name - don't put spaces there!

Secondly, the template will not be automatically generated when adding a new key / value to the resource file, you must enter the template and click "Save".

In addition, it should work fine - I hope this helps!

+7
source

All Articles