Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1465
  • Last Modified:

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?
0
quentinA
Asked:
quentinA
  • 2
1 Solution
 
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
 
quentinAAuthor Commented:
thanks again
0

Featured Post

NEW Veeam Agent for Microsoft Windows

Backup and recover physical and cloud-based servers and workstations, as well as endpoint devices that belong to remote users. Avoid downtime and data loss quickly and easily for Windows-based physical or public cloud-based workloads!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now