Introduction

AFD Robot API makes using address management and bank validation in .NET easy, minimising your work to get an integration up and running quickly, while also providing full flexibility to customise it to your requirements. Regardless of if you are using it with a Windows Form, ASP .NET or a backend application our .NET class library makes integration with your application simple.

If you wish to integrate directly into a WinForms application you may also like to consider looking at the .NET API WinForms Guide.

Setup

To use AFD Robot API you first need to install an AFD product or have access to an Evolution server. You can download data-restricted evaluation products from our website at:

http://www.afd.co.uk/try-it

To use AFD Robot API in .NET simply add a Reference to your project to our class library (AFD.API.dll). To do this right click the References item under your project in Solution Explorer select “Add Reference”, and use the Browse Tab to browse to the library file.

Integrating into any .NET Application

Robot API can be easily used in any .NET application including ASP .NET applications, WPF/Silverlight, backends etc. and you can determine if and how to display results on any interface you provide.

Creating an Instance of the Robot Class

Add the following line to the top of your form’s .cs file to reference the AFD.API:

using AFD.API;

To create an instance of the Robot class add the following line to your code:

Robot robot = new Robot(RobotType.Address);

(You can also use RobotType.Bank or RobotType.Email if wanting to carry out Bank or Email Validation). If you wish to mix Address, Bank and/or Email validation simply create multiple instances of the Robot class.

If using an evolution server rather than a locally installed product set the Authentication property to an instance of the Authentication class for your server, e.g.:

robot.Authentication = new Authentication("http://myserver:81", "333333", "password");

Task Reference for Robot Class

####. Address Lookup (Postcode and Fast-Find)

To find an address record from the postcode or any fragment of the address use the Find method on an instance of the Robot class with the lookup string you wish to use and one of the following operations:

  • Operation.FastFindLookup – Looks up the supplied string which can be a postcode or any fragment of the address.
  • Operation.PostcodeLookup – Looks up a supplied postcode
  • Operation.PostcodePropertyLookup – Looks up a supplied postcode which optionally may also include a property, e.g. “279, B11 1AA”

This will return:

  • > 0 The number of results found
  • < 0 No results have been found (-2) or an error has occurred (use LastErrorText to obtain a human readable message for the error).

You can then iterate through the robot.Records collection to process each result in your application. This collection has the method getField(string) which you can use to return any of the fields for the result.

For example:

// Create instance of the Robot class
Robot robot = new Robot(RobotType.Address);
// Lookup the records
int results = robot.Find("b11 1aa", Operation.FastFindLookup);
// Check for error
if (results < 0) {
    MessageBox.Show(robot.LastErrorText);
    return;
}
// Iterate through results
foreach (AFD.API.Record record in robot.Records) {
    // Obtain the fields you require – some examples:
	string list = record.GetField("List");
	string organisation = record.GetField("Organisation");
	string property = record.GetField("Property");
	string street = record.GetField("Street");
	string locality = record.GetField("Locality");
	string town = record.GetField("Town");
	string postcode = record.GetField("Postcode");
	// display a string for the result
	// - replace with a function to process the result in your application?
	MessageBox.Show(list);
}

The number of results returned for FastFind operations will be limited by the MaxRecords Property of the Robot class instance. When using installed data it may also be limited by the Timeout Property. For evolution the server’s pre-configured MaxSearchTime may be a limiting factor.

To carry out a search for an Address:

  • Call clear to Clear any current address fields.
  • Use the setField method to set the value of each field you wish to search
  • Call Find with Operation.Search (the Lookup parameter will be ignored)

The Find function will return:

  • > 0 The number of results found
  • < 0 No results have been found (-2) or an error has occurred (use LastErrorText to obtain a human readable message for the error).

You can then iterate through the robot.Records collection to process each result in your application. This collection has the method getField(string) which you can use to return any of the fields for the result.

For example:

// Create instance of the Robot class
Robot robot = new Robot(RobotType.Address);
// Set the fields to Search
robot.Clear();
robot.SetField("street", "Commercial Street");
robot.SetField("town", "Birmingham");
// Search for the records
int results = robot.Find(null, Operation.Search);
// Check for error
if (results < 0) {
    MessageBox.Show(robot.LastErrorText);
	return;
}
// Iterate through results
foreach (AFD.API.Record record in robot.Records) {
    // Obtain the fields you require – some examples:
	string list = record.GetField("List");
	string organisation = record.GetField("Organisation");
	string property = record.GetField("Property");
	string street = record.GetField("Street");
	string locality = record.GetField("Locality");
	string town = record.GetField("Town");
	string postcode = record.GetField("Postcode");
	// display a string for the result
	// - replace with a function to process the result in your application?
	MessageBox.Show(list);
}

The number of results returned for Search operations will be limited by the MaxRecords Property of the Robot class instance. When using installed data it may also be limited by the Timeout Property. For evolution the server’s pre-configured MaxSearchTime may be a limiting factor.

Bank records can be looked up or searched for in exactly the same way as Address records. The difference being that the Robot class must be instantiated with a parameter of RobotType.Bank rather than RobotType.Address.

The applicable operations are:

  • Operation.FastFindLookup – Looks up the supplied string which can be a sortcode, bank/branch name, location, STD Code or BIC.
  • Operation.Search – Search for results matching the search fields specified using the SetField method.

An example of a Bank Lookup:

// Create instance of the Robot class
Robot robot = new Robot(RobotType.Bank);
// Lookup the records
int results = robot.Find("560036", Operation.FastFind);
// Check for error
if (results < 0) {
    MessageBox.Show(robot.LastErrorText);
	return;
}
// Iterate through results
foreach (AFD.API.Record record in robot.Records) {
    // Obtain the fields you require – some examples:
    string list = record.GetField("List");
    string sortcode = record.GetField("SortCode");
    string ownerBankFullName = record.GetField("OwnerBankFullName");
    string branchTitle = record.GetField("FullBranchTitle");
    string location = record.GetField("Location");
    string directDebits = record.GetField("BACSDirectDebits");
    // display a string for the result
    // - replace with a function to process the result in your application?
    MessageBox.Show(list);
}

Bank Account Validation

To validate an account number use the setField method to set the value of the sort code and account number (alternatively the IBAN can be used)

You may also wish to set the clearing system if you want to restrict validation to the UK (BACS), or Irish (IPSO) systems only.

Call Find with Operation.ValidateAccount (the Lookup parameter will be ignored)

Following successful validation a single record will be returned. It is recommended you use the sortcode and account number returned rather than that you supplied as non-standard length account numbers will be transcribed for you.

An example of a Bank Account Validation:

// Create instance of the Robot class
Robot robot = new Robot(RobotType.Bank);
// Set the Account Details to validate
robot.Clear();
robot.SetField("SortCode", "774814");
robot.SetField("AccountNumber", "24782346");
// RollNumber can also be set if applicable, IBAN can also be validated instead
// Validate the Account Details
int results = robot.Find(null, Operation.AccountValidate);
// Check for error, e.g. invalid account number
if (results < 0) {
    MessageBox.Show(robot.LastErrorText);
	return;
}
// Success will return a single result
string sortcode = robot.GetField("SortCode");
string accountNumber = robot.GetField("AccountNumber");
string iban = robot.GetField("IBAN");
string rollNumber = robot.GetField("RollNumber");
string typeOfAccount = robot.GetField("TypeOfAccount");
string clearingSystem = robot.GetField("ClearingSystem");
MessageBox.Show(“Account Number is Valid");

Card Number Validation

To validate a debit or credit card number use the setField method to set the value of the card number and optionally expiry date. (The expiry date is checked that it is in range for the current date if provided).

Call Find with Operation.ValidateCard (the Lookup parameter will be ignored).

Following successful validation a single record will be returned.

An example of Card Number Validation:

// Create instance of the Robot class
Robot robot = new Robot(RobotType.Bank);
// Set the field to Validate
robot.Clear();
robot.SetField("cardnumber", "4694782385016585");
robot.SetField("expirydate", "10/17"); // This field is optional
// Validate the Card Details
int results = robot.Find(null, Operation.CardValidate);
// Check for error, e.g. invalid account number
if (results < 0) {
    MessageBox.Show(robot.LastErrorText);
	return;
}
// Success will return a single result
string cardType = robot.GetField("CardType");
MessageBox.Show(“Valid: “ + cardType);

Email Validation

To validate an email address from an instance of the robot class instianted with RobotType.Email simply call the Find method with the email address to validate and Operation.EmailValidate.

An example of Email Address Validation:

// Create instance of the Robot class
Robot robot = new Robot(RobotType.Email);
// Validate the Card Details
int results = robot.Find("support@afd.co.uk", Operation.EmailValidate);
// Check for error, e.g. invalid Email Address
if (results < 0) {
    MessageBox.Show(robot.LastErrorText);
	return;
}
// Email Address is Valid
MessageBox.Show("Email Address is Valid");

Statelessly Retrieving Previous Records

If you have returned results following an address or bank lookup or search and require to fetch one of those results again you can do this with a Retrieve operation. An example when you might wish to do this if is returning a list of results to the user, wanting to minimise data passed and then need to retrieve the full record when a user selects an individual record.

To do this you need to store the key (use getField("Key") to obtain this) when processing the original record.

Please note that this Key is unique in a particular dataset so can be used statelessly or across multiple servers as long as the same version of the data is still in use. It is not unique across future versions of the data and therefore should not be stored in a database as a unique reference.

To retrieve a record call Find with the key for the record specified in the lookup field and an operation of Operation.Retrieve.

A single result will be returned which you can then process.

This will return:

  • 1 The single result was found
  • < 0 No results have been found (-2) or an error has occurred (use LastErrorText to obtain a human readable message for the error).

For example:

// Create instance of the Robot class
Robot robot = new Robot(RobotType.Address);
// Lookup the records
int results = robot.Find("B11 1AA1001", Operation.Retrieve);
// Check for error
if (results < 0) {
    MessageBox.Show(robot.LastErrorText);
	return;
}
// Obtain the fields you require – some examples:
string organisation = robot.GetField("Organisation");
string property = robot.GetField("Property");
string street = robot.GetField("Street");
string locality = robot.GetField("Locality");
string town = robot.GetField("Town");
string postcode = robot.GetField("Postcode");

Calling off results individually

For ease of use the Find method used in the previous sections returns all results at once until a predetermined timeout or maximum record count is reached (if applicable). When used with an evolution server there is little point to doing anything else as results have to result from the same web request.

However in some cases when using an installed product, you may wish to return results one-by-one as they are called off or provide your own mechanism for determining when to abort a search (for example based on the actual results that come back).

In such scenarios rather than calling Find, you can call the FindFirst and FindNext methods. FindFirst has identical parameters to Find but rather than returning the results in the Records collection, it instead returns one result at a time (FindNext takes no parameters).

You do also need to be aware that FindFirst and/or FindNext will sometimes return a value of 0 indicating a record or sector break which is provided to give the opportunity to cancel long searches and at which point no new result will be returned.

An example of an Address Fast-Find, identical that given in section 4.2.1 but using findFirst and FindNext is as follows:

// Create instance of the Robot class
Robot robot = new Robot(RobotType.Address);
// Lookup the records
int result = robot.FindFirst("b11 1aa", Operation.FastFindLookup);
// Check for Error, but note if 0 has been returned it is still possible no results will be found
if (result < 0) {
    MessageBox.Show(robot.LastErrorText);
    return;
}
// Process and call off each result
long results = 0;
while (result >= 0) {
    if (result > 0) {
        // obtain some of the fields for the result to use in your application
        string list = robot.GetField("List");
        string organisation = robot.GetField("Organisation");
        string property = robot.GetField("Property");
        string street = robot.GetField("Street");
        string locality = robot.GetField("Locality");
        string town = robot.GetField("Town");
        string postcode = robot.GetField("Postcode");
        // display a string for the result
        // - replace with a function to process the result in your application?
        MessageBox.Show(list);
        results++;
    }
	else if (result == 0) {
	    // sector or record break – take the chance to allow user to cancel?
    }
	// set your own condition(s) to abort the search
	if (results > 500) break;
	    result = robot.FindNext();
	}
	if (results > 0) {
	    // success
    }
	else {
	    MessageBox.Show("No Results Found");
	}
}

Function Reference for Robot Class

The following functions are available in the Robot Class:

3.3.1. Clear

void Clear()

This clears the fields, necessary prior to setting criteria for a search (not necessary for fast-finds and postcode lookups).

GetField

string GetField(string)

This property returns the value of the specified field name for the current record. When using Find to return multiple results at once you should use the GetField method of a Record in the Records collection property instead to retrieve fields from any record returned.

Find

int Find(string Lookup, Operation, optional SkipOptions)

Carries out an operation using the AFD API. For a lookup, card or email validation the Lookup parameter specifies the lookup string (for example a postcode, sortcode, card number or email address). The Operation specifies the operation to carry out.

The following Operations are supported:

Robot Type Operation Description
Address FastFindLookup Looks up an address fragement specified by the Lookup parameter. This could be a postcode or fields from an address.
PostcodePropertyLookup Looks up an address from the specified postcode and optionally property (e.g. “277, B11 1AA”) specified by the Lookup parameter.
PostcodeLookup Looks up an address from the specified postcode.
Search Searches for an address specified by criteria set by calling setField for the appropriate fields prior to calling this function (lookup parameter is ignored and can be null)
Retrieve Retrieves a previously returned record. The required records key field should be specified as the lookup parameter.
Bank FastFindLookup Looks up a sort code or searches for a bank from the fragment given as specified by the Lookup parameter.
Search Searches for a bank branch specified by critieria set by calling setField for the appropriate fields prior to calling this function (lookup parameter is ignored and can be null).
Retrieve Retrieves a previously returned record. The required records key field should be specified as the lookup parameter.
AccountValidate Validates an account number. Use setField to set both the sortcode and account number or alternatively the IBAN prior to calling this function. The lookup parameter is ignored.
CardValidate Validates a card number. The lookup parameter should be set to the card number to validate.
EmailValidate Validates an email address. The lookup parameter should be set to the email address to validate.

For address functions you can optionally set the SkipOptions to a member of the SkipOptions enumeration to skip records in large searches. These options are as follows:

Skip Option Description
None Default – Returns all matching records (unless a timeout or maximum number of records is reached).
Address Only returns the first matching record per address (or household). Only has any effect with Names & Numbers.
Postcode Only returns the first matching record for each postcode.
Sector Returns the first matching record per Sector (this is the portion of the postcode prior to the space and the first digit afterwards, e.g. “B11 1”).
Outcode Returns the first matching record per Outcode (this is the portion of the postcode prior to the space, e.g. “B11”);
Town Returns the first matching record per Royal Mail Post Town.
Area Returns the first matching record per Postcode Area (this is the letters at the start of the postcode, e.g. “B” or “AB”).

This function returns the number of matching records returned, or a value < 0 if an error has occurred. Use the LastErrorText property to obtain a human readable version of an error.

FindFirst

int FindFirst(string Lookup, AFD.API.Operation Operation)

This method is identical in parameters to Find. The difference being that it will obtain the first result only (or sometimes a record or sector break in a long search). You can then call FindNext() to obtain subsequent records.

In general it is recommended you use Find to obtain results as this simplifies calling off results and in-built support for the MaxRecords and, for installed data, Timeout properties to restrict long searches to help prevent your application becoming unresponsive. However in cases were you are using locally installed data and wish to have full control over this process this method gives you that flexibility.

Some examples were you might use this would be if you wish to return results to the user as they are called off rather than at the end of a long search, or you wish to be able to determine when to abort a search based on the results themselves or user intervention then this method gives you that flexibility.

The return codes are the same as for Find with the addition of 0 which indicates a record or sector break, when returned no result has been returned (You will need to call FindNext to continue the search). This allows the opportunity to cancel long searches after a predetermined timeout etc. if required.

FindNext

int FindNext()

This method is used following a call to FindFirst to repeatedly call off subsequent records. It will return 1 on success, 0 on a record or sector break (indicating no new result has been returned but giving the opportunity to cancel or provide user responsiveness) or -6 to indicate the end of a search.

InsertRecord

int InsertRecord(int)

This function is not relevant when not using with an instance of Windows Forms and will always return false in such cases.

LastErrorText

string LastErrorText()

This returns human readable text for the last error to occur (will return an empty string if the last operation was successful). While you may wish to display your own error text for some errors it is recommended that you fall-back to using this for any error code you have not handled yourself.

SetField

bool SetField (string FieldName, string FieldValue)

Sets the value of the specified field for searching.

Properties Reference for Robot Class

DialogOptions and Mappings are not documented in this section as they are ignored unless Robot is instantiated for use specifically with a Windows Form (see Section 3 for futhur details).

AddressFields

Set the number of address fields to use when returning free address fields with GetField (e.g. address1, address2, etc.). The default is 6, setting this to the same number as the fields you have causes Robot to squeeze fields in as required.

IncludeOrganisation

Boolean value indicating if the Organisation is included in free address field (i.e. if you obtain address1, address2, etc.)

LastErrorText

Returns human readable descriptive text for the last operation. Returns an empty string if no error occurred (result code >= 0).

LastResult

Returns the result code for the last operation. While be < 0 if an error occurred or > 0 if successful.

MaxRecords

Sets the Maximum number of records to return from any lookup or search (default 500).

Records

Following an option calling Find this is a collection of the results (Record objects). Each Record in the collection has a getField method used to obtain individual fields for that result.

Timeout

Sets the maximum time in seconds to spend searching for records (Default is 30 seconds). This helps prevent very long searches making an application unresponsive or a very vague search taking too long when it could instead be refined. This is applicable to installed products only. For evolution the server will be preconfigured with a MaxSearchTime which has the same effect.

UpperCaseTown

Indicates that the Town will always be returned in upper case (default and preferred by Royal Mail for address labels)

Record Class

The Record class cannot be instantiated on its own. A collection of Record objects is returned by the Records Property of the Robot class following an operation calling Find`.

The class has a single method GetField. This property returns the value of the specified field name for the record.

Collections

RobotType

This collection is used on instantiating the Robot class to specify the type of Robot used. The values are Address for Address Management (e.g. Address Fastfind, Search, etc.), Bank for BankFinder (e.g. Account or Card Validation) or Email for Email Validation.

You cannot mix types in one instance of the robot class, but you can have multiple instances of the class of different types called in the same function in your code

Operation

This collection is used to specify the operation carried out. Section 4.3.3 provides a table with the valid Operations for each RobotType.

Return Codes

The possible return codes, available as the return code from FindFirst or the LastResult property, are as follows:

Success Codes

These are the possible codes returned:

Value Description
0 The search/lookup has not completed but may take some time and so is returning to give the user the option to cancel a long search.
1 The function was successful and a matching record has been returned.
2 This applies only to Bankfinder account number validation and indicates that the function was successful and the account number should be taken as valid. However, as account numbers on this sortcode cannot be validated you may wish to double check it is correct.

Error Codes

These specify the possible errors returned from any API function:

Value Description
-1 The field specification string specified is invalid. This shouldn’t be returned under normal circumstances.
-2 No records matching your lookup or search criteria were found.
-3 The record number provided (e.g. when re-retrieving an item from a list box) is invalid.
-4 An error occurred attempting to open the AFD data files. Check they are correctly installed.
-5 An error occurred reading the data. Likely to be due to corrupt data so software may need to be re-installed.
-6 End of Search (when the last result has already been called off – indicates there are no more results to return).
-7 Indicates there is an error with the product registration. Normally due to it having expired. Run the Welcome program to re-register the software.
-8 Occurs if you attempt to search for a Name and Organisation at the same time. Also occurs with Postcode Plus if the UDPRN field is searched for at the same time as any other field.
-99 Indicates that the user clicked the cancel button if the DLL internal list box was used.
-12 The sort code specified for an account number validation does not exist.
-13 The sortcode specified for an account number validation is invalid.
-14 The account number specified for an account number validation is invalid.
-21 The sort code and account number given are for a building society account which also requires a roll number for account credits. No roll number has been supplied or is incorrect for this building society.
-22 The International Bank Account Number provided is in an invalid format
-23 The IBAN provided contains a country that is not recognised as valid
-24 Both an IBAN and Account Number was provided and these details do not match.
-15 The expiry date specified for a card validation is invalid.
-16 The card has expired
-18 The card number specified for a card validation is invalid.
-19 The card number specified is a Visa card which can be used in an ATM only.
-20 While the card number appears to be a valid one, the card is not of any of the known types and is therefore unlikely to be acceptable for payment.

Evolution Server Details

The AFD.API.Authentication Object is used to specify authentication details to use robot with an evolution server. If you do not assign one to the Authentication property of the Robot class then a default instance is created which uses local installed product.

We strongly recommend that the details passed to create an instance of the Authentication object are stored as modifiable configuration parameters in your application, so that details can be changed in the future without needing to alter code.

There are three initialisers for the Authentication object:

  • Authentication()

    This creates a version to work with installed data only. You will require a copy of an AFD product installed on each machine your software runs on. This is the fastest and most efficient method and is particularly ideal for offline use.

  • Authentication(Serial, Password)

    This creates a version to work with AFD’s server. You pass it your serial number and password.

  • Authentication(Server, Serial, Password)

    This creates a version to work with your own server. The Server parameter should be a string including the protocol, server and (if not 80) the port so as to give wide compatibility. For example http://server:81

ASP .NET Webpage

With ASP .NET webpages you can easily use Robot with the Robot class as described in Section 4 of this manual.

If you wish to use auto-configuration with your webpage you may wish to consider using Robot Web rather than Robot API as Robot Web uses JavaScript and AJAX to lookup addresses in-line from your webpage.

If using Robot API in an ASP .NET webpage an example of obtaining address results to add to a list box is as follows:

protected void ButtonLookup_Click(object sender, EventArgs e)
	{
	// Create an instance of the Robot class for Address operations
	AFD.API.Robot robot = new AFD.API.Robot(AFD.API.RobotType.Address);
	// Lookup the postcode or fast-find string in the TextLookup TextBox
	int results = robot.Find(TextLookup.Text,
    AFD.API.Operation.FastFindLookup);
	// Add Items to ListBoxAddress For The User To Select From
	ListBoxAddress.AutoPostBack = true;
	foreach (AFD.API.Record record in robot.Records) {
	    string ListText = record.GetField("list");
	    string ListValue = record.GetField("key");
	    ListItem item = new ListItem(ListText, ListValue);
	    ListBoxAddress.Items.Add(item);
    }
}

On selecting an item from a List Box the record can be re-looked up to provide full address details for submission, an example of this:

protected void ListBoxAddress_SelectedIndexChanged(object sender, EventArgs e)
    {
	// Create an instance of the Robot class for Address operations
	AFD.API.Robot robot = new AFD.API.Robot(AFD.API.RobotType.Address);
	// Lookup the selected item
	int results = robot.Find(ListBox1.SelectedValue,AFD.API.Operation.Retrieve);
	// Assign the address to fields on the Form
	TextBoxOrganisation.Text = robot.GetField("organisation");
	TextBoxProperty.Text = robot.GetField("property");
	TextBoxStreet.Text = robot.GetField("street");
	TextBoxLocality.Text = robot.GetField("locality");
	TextBoxTown.Text = robot.GetField("town");
	TextBoxPostcode.Text = robot.GetField("postcode");
}

Appendicies

For our full list of appendicies please download the full .NET API Manual