Enterprise Library 6 Validation Block

I'm trying to get validation using app.config.
I have exactly same problem as here : http://stackoverflow.com/questions/19046427/enterprise-library-6-validation-config-file
i.e.when i configure TypeValidation to validate a class through config file it does not pick up. but when i add Data Annotations it Validates Correctly.

I have used Nuget to add references to the latest version of the Enterprise Library.

I have tried the solution offered in the S.O. question  (see below):

class Program
    {
        static void Main(string[] args)
        {
          
            var person = new Person();// {FirstName = "Joe"};

            ValidationFactory.SetDefaultConfigurationValidatorFactory(new SystemConfigurationSource());

            var personValidator = ValidationFactory.CreateValidator<Person>();

            var results = personValidator.Validate(person);


            if (!results.IsValid)
            {
                foreach (var validationResult in results)
                {
                    Console.WriteLine(validationResult.Message);
                }
            }
            else
            {
                Console.WriteLine("Person was valid !!!");
            }

            Console.ReadLine();


        }
    }

Open in new window


App.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
        <section name="validation" type="Microsoft.Practices.EnterpriseLibrary.Validation.Configuration.ValidationSettings, Microsoft.Practices.EnterpriseLibrary.Validation, Version=6.0.0.0, Culture=neutral, PublicKeyToken=null" requirePermission="true" />
    </configSections>
    <validation>
        <type name="ValidationV2.Person" defaultRuleset="Validation Ruleset"
            assemblyName="ValidationV2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
            <ruleset name="Validation Ruleset">
                <properties>
                    <property name="FirstName">
                        <validator type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.NotNullValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=6.0.0.0, Culture=neutral, PublicKeyToken=null"
                            messageTemplate="First name can not be null" name="Not Null Validator" />
                    </property>
                </properties>
            </ruleset>
        </type>
    </validation>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1"/>
    </startup>
</configuration>

Open in new window


But when I run it I get the following exception:

System.Configuration.ConfigurationErrorsException was unhandled
  HResult=-2146232062
  Message=An error occurred creating the configuration section handler for validation: Could not load file or assembly 'Microsoft.Practices.EnterpriseLibrary.Validation, Version=6.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) (E:\VisualStudioProjectsDefault\ValidationV2\ValidationV2\bin\Debug\ValidationV2.vshost.exe.Config line 4)
  Source=System.Configuration
  BareMessage=An error occurred creating the configuration section handler for validation: Could not load file or assembly 'Microsoft.Practices.EnterpriseLibrary.Validation, Version=6.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
  Filename=E:\VisualStudioProjectsDefault\ValidationV2\ValidationV2\bin\Debug\ValidationV2.vshost.exe.Config
  Line=4
  StackTrace:
       at System.Configuration.BaseConfigurationRecord.FindAndEnsureFactoryRecord(String configKey, Boolean& isRootDeclaredHere)
       at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
       at System.Configuration.BaseConfigurationRecord.GetSection(String configKey)
       at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName)
       at System.Configuration.ConfigurationManager.GetSection(String sectionName)
       at Microsoft.Practices.EnterpriseLibrary.Common.Configuration.SystemConfigurationSource.DoGetSection(String sectionName)
       at Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileBasedConfigurationSource.GetSection(String sectionName)
       at Microsoft.Practices.EnterpriseLibrary.Validation.Configuration.ValidationSettings.TryGet(IConfigurationSource configurationSource)
       at Microsoft.Practices.EnterpriseLibrary.Validation.ConfigurationValidatorFactory.InnerCreateValidator(Type targetType, String ruleset, ValidatorFactory mainValidatorFactory)
       at Microsoft.Practices.EnterpriseLibrary.Validation.CompositeValidatorFactory.<>c__DisplayClass1.<InnerCreateValidator>b__0(ValidatorFactory f)
       at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
       at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()
       at System.Linq.Enumerable.Count[TSource](IEnumerable`1 source)
       at Microsoft.Practices.EnterpriseLibrary.Validation.CompositeValidatorFactory.GetValidator(IEnumerable`1 validators)
       at Microsoft.Practices.EnterpriseLibrary.Validation.CompositeValidatorFactory.InnerCreateValidator(Type targetType, String ruleset, ValidatorFactory mainValidatorFactory)
       at Microsoft.Practices.EnterpriseLibrary.Validation.ValidatorFactory.FindOrCreateValidator(ValidatorCacheKey cacheKey, Func`3 wrapAndInstrument)
       at Microsoft.Practices.EnterpriseLibrary.Validation.ValidatorFactory.CreateValidator[T](String ruleset)
       at Microsoft.Practices.EnterpriseLibrary.Validation.ValidatorFactory.CreateValidator[T]()
       at Microsoft.Practices.EnterpriseLibrary.Validation.ValidationFactory.CreateValidator[T]()
       at ValidationV2.Program.Main(String[] args) in e:\VisualStudioProjectsDefault\ValidationV2\ValidationV2\Program.cs:line 21
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.IO.FileLoadException
       HResult=-2146234304
       Message=Could not load file or assembly 'Microsoft.Practices.EnterpriseLibrary.Validation, Version=6.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
       Source=System.Configuration
       FileName=Microsoft.Practices.EnterpriseLibrary.Validation, Version=6.0.0.0, Culture=neutral, PublicKeyToken=null
       FusionLog==== Pre-bind state information ===
LOG: DisplayName = Microsoft.Practices.EnterpriseLibrary.Validation, Version=6.0.0.0, Culture=neutral, PublicKeyToken=null
 (Fully-specified)
LOG: Appbase = file:///E:/VisualStudioProjectsDefault/ValidationV2/ValidationV2/bin/Debug/
LOG: Initial PrivatePath = NULL
Calling assembly : System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: E:\VisualStudioProjectsDefault\ValidationV2\ValidationV2\bin\Debug\ValidationV2.vshost.exe.Config
LOG: Using host configuration file: 
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///E:/VisualStudioProjectsDefault/ValidationV2/ValidationV2/bin/Debug/Microsoft.Practices.EnterpriseLibrary.Validation.DLL.
WRN: Comparing the assembly name resulted in the mismatch: PUBLIC KEY TOKEN
ERR: Failed to complete setup of assembly (hr = 0x80131040). Probing terminated.

       StackTrace:
            at System.Configuration.TypeUtil.GetTypeWithReflectionPermission(IInternalConfigHost host, String typeString, Boolean throwOnError)
            at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.Init(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord)
            at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.InitWithRestrictedPermissions(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord)
            at System.Configuration.RuntimeConfigurationRecord.CreateSectionFactory(FactoryRecord factoryRecord)
            at System.Configuration.BaseConfigurationRecord.FindAndEnsureFactoryRecord(String configKey, Boolean& isRootDeclaredHere)
       InnerException: 

Open in new window




I've trawled online, but can't find anything to help make it work.
Does anyone have any suggestions about what I'm doing wrong?
quentinAAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

käµfm³d 👽Commented:
Adding the public key token (31bf3856ad364e35) to the configuration file made it work for me--and by "work" I mean the error you describe went away:

Added in lines 4 and 12
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="validation" type="Microsoft.Practices.EnterpriseLibrary.Validation.Configuration.ValidationSettings, Microsoft.Practices.EnterpriseLibrary.Validation, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
  </configSections>
  <validation>
    <type name="ValidationV2.Person" defaultRuleset="Validation Ruleset"
        assemblyName="ValidationV2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
      <ruleset name="Validation Ruleset">
        <properties>
          <property name="FirstName">
            <validator type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.NotNullValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                messageTemplate="First name can not be null" name="Not Null Validator" />
          </property>
        </properties>
      </ruleset>
    </type>
  </validation>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
</configuration>

Open in new window


Screenshot
Your validation rule seems to need a bit of tweaking  = )
0
käµfm³d 👽Commented:
Actually, strike my very last comment. Your rule is fine. I had the wrong namespace in the config file. (Doh!)

Screenshot
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
quentinAAuthor Commented:
thanks again
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.