0

I've a c# application(in fact it runs into a windows service or like a windows application).

In receive the configuration for one run of the service/application from an XML file.

This XML file is in fact only my data serialized/deserialized in XML. It's one of my other application that generate it.

Before running the business code, I would like to ensure that the configuration file is valid.

By this I mean things like "This String must not be null", "This TimeSpan must have a value greater than XYZ", ...

So only verification that can be made by seing the content of the field(no need to access to something else).

It reminds me a lot the Data Annotation that I used in asp.Net MVC, and I would like if there is something similar for simple c# code, without having to load the whole asp.net MVC dll.

My other option is to implement a method "Validate()" which throw an exception if one field is incorrect, but I will have a lot of if(String.IsNullOrEmpty() and other dummy validations.

I do not want to implement myself a big validator that uses reflexion, it's a bit overkill for only a small configuration file verification.

The application which generate those file could also be interessted to use those same validation.

Edit: I've to use .Net 3.5

J4N
  • 19,480
  • 39
  • 187
  • 340

2 Answers2

1

This question looks like a duplicate of the following SO question.

Using ASP.Net MVC Data Annotation outside of MVC

Edit: Seeing as you say the ValidationContext isn't available I would recommend writing some custom code that uses Reflection and evaluates all the attributes on the properties for you.

See the answer to this question for an example of how it can be done.

ASP.Net MVC 2 Controller's TryValidate doesn't validate the List<> items within the model

Community
  • 1
  • 1
Johann Strydom
  • 1,482
  • 14
  • 18
  • "I was looking for a .Net 3.5 solution - ValidationContext is not available before .Net 4.0 " First comment of the selected solution. Like I previously said, I need to work with .Net 3.5 – J4N Nov 23 '12 at 14:48
0

I used the IDataErrorInfo(the same class will be used in the wpf application). And with a custom method where I check every possible attribute here.

Here is the method:

 public Boolean IsModelValid()
    {
        Boolean isValid = true;
        PropertyInfo[] properties = GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);

        foreach (PropertyInfo p in properties)
        {
            if (!p.CanWrite || !p.CanRead)
            {
                continue;
            }
            if (this[p.Name] != null)
            {
                isValid = false;
            }
        }
        return isValid;
    }
J4N
  • 19,480
  • 39
  • 187
  • 340