Wednesday 4 June 2014

Using Data Annotations with Portable Class Libraries

I am currently writing an application that’s targeting multiple platforms – iOS, Android, Windows Phone as clients, and naturally .NET on the server which will be hosted in Azure. I’m making good use of portable class libraries, so that I can share as much code between my clients as possible (and I’m using Xamarin to make all this possible).

For my client projects I have two shared libraries – one with interfaces, another with implementations. As an example I have a DTO class on the client as follows…

public class AccountInformationRequest
{
public string Token { get; set; }

public string MSISDN { get; set; }

public string Carrier { get; set; }
}



This class is also used on the server in a controller method…

public async Task<AccountInformation> PostAccountInformation(AccountInformationRequest request)
{
return await _accountInformationService.GetAccountInformation(request);
}



On the server however I want to use data annotations to minimise the amount of code I need to write in order to validate the incoming request but this poses a problem – the AccountInformationRequest type is defined in a Portable Class Library, and if I update it to add on the data annotation attributes then my PCL will be re-targeted and won’t then run on all of my desired client platforms.


As usual in programming, another level of indirection solves every problem. Since .NET 1.0 we’ve had ICustomTypeDescriptor, and indeed one of the first articles I wrote online was about this interface (the article is long gone, it was written in 2001 ish). Since .NET 2 things have got measurably better for anyone wanting to do some spelunking with types, as it released the TypeDescriptor and TypeDescriptorProvider support. Fast forward a few more years and we now have a very simple way to augment one class with metadata from another – the massively named ‘AssociatedMetadataTypeTypeDescriptionProvider’.


What this class allows you to do is say “Hey, this class X provides metadata for that class Y”. Or more to the point for this article, “This server class which has all the attributes I need replaces the metadata for the PCL class”. All you need to do is create a second class which has all the metadata attributes you need (in my case just validation), then register it. My server side class is as follows…

public class AccountInformationRequestServer
{
[Required]
public string Token { get; set; }

[Required]
public string MSISDN { get; set; }

[Required]
public string Carrier { get; set; }
}



Then I can just register it inside Global.asax…

TypeDescriptor.AddProvider
(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(AccountInformationRequest),
typeof(AccountInformationRequestServer)),
typeof(AccountInformationRequest));



The registration looks a little cryptic, so I’ve altered it below to show the orginalClass (that being the class defined in the PCL) and the metadataClass (that being the one defined server side)…

TypeDescriptor.AddProvider
(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(originalClass), typeof(metadataClass)),
typeof(originalClass));



That’s all there is to it. Now I can make an API call from the client, and have API validation on the server, whilst still using the same datatypes in both PCL and full fat .NET.


You’ll find the AssociatedMetadataTypeTypeDescriptionProvider class defined within System.ComponentModel.DataAnnotations (in the assembly with the same name).


17 comments:

Unknown said...

Very cool stuff. I am just about to start a strikingly similar project for a client and this will be very helpful! Thank you sir.

Unknown said...

Portable class libraries contain some of the articles and materials for students as well. Saint Michael's College libraries have been using an old method of essay writing help service assignments within the class activities. Among those - citations and reminders as well as footnotes.

Richard Majece said...

I think that randomness isn't the best idea here. I am sure that https://pro-academic-writers.com/blog/harvard-format will help you to understand all the importance of my words. Just pay attention on education.

blackkutty said...

Extremely cool stuff. I am going to begin a strikingly comparative task for a customer and this will be extremely useful!
Article Submission sites | Latest Updates

admin said...

It’s very excellent information and more real facts to provided that post.Thank you for sharing this information. 500-701 exam dump

Unknown said...

Thanks for sharing the valuable information.
Regards,
DOT NET Training Institutes in Chennai|Best DOT NET Training in Chennai|DOT NET Training in Chennai

Martha Jones said...

Code Writing taking to much time because that is not ordinary writing programmer face many errors while writing code. I am also writing a quality code of Tutors Help Online website.

Puremelda said...

You attain full value for the money which you put in to access when you seek the services of our custom dissertation writing help, as well as other types of top research papers from our firm which include dissertations, theses, reviews any different writings.

Unbiased said...

Very informative article, Which you have shared here about the Data Annotations. After reading your article I got very much information and it is very useful for us. Thank you for sharing this article here. unbiased is the best Data annotation platform & block chain based decentralized data marketplace.

ahmed5987 said...

لذلك ، من المهم بالنسبة لك تحديد العقرب إذا كنت مصابًا بالصدمات. إذا لم تكن متأكدًا ، فمن الأفضل أن تطلب المساعدة الطبية لاتخاذ الاحتياطات اللازمة.افضل شركة مكافحة حشرات
شركة مكافحة النمل الابيض بالجبيل
شركة مكافحة حشرات بالجبيل
شركة رش مبيدات بالجبيل

shreekavi said...

Great post. keep sharing such a worthy information
Tally Course in chennai
Tally Course in Bangalore
Tally Training in Bangalore
Tally training in coimbatore
Tally course in madurai
Tally Course in Hyderabad
Tally Classes in Bangalore
Tally institute in Bangalore
Ethical hacking course in bangalore
Selenium Course in Bangalore

subha said...

This blog is very interesting and powerful content. I got more important information and it's very useful for improve my knowledge. lovely page guys
Ai & Artificial Intelligence Course in Chennai
PHP Training in Chennai
Ethical Hacking Course in Chennai Blue Prism Training in Chennai
UiPath Training in Chennai

Teresa Halminton said...

If you have not had Hotmail account, it will be easier to start with hotmail email login

siva said...

Amazing blog,Really useful information to all, Keep sharing more useful updates.
benefits of cloud computing
benefits of deep learning
why we need devops
php vs asp net
javascript interview questions pdf
javascript interview questions for freshers

Snehal Harshe said...

Thank you so much for sharing all this wonderful information !!!! It is so appreciated!! You have good humor in your blogs. So much helpful and easy to read!
Java Classes in Mumbai
Java Classes in Delhi

Ashish said...


When you partner with the Top React Native Mobile App Development Services Company , you get access to a team of talented developers, designers, and project managers. They work together seamlessly to ensure that your mobile app is delivered on time and meets all your requirements.

Angel17 said...

Such an awesome post. Thanks for sharing this information! pool deck repairs near me