views:

89

answers:

3

I have a Person and an Organisation Entity: Person looks like this:

public class PersonEntity
{
public string FirstName {get;set;}
public string LastName {get;set;}

public bool IsValid(PersonEnum Attribute, string AttributeValue)
{
if(attribute == PersonEnum.FirstName && AttributeValue == null)
return false;
if(attribute == PersonEnum.LastName && AttributeValue == null)
return false;

return true;
}
}

I have a PersonEnum //Created just to support IsValid Method.

public enum PersonEnum
{
FirstName, LastName
}

Similarly Organisation has an Entity and an Enum.

I want to create a Helper class as following to have all validations at one place, I want to pass the name of Class (Entity), its member (Enum) and value:

public class Helper
{
//Not sure how to pass A Class def and an attribute. 
public static ValidateEntityAttribute(*[EntityEnum]*,*[EntityEnum]*, Value)
{
.. do something that looks at the Entity and call it's IsValid method.
}
}

Can It be done without using Reflection, I also want this to be generic so I can use it for all my entities.

Any Suggesstions?

+2  A: 

I would strongly recommend doing this another way, as your design will make it much harder to change your classes. To change a class you would have to update a validation method in a different class, and an enum for the parameters.

One better way to do this is to setup a Rule Violation scheme as done in the NerdDinner tutorial.

C. Ross
A: 

I agree with C. Ross; you'll need a lot of reflection to get this working and have no compile time support what so ever. It takes a lot of time to build it this way and a lot of time to maintain.

You'd be better of using a Validation Framework as Mattias also suggests. There are several frameworks to choose from. I'm personally a fan of the Microsoft Enterprise Library Validation Application Block (VAB), but it has a steep learning curve. Another good option is .NET 3.5 DataAnnotations, which has less features, but is easier to learn.

If you're interested in VAB, I'd advise you to start by downloading the Hands On Lab and reading the ValidationHOL.pdf tutorial that comes with it. It gives a good impression of what can be achieved with VAB. I've written multiple articles on integrating VAB with ADO.NET Entity Framework. You can start reading here.

Good luck

Steven
A: 

The Enterprise Library Validation is really good. I will recommend it. If you want to do something lightweight for a small project then heres a solution:

You will have to use reflection but lets see how you can achieve this in most simple way...

public class Helper 
{
public static ValidateEntityAttribute(Type objectType, Enum objectEnum, object Value) 
{ 
if(objectType.GetMethod("IsValid", BindingFlags.NonPublic).Invoke(null, BindingFlags.NonPublic, null, new object[{objectEnum, Value}], null))
throw new Exception("Invalid entry");
} 
}
Usman Akram
Similar to what I was looking for. I guess i will have to use reflection! Thanks