Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DisplayAttribute name property not working in Silverlight

I am binding DataGrid.ItemsSource property to the List<PersonDetails> object. I am getting datas through Silverlight-enabled WCF Service. So the PersonDetails class is implemented in Web Project. Each DataGrid's header text is changing as i want if the class is located in Silverlight project. But then I can not use this class in the web service. The only solution is to add same class in to the both of the projects. But, is there any other way?

The class looks like that:

[DataContract]
public class PersonGeneralDetails
{
    // Properties

    [DataMember]
    [DisplayAttribute(Name = "Sira")]
    public int RowNumber { get; set; }

    [DataMember]
    [DisplayAttribute(Name = "Seriyasi")]
    public string SerialNumber { get; set; }
}

It seems attributes aren't generated in web project. I know that I can change header text using DataGrid events. But i want to make it work using attributes.

like image 611
Farhad Jabiyev Avatar asked Mar 08 '13 11:03

Farhad Jabiyev


1 Answers

The problem is the WCF DataContract is an inter-operable mechanism that can be used across languages and platforms.

If you take a look to serialized data generated by the DataContractSerializer (or its code in System.Runtime.Serialization.dll, specifically InternalWriteObjectXyz() methods) you'll see that it merely serializes values into a simple XML message. Nothing related to .NET Framework will be there so all kind of attributes, both custom and compiler generated, will be stripped out and won't even received by the client.

It works creating a copy of your data and sending them from server to client, clients will then create a new class with the same signature. Note: a NEW CLASS with the same signature, NOT JUST A NEW OBJECT of the original class.

Of course there are some workaround for this. You may write your own serializer (see this post on SO for an example) or your own ISerializationSurrogate.

If you can deploy/share your assemblies to your clients you have a nice workaround: just deploy them and DataContractSerializer will build the right object on your clients (exactly the same one you had on the server, with all its attributes). Just remember that:

  • If custom attributes comes from run-time values (for example because of localization) then they'll be resolved on the client, not on the server (because attributes will be created on the client, their values won't be included in the XML message).
  • In the client application you need to add a reference to the assembly that contains your types.
  • When you add your service reference you have to instruct VS to use them (or it'll create proxies), in the Service Reference Settings dialog select Reuse types in referenced assemblies (you can limit this to only assemblies you want to share).
like image 106
Adriano Repetti Avatar answered Oct 24 '22 01:10

Adriano Repetti