ASP.NET MVC 5: Validating a VAT with ValidationAttribute and EU checkVatService

Validating a VAT with ValidationAttribute and EU checkVatService can be done very easily in a different assembly for using it in all your projects.
Just create a new project (I named it VAT) and follow these steps!

Step 1, add the service refenerence to your project
Right click on References and choose Service Reference. Paste this address http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl type your namespace (I use checkVatService) and hit OK

Step 2, add a repository for the service

using VAT.checkVatService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Text;
using System.Threading.Tasks;

namespace VAT.Repositories {
    public class CheckVatRepository {

        public bool CheckVat( string countryCode, string VAT ) {
            if ( string.IsNullOrEmpty( VAT ) || string.IsNullOrEmpty( countryCode ) )
                return false;

            //If the country code is AT for Austria we need a U before the UID
            if ( countryCode.ToUpper().Equals( "AT" ) ) {
                if ( !VAT.StartsWith( "U" ) )
                    VAT = "U" + VAT;
            }

            var strVat = VAT;
            var strCountry = countryCode;

            var bValid = false;
            var strName = string.Empty;
            var strAddress = string.Empty;

            BasicHttpBinding binding = new BasicHttpBinding();
            binding.Name = "checkVatBinding";
            binding.CloseTimeout = TimeSpan.FromMinutes( 1 );
            binding.OpenTimeout = TimeSpan.FromMinutes( 1 );
            binding.OpenTimeout = TimeSpan.FromMinutes( 1 );
            binding.ReceiveTimeout = TimeSpan.FromMinutes( 1 );
            binding.SendTimeout = TimeSpan.FromMinutes( 1 );
            binding.AllowCookies = false;
            binding.BypassProxyOnLocal = false;
            binding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
            binding.MaxBufferSize = 65536;
            binding.MaxBufferPoolSize = 65536;
            binding.MaxReceivedMessageSize = 65536;
            binding.MessageEncoding = WSMessageEncoding.Text;
            binding.TextEncoding = Encoding.UTF8;
            binding.TransferMode = TransferMode.Buffered;
            binding.UseDefaultWebProxy = true;
            binding.ReaderQuotas.MaxDepth = 32;
            binding.ReaderQuotas.MaxStringContentLength = 8192;
            binding.ReaderQuotas.MaxArrayLength = 16384;
            binding.ReaderQuotas.MaxBytesPerRead = 4096;
            binding.ReaderQuotas.MaxNameTableCharCount = 16384;
            binding.Security.Mode = BasicHttpSecurityMode.None;
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
            binding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
            binding.Security.Transport.Realm = "";
            binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
            binding.Security.Message.AlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Default;

            EndpointAddress addr = new EndpointAddress( "http://ec.europa.eu/taxation_customs/vies/services/checkVatService" );

            try {
                var cvptc = new checkVatPortTypeClient( binding, addr );
                cvptc.checkVat( ref strCountry, ref strVat, out bValid, out strName, out strAddress );
                return bValid;
            }
            catch {
                return false;
            }
            return true;
        }
    }
}

* You need all of the binfing stuff if you plan to use the service in a different assembly like i do. For some reason, didn’t find why, values in a config of a second assembly could not be read!

Step 3, add a class/method for checking
Right click on project, and select Add > Class. Name it something like VatCheckAttribute and paste the followings in it:

using VAT.Repositories;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace VAT.Attributes {

    public class VatCheckAttribute : ValidationAttribute {

        private string _countryCode = "";
        public VatCheckAttribute( string CountryCode ) {
            _countryCode = CountryCode;
        }


        protected override ValidationResult IsValid( object value, ValidationContext validationContext ) {

            if ( (new CheckVatRepository()).CheckVat( _countryCode, (string)value ) )
                return null;

            return new ValidationResult( this.FormatErrorMessage( validationContext.DisplayName ) );

        }
    }
}

And you are done! You can use the validation in a ViewModel like this:

...
using VAT.Attributes;
...
namespace WhatEver{
    [VatCheckAttribute( "EL", ErrorMessageResourceType = typeof( Resources.Strings.Site ), ErrorMessageResourceName = "lblVATError", ErrorMessage = null )]
    public string VAT { get; set; }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s