Demonstrating JavaScript and NuGet with DOTS Address Validation 3

In this demonstration I am going to show you how to implement our DOTS Address Validation 3 web service with JavaScript and no Asp.Net markup tags using Visual Studio. We are going to create a form for address inputs, similar to what you would see on a checkout page, which will call our API to validate the address. Although, we could call the web service directly from JavaScript, we would then be forced to expose our license key. So we will use an aspx.cs page to handle our call to the service API, keeping our license key safe from prying eyes. In this demonstration, I will also show you how to add the NuGet version of DOTS Address Validation 3 to the project so that you are always using our best practices and speeding up your integration.

First, create a new empty web site, which I am going to call, cSharpJavascriptAjax. Then I am going to add a new html page called, Addressvalidation.html.

Next, we are going to add the markup for the form. Add the following code in between the body tag.

    
Enter An Address
(US addresses only)

Business Name:
Address 1:
Address 2:
City:
State:
PostalCode:

This form was designed using the table structure for the layout. You will likely want to create the layout using divs, which is more appropriate. Here is what the page looks like in the browser.

To speed things up a bit, I am going to include jQuery in the header so we can utilize some of the short cut functions. Of course, all of this can be done in pure JavaScript.


    
    Address Validation 3
	


For the action we will take when the Complete button is clicked, we will create the submit function. This will take in all the values from the form, call the web service and then display the response to the screen. I added an alert and left the URL blank, this will allow for a quick test to make sure what we have is working. Later we will update the failure and success sections as well. For now, they will simply display an alert for testing.

First, let’s start by making sure we are getting all the inputs into the submit function and are getting all the inputs back. I am going to display an alert with DataValue variable so we can see what we have.


Good, now that we know that is working, we will need to make the call to the web service. Like I mentioned before, we could call the service directly but using JavaScript would make the license key visible. So we are going to leverage asp.net for security by creating and empty aspx page and add a method to the aspx.cs page to handle the call. Let’s go ahead and add the aspx/aspx.cs page to the project and call it, ServiceObjectsAPIHandler.

Here is our empty aspx.cs page, where we will be adding our function. It will go below the Page_Load method.

Let’s call the method, CallDOTSAddressValidation3_GBM. There are two things to notice with the signature for this method. We decorate the method with the WebMethod attribute so that our new method can be exposed as a web service method. And, we declare it as static because of the stateless nature of the static methods. An instance of a class does not need to be declared.

        [WebMethod]
        public static string CallDOTSAddressValidation3_GBM(string InputText)
        {
            return InputText;
        }

To test things out, for now we will just take one string input and return it to the Ajax call where we will display it. In order to do this, we will need to adjust our DataValue call in the script on the html page.

var DataValue = "{InputText:'Hello World!'}";

We will also need to add the URL and method to the Ajax call.

url: "ServiceObjectsAPIHandler.aspx/CallDOTSAddressValidation3_GBM",

I also adjusted the alerts so we can see the success or fail.

failure: function (response) {
                    alert(response.d + " :(");
                },
                success: function (response) {
                    alert(response.d + " :)");
                }

Great! That worked! Now, let’s write up the code in the aspx.cs page to make the call to the service. We could grab some sample code from the web site and walk through it, but we have documentation and tutorials already on how to do that. Instead, I am going to take a short cut and grab what I need from NuGet. We offer NuGet packages for most of our services, which include best practices such as failover configurations and speeding up the integration time.

To do this, we will need to open up the NuGet Package Manager in Visual Studio under the Tools menu option. When browsing for our services, you can type “Serviceobjects”. You should see a list of available Service Objects NuGet packages to choose from.

Select DOTSAddressValidation3US, you will be prompted to select the project you want to install it under. Select the project and then click install.

Once the installation is complete, a ReadMe file will automatically open that will contain a lot of information about the service. You will also notice a few things were added to your project. First, a DLL for DOTSAddressValidation3US was added to the bin folder and was referenced in your project.

Next, an AV3LicenseKey app setting was added to your web.config file with the value “WSXX-XXXX-XXXX”. You will need to substitute this value for the key you received from Service Objects.

    
      
    

Also in the web.config you will see several endpoints were added. These will be used in the pre-packaged code to determine how to call the service based on your key.


        
            
                
                
            
        
        
            
            
            
        
    

Now that we have the NuGet package added to the project, we can use it. Next is the code that will use the DOTSAddressValidation3US DLL by loading it up with the input parameters, making the call to the service, then working with the response and finally sending the data back out to our JavaScript.

First we get the license key from the web configs file.

string LicenseKey = System.Configuration.ConfigurationManager.AppSettings["AV3LicenseKey"];

Then we make the call to the service. You will notice that we throw in a Boolean parameter at the end of the call to GetBestMatches for live or trial. This is an indicator that will tell the underlying process which endpoints to use. A mismatch between your license key and this Boolean flag will cause the call to the service to fail.

DOTSAddressValidation3US.AV3Service.BestMatchesResponse DOTSAddressResponse = DOTSAddressValidation3US.DOTSAV3.GetBestMatches(BusinessName, Address, Address2, City, State, ZipCode, LicenseKey, false);

After we make the call to the service, we will process the response and send the data back to the JavaScript. If there is an error, we will return the error details. Otherwise, we will return a serialized version of the response object. Note that you can also just deal with the response completely here or completely in JavaScript. I mixed it up so you can see a bit of both.

if(DOTSAddressResponse.Error != null)
{
string ErrorDesc = DOTSAddressResponse.Error.Desc;
string ErrorType = DOTSAddressResponse.Error.Type;
      return "Address Error: " + ErrorType + ". " + ErrorDesc;
}
else
{
      return new JavaScriptSerializer().Serialize(DOTSAddressResponse);
     } 

Here is the whole method all together.

[WebMethod]
public static string CallDOTSAddressValidation3_GBM(string BusinessName, string Address, string Address2, string City, string State, string ZipCode)
{
string LicenseKey = System.Configuration.ConfigurationManager.AppSettings["AV3LicenseKey"];
DOTSAddressValidation3US.AV3Service.BestMatchesResponse DOTSAddressResponse = DOTSAddressValidation3US.DOTSAV3.GetBestMatches(BusinessName, Address, Address2, City, State, ZipCode, LicenseKey, false);
            if(DOTSAddressResponse.Error != null)
            {
                string ErrorDesc = DOTSAddressResponse.Error.Desc;
                string ErrorType = DOTSAddressResponse.Error.Type;
                return "Address Error: " + ErrorType + ". " + ErrorDesc;
            }
            else
            {
                return new JavaScriptSerializer().Serialize(DOTSAddressResponse);
            }
}

Now we will turn our attention back to the JavaScript and update our submit function. All we really have to deal with now is the response from the aspx method call. Here is the portion of the Ajax call implementing that.

failure: function (response) {
    alert('Something went wrong!');},
success: function (response) {
    if ((response.d + "").startsWith("Address Error")) {
         alert(response.d);
    }else {
         var AddressResponse = JSON.parse(response.d);
         if (AddressResponse.Addresses[0].DPV === "1") {
              alert("Good Address!");
         }else {
              alert("Not Good Address: " + AddressResponse.Addresses[0].DPVNotes);
         }
    }}

Success or failure here does not mean that the address is good or not. It is really just a success or failure of the call to the aspx web method. On failure, we simply make an alert stating something went wrong. On success, we examine the response value, determine if the address was good or not and display the appropriate response. Here is the whole submit function.

function submit() {
var DataValue = "{BusinessName:'" + $('#inputBusinessName').val() + 
"',Address1:'" + $('#inputAddress').val() + 
"',Address2:'" + $('#inputAddress2').val() + 
"',City:'" + $('#inputCity').val() + 
"',State:'" + $('#inputState').val() + 
"',ZipCode:'" + $('#inputZip').val() + "'}";
            $.ajax({
                type: "POST",
                url: "ServiceObjectsAPIHandler.aspx/CallDOTSAddressValidation3_GBM",
                data: DataValue,
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                failure: function (response) {
                    alert('Something went wrong!');
                },
                success: function (response) {
                    if ((response.d + "").startsWith("Address Error")) {
                        alert(response.d);
                    }
                    else {
                        var AddressResponse = JSON.parse(response.d);
                        if (AddressResponse.Addresses[0].DPV === "1") {
                            alert("Good Address!");
                        }else {
                            alert("Not Good Address: " + AddressResponse.Addresses[0].DPVNotes);
                        }
                    }
                }
            });
        }

 

Here is a good address.

 

And here is a bad address.

 

In the submit function, we did the most basic check to see if an address was good or not.

if (AddressResponse.Addresses[0].DPV === "1")

But many more data points from the response can be used to make any number of conclusions about an address. One thing you will notice is that AddressResponse.Addresses is an array. A check to see if multiple addresses are returned can be valuable because in certain situations more than one address may be returned. One example is when an East and a West street address are equally valid responses to an input address. In this case you may want to display both addresses and let the user determine which to use. You may want to evaluate the individual address fragments or the corrections that were made to the address.

The data points associated to the DOTS Address Validation US 3 service can be found on our development guide page for the service.

The following is commented out code that I added to the submit method for easy access to the various output data points.

//AddressResponse.Addresses[0].Address1
//AddressResponse.Addresses[0].Address2
//AddressResponse.Addresses[0].City
//AddressResponse.Addresses[0].State
//AddressResponse.Addresses[0].Zip
//AddressResponse.Addresses[0].IsResidential
//AddressResponse.Addresses[0].DPV
//AddressResponse.Addresses[0].DPVDesc
//AddressResponse.Addresses[0].DPVNotes
//AddressResponse.Addresses[0].DPVNotesDesc
//AddressResponse.Addresses[0].Corrections
//AddressResponse.Addresses[0].CorrectionsDesc
//AddressResponse.Addresses[0].BarcodeDigits
//AddressResponse.Addresses[0].CarrierRoute
//AddressResponse.Addresses[0].CongressCode
//AddressResponse.Addresses[0].CountyCode
//AddressResponse.Addresses[0].CountyName
//AddressResponse.Addresses[0].FragmentHouse
//AddressResponse.Addresses[0].FragmentPreDir
//AddressResponse.Addresses[0].FragmentStreet
//AddressResponse.Addresses[0].FragmentSuffix
//AddressResponse.Addresses[0].FragmentPostDir
//AddressResponse.Addresses[0].FragmentUnit
//AddressResponse.Addresses[0].Fragment
//AddressResponse.Addresses[0].FragmentPMBPrefix
//AddressResponse.Addresses[0].FragmentPMBNumber

And here is the same thing but for the Error object in the aspx page.

//string ErrorDesc = DOTSAddressResponse.Error.Desc;
//string ErrorDescCode = DOTSAddressResponse.Error.DescCode;
//string ErrorType = DOTSAddressResponse.Error.Type;
//string ErrorTypeCode = DOTSAddressResponse.Error.TypeCode;

I hope this walk-thru was helpful in demonstrating how to implement our DOTS Address Validation 3 web service with JavaScript and no Asp.Net markup tags using Visual Studio. If you have any question, please feel free to contact Service Objects for support.