Code samples
Full integration examples shipped by Nova for both REST and SOAP transports. The C# and Java samples include error handling and pagination patterns; the JavaScript examples are working front-end snippets you can drop into a page.
REST
REST is the recommended transport for new integrations. Authenticate with Authorization: customer|key and POST JSON to <NCODE_WS4_BASE_URL>/<Method>.
RestExamples.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using nCodeCloudWSProxy;
using nCodeCloudWSProxy.nCodeWebService4C1;
using nCodeCloudWSProxy.nCodeWebService4TS;
namespace nCodeCloudRestCS
{
class RestExamples
{
private const int MAX_SHOW_ALTERNATIVES = 50;
static void Main(string[] args)
{
string caption = "This program demonstrates accessing nCodeWS4C1 RESTful Web Service in C#.NET";
string ws4c1resturl = string.Empty;
string ws4tsresturl = string.Empty;
string authtoken = string.Empty;
string cn = string.Empty;
string lk = string.Empty;
string message = string.Empty;
try
{
// instruct json.net to apply string enum converter, we need to invoke it only once, at the application startup
SetJsonConvert();
Console.WriteLine(caption);
Console.WriteLine();
Console.Write("Web Service Url: ");
ws4c1resturl = Console.ReadLine();
Console.Write("Customer Name: ");
cn = Console.ReadLine();
Console.Write("License Key: ");
lk = Console.ReadLine();
// the credentials passed to the web service can be in the <customer>|<license key> form
authtoken = cn + "|" + lk;
// perform tests without obtaining token
RESTfulGetMethodsTest(ws4c1resturl, authtoken);
RESTfulAddressCorrectionTest(ws4c1resturl, authtoken);
RESTfulAddressTransformationTest(ws4c1resturl, authtoken);
RESTfulAddressSearchTest(ws4c1resturl, authtoken);
RESTfulOneStopTest(ws4c1resturl, authtoken);
// now, test using the token obtained from the token web service
int tl = 60; // for simplicity, the token timeout value in minutes will be fixed
ws4tsresturl = ws4c1resturl.Replace("C1", "TS");
GetTokenOutput tokenoutput = GetSecurityToken(ws4tsresturl, cn, lk, tl);
Console.WriteLine("Testing token: " + tokenoutput.Token);
Console.WriteLine("Token expires at: " + tokenoutput.ExpiresAt);
// once acquired, the token should be reused for subsequent nCodeWS4C1 calls, until it expires
RESTfulGetMethodsTest(ws4c1resturl, tokenoutput.Token);
RESTfulAddressCorrectionTest(ws4c1resturl, tokenoutput.Token);
RESTfulAddressTransformationTest(ws4c1resturl, tokenoutput.Token);
RESTfulAddressSearchTest(ws4c1resturl, authtoken);
RESTfulOneStopTest(ws4c1resturl, tokenoutput.Token);
}
catch (Exception ex)
{
message = Environment.NewLine + "Unexpected Exception. Reason: " + ex.Message;
if (ex.InnerException != null)
{
message += Environment.NewLine + "Detail: " + ex.InnerException.Message;
}
Console.WriteLine(message);
}
message = Environment.NewLine + "Press Enter To Exit The Program: ";
Console.Write(message);
Console.ReadLine();
}
public static void RESTfulAddressCorrectionTest(string ws4resturl, string authtoken)
{
AnalyzeGetAlternativesInput request = null;
AnalyzeGetAlternativesOutput response = null;
AddressLayout layout = null;
string sLine = string.Empty;
string sResponse = null;
Console.WriteLine(Environment.NewLine + "RESTful Address Correction Test" + Environment.NewLine);
try
{
// define the input request parameters:
request = new AnalyzeGetAlternativesInput();
Console.Write("Adress Layout: ");
request.strLayout = Console.ReadLine();
Console.Write("Analysis Mode: ");
request.strAnalysis = Console.ReadLine();
Console.Write("Correction Style: ");
request.strCorrection = Console.ReadLine();
// set the maximum number of alternatives, version 4.10 or later
request.MaxAlternatives = MAX_SHOW_ALTERNATIVES;
// will need the line names for the user input
sResponse = InvokeWebRequest(ws4resturl, "GetLayoutDetails", request.strLayout, authtoken);
layout = JsonConvert.DeserializeObject<AddressLayout>(sResponse);
if (layout.intRetCode == 0)
{
throw new Exception(layout.strMessage);
}
request.udtLinesIn = new LineContent[layout.intTotalLines];
Console.WriteLine();
for (int index = 0; index < layout.intTotalLines; index++)
{
request.udtLinesIn[index] = new LineContent();
request.udtLinesIn[index].strName = layout.Lines[index].strLineName;
Console.Write(layout.Lines[index].strLineName + ": ");
sLine = Console.ReadLine();
request.udtLinesIn[index].strContent = sLine;
}
// perform the address correction
sResponse = InvokeWebRequest(ws4resturl, "AnalyzeGetAlternatives", request, authtoken);
response = JsonConvert.DeserializeObject<AnalyzeGetAlternativesOutput>(sResponse);
if (response.intRetCode != 0)
{
Console.WriteLine();
Console.WriteLine("Resulting Message: " + response.strMessage);
Console.WriteLine("Address Status: " + response.strStatus);
Console.WriteLine("Number Of Alternatives: " + response.intAlternatives);
Console.WriteLine("Actual Alternatives Found: " + response.ActualAlternativesFound);
Console.WriteLine("Address Hash Code: " + response.HashCode);
Console.WriteLine();
Console.WriteLine("Resulting Addreess:");
for (int index = 0; index < response.udtLinesOut.Length; index++)
{
sLine = response.udtLinesOut[index].strName + ": ";
sLine += response.udtLinesOut[index].strContent;
Console.WriteLine(sLine);
}
}
else
{
throw new Exception("Unexpected Address Correction Error: " + response.strMessage);
}
}
catch (Exception ex)
{
Console.WriteLine("Unexpected Exception: " + ex.ToString());
}
WaitBeforeContinuing();
}
public static void RESTfulAddressTransformationTest(string ws4resturl, string authtoken)
{
AddressLayout layout = null;
TransformInput request = new TransformInput();
TransformOutput response = null;
string sLine = string.Empty;
string sResponse = null;
Console.WriteLine(Environment.NewLine + "RESTful Address Transformation Test" + Environment.NewLine);
try
{
// define the input request parameters:
Console.Write("Input Adress Layout: ");
request.strFirstLayout = Console.ReadLine();
Console.Write("Output Adress Layout: ");
request.strSecondLayout = Console.ReadLine();
Console.Write("Analysis Mode: ");
request.strAnalysis = Console.ReadLine();
Console.Write("Correction Style: ");
request.strCorrection = Console.ReadLine();
// will need the line names for the user input
sResponse = InvokeWebRequest(ws4resturl, "GetLayoutDetails", request.strFirstLayout, authtoken);
layout = JsonConvert.DeserializeObject<AddressLayout>(sResponse);
if (layout.intRetCode == 0)
{
throw new Exception(layout.strMessage);
}
request.udtLinesIn = new LineContent[layout.intTotalLines];
Console.WriteLine();
for (int index = 0; index < layout.intTotalLines; index++)
{
request.udtLinesIn[index] = new LineContent();
request.udtLinesIn[index].strName = layout.Lines[index].strLineName;
Console.Write(layout.Lines[index].strLineName + ": ");
sLine = Console.ReadLine();
request.udtLinesIn[index].strContent = sLine;
}
// perform the address transformation
sResponse = InvokeWebRequest(ws4resturl, "TransformAddress", request, authtoken);
response = JsonConvert.DeserializeObject<TransformOutput>(sResponse);
Console.WriteLine();
Console.WriteLine("Return Code: " + response.intRetCode);
Console.WriteLine("Message: " + response.strMessage);
if (response.intRetCode != 0)
{
Console.WriteLine();
Console.WriteLine("Transformed Address:");
for (int index = 0; index < response.udtLinesOut.Length; index++)
{
sLine = response.udtLinesOut[index].strName + ": ";
sLine += response.udtLinesOut[index].strContent;
Console.WriteLine(sLine);
}
}
else
{
throw new Exception("Unexpected Address Transformation Error: " + response.strMessage);
}
}
catch (Exception ex)
{
Console.WriteLine("Unexpected Exception: " + ex.ToString());
}
WaitBeforeContinuing();
}
public static void RESTfulOneStopTest(string ws4resturl, string authtoken)
{
OneStopAnalyzeInput request = null;
OneStopAnalyzeOutput response = null;
AddressLayout layout = null;
string message = String.Empty;
bool shouldExit = false;
bool newAddress = true;
string sResponse = null;
string sLine = null;
const int BROWSING_LEVEL = 2;
Console.WriteLine(Environment.NewLine + "RESTful oneStop Address Capture Test" + Environment.NewLine);
try
{
request = new OneStopAnalyzeInput();
// define the input request parameters:
Console.Write("Adress Layout: ");
request.AddressLayout = Console.ReadLine();
Console.Write("Analysis Mode: ");
request.AnalysisMode = Console.ReadLine();
Console.Write("Correction Style: ");
request.CorrectionStyle = Console.ReadLine();
request.MaxAlternatives = MAX_SHOW_ALTERNATIVES;
request.BrowsingLevel = BROWSING_LEVEL;
request.SelectedAlternative = string.Empty;
request.EnableAltDetails = false;
request.GuessingFlags = new GuessingModes();
// for simplicity, use the defaults implied by the analysis mode
request.GuessingFlags.UseDefaults = true;
// will need the line names for the user input
sResponse = InvokeWebRequest(ws4resturl, "GetLayoutDetails", request.AddressLayout, authtoken);
layout = JsonConvert.DeserializeObject<AddressLayout>(sResponse);
if (layout.intRetCode == 0)
{
throw new Exception(layout.strMessage);
}
else
{
request.AddressLinesIn = new LineContent[layout.intTotalLines];
}
do
{
if (newAddress)
{
// collect the address lines
Console.WriteLine();
for (int index = 0; index < layout.intTotalLines; index++)
{
request.AddressLinesIn[index] = new LineContent();
request.AddressLinesIn[index].strName = layout.Lines[index].strLineName;
Console.Write(layout.Lines[index].strLineName + ": ");
sLine = Console.ReadLine();
request.AddressLinesIn[index].strContent = sLine;
}
}
// check if the user wants to exit
if (shouldExit)
{
break;
}
// process the user request
sResponse = InvokeWebRequest(ws4resturl, "OneStopAnalyze", request, authtoken);
response = JsonConvert.DeserializeObject<OneStopAnalyzeOutput>(sResponse);
// verify the return code
if (!response.SuccessStatus)
{
// should not happen
message = "Unexpected Failure While Calling OneStopAnalyze().";
message += Environment.NewLine + "Reason: " + response.Message;
Console.WriteLine(message);
break;
}
else // normal flow
{
if (response.AddressComplete) // complete address
{
// present the message
Console.WriteLine();
Console.WriteLine(response.Message);
Console.WriteLine();
// see if LVR name is applicable
if (response.AddressDetails[0].LVRType != AES_TypeOfLVR.AES_NotAnLVR)
{
string lvrName = string.Empty;
if (response.AddressDetails[0].LVRType == AES_TypeOfLVR.AES_Building)
{
lvrName = "Building: " + response.AddressDetails[0].LVRName;
}
else if (response.AddressDetails[0].LVRType == AES_TypeOfLVR.AES_GovStreetLVR)
{
lvrName = "GOV. LVR: " + response.AddressDetails[0].LVRName;
lvrName += ", " + response.AddressDetails[0].BranchName;
}
else if (response.AddressDetails[0].LVRType == AES_TypeOfLVR.AES_GovPOBoxLVR)
{
lvrName = "GOV. LVR: " + response.AddressDetails[0].LVRName;
lvrName += ", " + response.AddressDetails[0].BranchName;
}
else
{
lvrName = "LVR: " + response.AddressDetails[0].LVRName;
}
// present the LVR information
Console.WriteLine(lvrName);
}
// present the address
for (int index = 0; index < response.AddressLinesOut.Length; index++)
{
sLine = response.AddressLinesOut[index].strName + ": ";
sLine += response.AddressLinesOut[index].strContent;
Console.WriteLine(sLine);
}
request.SelectedAlternative = string.Empty;
newAddress = true;
}
else if (response.AlternativeListType == AltListType.Empty) // the list of alternatives is empty
{
// just present the message
Console.WriteLine(response.Message);
request.SelectedAlternative = string.Empty;
newAddress = true;
}
else if (response.AlternativeListType == AltListType.Addresses && response.Alternatives.Count == 1) // one address alternative
{
// this means we should have the suggested address available
// present the alternative address record, since it will contain range information
Console.WriteLine(response.Alternatives[0]);
// present the suggested address
for (int index = 0; index < response.SuggestedLines.Length; index++)
{
sLine = response.SuggestedLines[index].strName + ": ";
sLine += response.SuggestedLines[index].strContent;
Console.WriteLine(sLine);
}
// get the intended range number from the user
Console.Write("Please Enter The Intended Number: ");
string sNumber = Console.ReadLine();
// redefine the user input
foreach (LineContent line in response.SuggestedLines)
{
if (line.strContent.Contains("?###"))
{
line.strContent = line.strContent.Replace("?###", sNumber);
}
}
request.AddressLinesIn = response.SuggestedLines;
request.SelectedAlternative = string.Empty;
newAddress = false;
}
else // present the list of alternatives and ask for a selection
{
newAddress = false;
if (response.AlternativeListType == AltListType.Addresses)
{
message = "A List Of " + response.Alternatives.Count + " Address Records Was Created:";
}
else if (response.AlternativeListType == AltListType.Names)
{
message = "A List Of " + response.Alternatives.Count + " Street/Station Names Was Created:";
}
else
{
message = "Invalid Alternative List Type (" + response.AlternativeListType.ToString() + ").";
}
Console.WriteLine(message);
if (response.Alternatives.Count != response.ActualAlternativesFound)
{
message = "The Number Of Items Actually Found Was " + response.ActualAlternativesFound + ".";
Console.WriteLine(message);
}
// present the list
Console.WriteLine();
for (int iIndex = 1; iIndex <= response.Alternatives.Count; iIndex++)
{
// get the alternative and present it
string lineNumber = iIndex.ToString() + ".";
message = lineNumber.PadRight(5) + response.Alternatives[iIndex - 1];
Console.WriteLine(message);
}
// separate the list from the rest
Console.WriteLine();
// ask for the index of the selected alternative
int iSelectedIndex;
if (response.Alternatives.Count == 1) // only one item in the list
{
iSelectedIndex = 1;
}
else if (response.Alternatives.Count > 1) // ask for the index
{
Console.Write("Please Enter The Index Of The Selected Alternative: ");
string number = Console.ReadLine();
if (number.Length > 0 && number[0] == '*')
{
request.SelectedAlternative = string.Empty;
shouldExit = false;
newAddress = true;
continue;
}
if (!int.TryParse(number, out iSelectedIndex) ||
iSelectedIndex < 1 ||
iSelectedIndex > response.Alternatives.Count)
{
message = "Invalid Index Was Selected.";
Console.WriteLine(message);
continue;
}
}
else
{
request.SelectedAlternative = string.Empty;
continue;
}
// define the selected alternative, no need to check the return value again
request.SelectedAlternative = response.Alternatives[iSelectedIndex - 1];
}
}
Console.WriteLine();
if (newAddress)
{
// ask if more oneStop address capture is needed
Console.Write("More oneStop Address Capture(Y=Yes,N=No): ");
string choice = Console.ReadLine();
if (choice.Equals("N", StringComparison.CurrentCultureIgnoreCase))
shouldExit = true;
}
} while (!shouldExit);
}
catch (Exception ex)
{
Console.WriteLine("Unexpected Exception: " + ex.ToString());
}
WaitBeforeContinuing();
}
public static void RESTfulAddressSearchTest(string ws4resturl, string authtoken)
{
BrowsingRequest request = new BrowsingRequest();
AddressesFound response = null;
string sLine = string.Empty;
string sResponse = null;
Console.WriteLine(Environment.NewLine + "RESTful Address Search Test" + Environment.NewLine);
try
{
// define the search conditions:
request.TargetType = NB_TargetType.NB_TargetAddresses;
// for simplicity, search by postal code only
Console.Write("Postal Code To Search: ");
request.PostalCode = Console.ReadLine();
// set other name conditions to empty
request.Name = string.Empty;
request.Type = string.Empty;
request.Direction = string.Empty;
request.Municipality = string.Empty;
request.Province = string.Empty;
request.NumberFrom = string.Empty;
request.NumberTo = string.Empty;
request.RouteKeyword = string.Empty;
request.RouteNumber = string.Empty;
// set the inclusion conditions
request.IncludeAll = NB_IsIncluded.NB_IncludedYes;
request.AllInRange = NB_AllInRange.NB_AllInRangeNo;
request.IncludeStreet = NB_IsIncluded.NB_IncludedYes;
request.IncludeSSBR = NB_IsIncluded.NB_IncludedYes;
request.IncludePOBox = NB_IsIncluded.NB_IncludedYes;
request.IncludeRoute = NB_IsIncluded.NB_IncludedYes;
request.IncludeGD = NB_IsIncluded.NB_IncludedYes;
request.IncludeUrban = NB_IsIncluded.NB_IncludedYes;
request.IncludeRural = NB_IsIncluded.NB_IncludedYes;
// set the conditions that are new to nCodeWS4
request.ApplyMisspellings = false;
request.ApplyMissingWords = false;
request.AccentedInput = false;
request.AccentedOutput = true;
request.LowercaseOutput = true;
request.ApplyAltMnc = false;
request.UseMncAsGda = false;
// the max items to be returned
request.MaxItems = MAX_SHOW_ALTERNATIVES;
// perform the search
sResponse = InvokeWebRequest(ws4resturl, "SearchForAddresses", request, authtoken);
response = JsonConvert.DeserializeObject<AddressesFound>(sResponse);
// present the results
Console.WriteLine();
if (response.intRetCode == 0) // failed, report the error
{
throw new Exception("Address Search Error:" + response.strMessage);
}
else // present the results
{
sLine = "Total " + response.Address.Length + " Addresses Found.";
Console.WriteLine(sLine);
foreach (AddressElements ae in response.Address)
{
sLine = Common.PresentAddress(ae);
Console.WriteLine(sLine);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Unexpected Exception: " + ex.ToString());
}
WaitBeforeContinuing();
}
public static void RESTfulGetMethodsTest(string ws4resturl, string authtoken)
{
WebServiceInfo wsiresponse = null;
ParamList paramlist = null;
AddressLayout layout = null;
string sResponse = null;
const string LAYOUT_NAME = "SERP TEST";
Console.WriteLine(Environment.NewLine + "RESTful Get Methods Test" + Environment.NewLine);
try
{
// retrieve Web service information
sResponse = InvokeWebRequest(ws4resturl, "GetWebServiceInfo", string.Empty, authtoken);
wsiresponse = JsonConvert.DeserializeObject<WebServiceInfo>(sResponse);
// print out Web service info
if (!wsiresponse.SuccessStatus) // failed, report the error
{
throw new Exception(wsiresponse.Message);
}
else // present the results
{
Console.WriteLine("Web Service Info:");
Console.WriteLine("Web Service Name: " + wsiresponse.WebServiceName);
Console.WriteLine("Web Service Version: " + wsiresponse.WebServiceVersion);
Console.WriteLine("Native Library Version: " + wsiresponse.NativeLibraryVersion);
Console.WriteLine("Address Data Version: " + wsiresponse.DataVersion);
}
WaitBeforeContinuing();
// list the address layouts
sResponse = InvokeWebRequest(ws4resturl, "GetParamList", NPAR_ParameterType.NPAR_AddressLayouts, authtoken);
paramlist = JsonConvert.DeserializeObject<ParamList>(sResponse);
if (paramlist.intRetCode == 0) // failed, report the error
{
throw new Exception(paramlist.strMessage);
}
else // present the list of address layouts:
{
Console.WriteLine("Found " + paramlist.strParamName.Count + " Address Layouts: ");
for (int count = 0; count < paramlist.strParamName.Count; count++)
{
string sLine = (count + 1).ToString() + ". " + paramlist.strParamName[count];
Console.WriteLine(sLine);
}
}
WaitBeforeContinuing();
// list the analysis modes
sResponse = InvokeWebRequest(ws4resturl, "GetParamList", NPAR_ParameterType.NPAR_AnalysisModes, authtoken);
paramlist = JsonConvert.DeserializeObject<ParamList>(sResponse);
if (paramlist.intRetCode == 0) // failed, report the error
{
throw new Exception(paramlist.strMessage);
}
else // present the list of analysis modes:
{
Console.WriteLine("Found " + paramlist.strParamName.Count + " Analysis Modes: ");
for (int count = 0; count < paramlist.strParamName.Count; count++)
{
string sLine = (count + 1).ToString() + ". " + paramlist.strParamName[count];
Console.WriteLine(sLine);
}
}
WaitBeforeContinuing();
// list the correction styles
sResponse = InvokeWebRequest(ws4resturl, "GetParamList", NPAR_ParameterType.NPAR_CorrectionStyles, authtoken);
paramlist = JsonConvert.DeserializeObject<ParamList>(sResponse);
if (paramlist.intRetCode == 0) // failed, report the error
{
throw new Exception(paramlist.strMessage);
}
else // present the list of correction styles:
{
Console.WriteLine("Found " + paramlist.strParamName.Count + " Correction Styles: ");
for (int count = 0; count < paramlist.strParamName.Count; count++)
{
string sLine = (count + 1).ToString() + ". " + paramlist.strParamName[count];
Console.WriteLine(sLine);
}
}
WaitBeforeContinuing();
// present the properties of a specific address layout
sResponse = InvokeWebRequest(ws4resturl, "GetLayoutDetails", LAYOUT_NAME, authtoken);
layout = JsonConvert.DeserializeObject<AddressLayout>(sResponse);
if (layout.intRetCode == 0) // failed, report the error
{
throw new Exception(layout.strMessage);
}
else // present the address layout details
{
Console.WriteLine("Address Layout '{0}' Details:", layout.strLayoutName);
Console.WriteLine("Record Length: {0}", layout.intRecordLength);
Console.WriteLine("Number Of Lines: {0}", layout.intTotalLines);
// present each address line details
for (int count = 0; count < layout.Lines.Length; count++)
{
AddressLine al = layout.Lines[count];
string line = ((count + 1) + ". ").PadLeft(5);
line += al.strLineName + " [" + al.intLineStart + ",";
line += (al.intLineStart + al.intLineLength - 1) + "]";
// present the list of address types associated with the line
foreach (NAT_AddressType at in al.Types)
{
line += " " + at.ToString();
}
// present the address line
Console.WriteLine(line);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Unexpected Exception: " + ex.ToString());
}
WaitBeforeContinuing();
}
// ws4tsurl is the url of the token service
// cn represents the customer name
// lk represents the license key related to the customer
// tl represents the token duration in minutes
public static GetTokenOutput GetSecurityToken(string ws4resturl, string cn, string lk, int tl)
{
string authtoken = string.Empty;
GetTokenOutput response = null;
try
{
// the credentials passed to the token web service must be in the <customer>|<license key> form
authtoken = cn + "|" + lk;
string sResponse = InvokeWebRequest(ws4resturl, "GetToken", tl, authtoken);
// call the token web service
response = JsonConvert.DeserializeObject<GetTokenOutput>(sResponse);
// verify the results
if (response.Outcome)
{
return response;
}
else // failed
{
string message = "Error getting security token. Reason: " + response.Message;
throw new Exception(message);
}
}
catch (Exception ex)
{
// possible error handling here, before rethrowing the exception
throw ex;
}
}
// generic method for invoking nCodeWS4C1 RESTful POST methods
private static string InvokeWebRequest(string ws4resturl, string method, object request, string token)
{
string sResponse = null;
HttpWebRequest webRequest = null;
StreamWriter requestWriter = null;
// create the web request
string url = ws4resturl + "/" + method;
webRequest = WebRequest.Create(url) as HttpWebRequest;
if (webRequest != null)
{
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
webRequest.Proxy = null; // speeds up performance
// for ppu invocations only, need to add the authorization header
if (token.Length > 0)
{
webRequest.Headers.Add("Authorization", token);
}
}
else
{
string message = "Failed To Create WebRequest object.";
message += Environment.NewLine + "The URL was '" + url + "'.";
throw (new Exception(message));
}
// use json.net for serialization
string sRequest = JsonConvert.SerializeObject(request);
// invoke the method
using (requestWriter = new StreamWriter(webRequest.GetRequestStream()))
{
requestWriter.Write(sRequest);
}
HttpWebResponse resp = (HttpWebResponse)webRequest.GetResponse();
Stream resStream = resp.GetResponseStream();
StreamReader reader = new StreamReader(resStream);
sResponse = reader.ReadToEnd();
resp.Close();
return sResponse;
}
private static void SetJsonConvert()
{
JsonConvert.DefaultSettings = (() =>
{
var settings = new JsonSerializerSettings();
settings.Converters.Add(new StringEnumConverter { });
return settings;
});
}
private static void WaitBeforeContinuing()
{
Console.WriteLine();
Console.Write(Environment.NewLine + "Please press Enter to continue: ");
Console.ReadLine(); // wait for the user's response
Console.WriteLine();
}
}
}
SOAP
SOAP samples are provided for legacy integrations. The same methods and field shapes apply. New integrations should prefer REST.
SoapExamples.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;
using System.ServiceModel.Web;
using nCodeCloudWSProxy;
using nCodeCloudWSProxy.nCodeWebService4TS;
using nCodeCloudWSProxy.nCodeWebService4C1;
namespace nCodeCloudSoapCS
{
class SoapExamples
{
private const int OPEN_TIMEOUT = 60; // in seconds
private const int CLOSE_TIMEOUT = 30; // in seconds
private const int SEND_TIMEOUT = 60; // in seconds
private const int RECIEVE_TIMEOUT = 60; // in seconds
private const int MAX_MESSAGE = 100 * 1024 * 1024; // should never be exceeded
private const string HTTP_HEADER_NAME = "Authorization";
private const int MAX_SHOW_ALTERNATIVES = 50;
static void Main(string[] args)
{
string caption = "This program demonstrates accessing nCodeWS4C1 SOAP Web Service in C#.NET";
InCodeWS4C1Client ws4c1 = null;
string ws4c1url = string.Empty;
string ws4tsurl = string.Empty;
string authtoken = string.Empty;
string cn = string.Empty;
string lk = string.Empty;
string message = string.Empty;
try
{
Console.WriteLine(caption);
Console.WriteLine();
Console.Write("Web Service Url: ");
ws4c1url = Console.ReadLine();
Console.Write("Customer Name: ");
cn = Console.ReadLine();
Console.Write("License Key: ");
lk = Console.ReadLine();
// once created, the nCodeWS4C1 SOAP proxy should be reused during the lifetime of the application
ws4c1 = GetWS4C1Client(ws4c1url);
// the credentials passed to the web service can be in the <customer>|<license key> form
authtoken = cn + "|" + lk;
// perform tests without obtaining token
TestGetMethods(ws4c1, authtoken);
AddressCorrectionTest(ws4c1, authtoken);
AddressTransformationTest(ws4c1, authtoken);
AddressSearchTest(ws4c1, authtoken);
AddressBrowsingTest(ws4c1, authtoken);
TestOneStop(ws4c1, authtoken);
// now, test using the token obtained from the token web service
int tl = 60; // for simplicity, the token timeout value in minutes will be fixed
ws4tsurl = ws4c1url.Replace("C1", "TS");
GetTokenOutput tokenoutput = GetSecurityToken(ws4tsurl, cn, lk, tl);
Console.WriteLine("Testing token: " + tokenoutput.Token);
Console.WriteLine("Token expires at: " + tokenoutput.ExpiresAt);
// once acquired, the token should be reused for subsequent nCodeWS4C1 calls, until it expires
TestGetMethods(ws4c1, tokenoutput.Token);
AddressCorrectionTest(ws4c1, tokenoutput.Token);
AddressTransformationTest(ws4c1, tokenoutput.Token);
AddressSearchTest(ws4c1, tokenoutput.Token);
AddressBrowsingTest(ws4c1, tokenoutput.Token);
TestOneStop(ws4c1, authtoken);
}
catch (Exception ex)
{
message = Environment.NewLine + "Unexpected Exception. Reason: " + ex.Message;
if (ex.InnerException != null)
{
message += Environment.NewLine + "Detail: " + ex.InnerException.Message;
}
Console.WriteLine(message);
}
message = Environment.NewLine + "Press Enter To Exit The Program: ";
Console.Write(message);
Console.ReadLine();
}
public static void AddressCorrectionTest(InCodeWS4C1Client ws4c1, string authtoken)
{
AnalyzeGetAlternativesInput request = null;
AnalyzeGetAlternativesOutput response = null;
AddressLayout layout = null;
string sLine = string.Empty;
Console.WriteLine(Environment.NewLine + "SOAP Address Correction Test" + Environment.NewLine);
try
{
// define the input request parameters:
request = new AnalyzeGetAlternativesInput();
Console.Write("Adress Layout: ");
request.strLayout = Console.ReadLine();
Console.Write("Analysis Mode: ");
request.strAnalysis = Console.ReadLine();
Console.Write("Correction Style: ");
request.strCorrection = Console.ReadLine();
// set the maximum number of alternatives, version 4.10 or later
request.MaxAlternatives = MAX_SHOW_ALTERNATIVES;
// will need the line names for the user input
using (new OperationContextScope((IClientChannel)(ws4c1.InnerChannel)))
{
WebOperationContext.Current.OutgoingRequest.Headers[HTTP_HEADER_NAME] = authtoken;
layout = ws4c1.GetLayoutDetails(request.strLayout);
}
if (layout.intRetCode == 0)
{
throw new Exception(layout.strMessage);
}
// gather the address information
request.udtLinesIn = new LineContent[layout.intTotalLines];
Console.WriteLine();
for (int index = 0; index < layout.intTotalLines; index++)
{
request.udtLinesIn[index] = new LineContent();
request.udtLinesIn[index].strName = layout.Lines[index].strLineName;
Console.Write(layout.Lines[index].strLineName + ": ");
sLine = Console.ReadLine();
request.udtLinesIn[index].strContent = sLine;
}
// perform the address correction
using (new OperationContextScope((IClientChannel)(ws4c1.InnerChannel)))
{
WebOperationContext.Current.OutgoingRequest.Headers[HTTP_HEADER_NAME] = authtoken;
response = ws4c1.AnalyzeGetAlternatives(request);
}
if (response.intRetCode != 0)
{
Console.WriteLine();
Console.WriteLine("Resulting Message: " + response.strMessage);
Console.WriteLine("Address Status: " + response.strStatus);
Console.WriteLine("Number Of Alternatives: " + response.intAlternatives);
Console.WriteLine("Actual Alternatives Found: " + response.ActualAlternativesFound);
Console.WriteLine("Address Hash Code: " + response.HashCode);
Console.WriteLine();
Console.WriteLine("Resulting Addreess:");
for (int index = 0; index < response.udtLinesOut.Length; index++)
{
sLine = response.udtLinesOut[index].strName + ": ";
sLine += response.udtLinesOut[index].strContent;
Console.WriteLine(sLine);
}
// here is where AnalyzeGetAlternatives method offers more information than the simpler AnalyzeAddress method
if (response.intAlternatives > 0)
{
Console.WriteLine();
Console.WriteLine("Address Alternatives:");
for (int count = 0; count < response.Alternatives.Length; count++)
{
AlternativeAddress aa = response.Alternatives[count];
string alternative = (count + 1).ToString() + ". " + Common.PresentAddress(aa.Address);
Console.WriteLine(alternative);
}
}
}
else
{
Console.WriteLine("Unexpected Address Correction Error: " + response.strMessage);
}
}
catch (Exception ex)
{
Console.WriteLine("Unexpected Exception: " + ex.ToString());
}
WaitBeforeContinuing();
}
public static void AddressTransformationTest(InCodeWS4C1Client ws4c1, string authtoken)
{
AddressLayout layout = null;
TransformInput request = new TransformInput();
TransformOutput response = null;
string sLine = string.Empty;
Console.WriteLine(Environment.NewLine + "SOAP Address Transformation Test" + Environment.NewLine);
try
{
// define the input request parameters:
Console.Write("Input Adress Layout: ");
request.strFirstLayout = Console.ReadLine();
Console.Write("Output Adress Layout: ");
request.strSecondLayout = Console.ReadLine();
Console.Write("Analysis Mode: ");
request.strAnalysis = Console.ReadLine();
Console.Write("Correction Style: ");
request.strCorrection = Console.ReadLine();
// will need the line names for the user input
using (new OperationContextScope((IClientChannel)(ws4c1.InnerChannel)))
{
WebOperationContext.Current.OutgoingRequest.Headers[HTTP_HEADER_NAME] = authtoken;
layout = ws4c1.GetLayoutDetails(request.strFirstLayout);
}
if (layout.intRetCode == 0)
{
throw new Exception(layout.strMessage);
}
// gather the input address information
request.udtLinesIn = new LineContent[layout.intTotalLines];
Console.WriteLine();
for (int index = 0; index < layout.intTotalLines; index++)
{
request.udtLinesIn[index] = new LineContent();
request.udtLinesIn[index].strName = layout.Lines[index].strLineName;
Console.Write(layout.Lines[index].strLineName + ": ");
sLine = Console.ReadLine();
request.udtLinesIn[index].strContent = sLine;
}
using (new OperationContextScope((IClientChannel)(ws4c1.InnerChannel)))
{
WebOperationContext.Current.OutgoingRequest.Headers[HTTP_HEADER_NAME] = authtoken;
response = ws4c1.TransformAddress(request); // perform the transformation
}
// present the results
Console.WriteLine();
Console.WriteLine("Return Code: " + response.intRetCode);
Console.WriteLine("Message: " + response.strMessage);
if (response.intRetCode != 0)
{
Console.WriteLine();
Console.WriteLine("Transformed Address:");
for (int index = 0; index < response.udtLinesOut.Length; index++)
{
sLine = response.udtLinesOut[index].strName + ": ";
sLine += response.udtLinesOut[index].strContent;
Console.WriteLine(sLine);
}
}
else
{
Console.WriteLine("Unexpected Address Transformation Error: " + response.strMessage);
}
}
catch (Exception ex)
{
Console.WriteLine("Unexpected Exception: " + ex.ToString());
}
WaitBeforeContinuing();
}
public static void AddressSearchTest(InCodeWS4C1Client ws4c1, string authtoken)
{
BrowsingRequest request = new BrowsingRequest();
AddressesFound response = null;
string sLine = string.Empty;
Console.WriteLine(Environment.NewLine + "SOAP Address Search Test" + Environment.NewLine);
try
{
// define the search conditions:
request.TargetType = NB_TargetType.NB_TargetAddresses;
// for simplicity, search by postal code only
Console.Write("Postal Code To Search: ");
request.PostalCode = Console.ReadLine();
// set other name conditions to empty
request.Name = string.Empty;
request.Type = string.Empty;
request.Direction = string.Empty;
request.Municipality = string.Empty;
request.Province = string.Empty;
request.NumberFrom = string.Empty;
request.NumberTo = string.Empty;
request.RouteKeyword = string.Empty;
request.RouteNumber = string.Empty;
// set the inclusion conditions
request.IncludeAll = NB_IsIncluded.NB_IncludedYes;
request.AllInRange = NB_AllInRange.NB_AllInRangeNo;
request.IncludeStreet = NB_IsIncluded.NB_IncludedYes;
request.IncludeSSBR = NB_IsIncluded.NB_IncludedYes;
request.IncludePOBox = NB_IsIncluded.NB_IncludedYes;
request.IncludeRoute = NB_IsIncluded.NB_IncludedYes;
request.IncludeGD = NB_IsIncluded.NB_IncludedYes;
request.IncludeUrban = NB_IsIncluded.NB_IncludedYes;
request.IncludeRural = NB_IsIncluded.NB_IncludedYes;
// set the conditions that are new to nCodeWS4
request.ApplyMisspellings = false;
request.ApplyMissingWords = false;
request.AccentedInput = false;
request.AccentedOutput = true;
request.LowercaseOutput = true;
request.ApplyAltMnc = false;
request.UseMncAsGda = false;
// the max items to be returned
request.MaxItems = MAX_SHOW_ALTERNATIVES;
// perform the search
using (new OperationContextScope((IClientChannel)(ws4c1.InnerChannel)))
{
WebOperationContext.Current.OutgoingRequest.Headers[HTTP_HEADER_NAME] = authtoken;
response = ws4c1.SearchForAddresses(request);
}
// present the results
Console.WriteLine();
if (response.intRetCode == 0) // failed, report the error
{
throw new Exception("Address Search Error:" + response.strMessage);
}
else // present the results
{
sLine = "Total " + response.Address.Length + " Addresses Found.";
Console.WriteLine(sLine);
foreach (AddressElements ae in response.Address)
{
sLine = Common.PresentAddress(ae);
Console.WriteLine(sLine);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Unexpected Exception: " + ex.ToString());
}
WaitBeforeContinuing();
}
public static void AddressBrowsingTest(InCodeWS4C1Client ws4c1, string authtoken)
{
AddressLayout layout = new AddressLayout();
BrowseAddressExInput request = new BrowseAddressExInput();
BrowseAddressExOutput response = null;
string sLine = string.Empty;
Console.WriteLine(Environment.NewLine + "SOAP Address Browsing Test" + Environment.NewLine);
try
{
// define the input request parameters:
Console.Write("Adress Layout: ");
request.strLayout = Console.ReadLine();
Console.Write("Analysis Mode: ");
request.strAnalysis = Console.ReadLine();
Console.Write("Correction Style: ");
request.strCorrection = Console.ReadLine();
// set the maximum number of alternatives, version 4.10 or later
request.MaxAlternatives = MAX_SHOW_ALTERNATIVES;
// will need the line names for the user input
using (new OperationContextScope((IClientChannel)(ws4c1.InnerChannel)))
{
WebOperationContext.Current.OutgoingRequest.Headers[HTTP_HEADER_NAME] = authtoken;
layout = ws4c1.GetLayoutDetails(request.strLayout);
}
if (layout.intRetCode == 0)
{
throw new Exception(layout.strMessage);
}
// gather the input address information
request.udtLinesIn = new LineContent[layout.intTotalLines];
Console.WriteLine();
for (int index = 0; index < layout.intTotalLines; index++)
{
request.udtLinesIn[index] = new LineContent();
request.udtLinesIn[index].strName = layout.Lines[index].strLineName;
Console.Write(layout.Lines[index].strLineName + ": ");
sLine = Console.ReadLine();
request.udtLinesIn[index].strContent = sLine;
}
request.GuessingFlags = new GuessingModes(); // new to nCodeWS4
// for simplicity, use the defaults implied by the analysis mode
request.GuessingFlags.UseDefaults = true;
using (new OperationContextScope((IClientChannel)(ws4c1.InnerChannel)))
{
WebOperationContext.Current.OutgoingRequest.Headers[HTTP_HEADER_NAME] = authtoken;
response = ws4c1.BrowseAddressEx(request); // perform the browsing
}
// present the results
Console.WriteLine();
Console.WriteLine(response.strMessage); // present the outcome
// if successful, present the address browsing results
if (response.intRetCode != 0 && response.ResultType != DAB_ResultType.DAB_Empty)
{
Console.WriteLine();
if (response.ResultType == DAB_ResultType.DAB_Addresses)
{
sLine = "Showing " + response.Address.Length + " out of " + response.ActualItemsFound + " Addresses Found.";
Console.WriteLine(sLine);
for (int count = 0; count < response.Address.Length; count++)
{
AddressElements ae = response.Address[count];
sLine = (count + 1).ToString() + ". " + Common.PresentAddress(ae);
Console.WriteLine(sLine);
}
}
else // the list of names has been created
{
sLine = "Showing " + response.Name.Length + " out of " + response.ActualItemsFound + " Names Found.";
Console.WriteLine(sLine);
for (int count = 0; count < response.Name.Length; count++)
{
ParserElements pe = response.Name[count];
sLine = (count + 1).ToString() + ". " + Common.PresentPEOneLine(pe);
Console.WriteLine(sLine);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Unexpected Exception: " + ex.ToString());
}
WaitBeforeContinuing();
}
public static void TestOneStop(InCodeWS4C1Client ws4c1, string authtoken)
{
OneStopAnalyzeInput request = null;
OneStopAnalyzeOutput response = null;
AddressLayout layout = null;
string message = String.Empty;
bool shouldExit = false;
bool newAddress = true;
string sLine = null;
const int BROWSING_LEVEL = 2;
Console.WriteLine(Environment.NewLine + "SOAP oneStop Address Capture Test" + Environment.NewLine);
try
{
request = new OneStopAnalyzeInput();
// define the input request parameters:
Console.Write("Adress Layout: ");
request.AddressLayout = Console.ReadLine();
Console.Write("Analysis Mode: ");
request.AnalysisMode = Console.ReadLine();
Console.Write("Correction Style: ");
request.CorrectionStyle = Console.ReadLine();
request.MaxAlternatives = MAX_SHOW_ALTERNATIVES;
request.BrowsingLevel = BROWSING_LEVEL;
request.SelectedAlternative = string.Empty;
request.EnableAltDetails = false;
request.GuessingFlags = new GuessingModes();
// for simplicity, use the defaults implied by the analysis mode
request.GuessingFlags.UseDefaults = true;
// will need the line names for the user input
using (new OperationContextScope((IClientChannel)(ws4c1.InnerChannel)))
{
WebOperationContext.Current.OutgoingRequest.Headers[HTTP_HEADER_NAME] = authtoken;
layout = ws4c1.GetLayoutDetails(request.AddressLayout); // perform the browsing
}
if (layout.intRetCode == 0)
{
throw new Exception(layout.strMessage);
}
else
{
request.AddressLinesIn = new LineContent[layout.intTotalLines];
}
do
{
if (newAddress)
{
// collect the address lines
Console.WriteLine();
for (int index = 0; index < layout.intTotalLines; index++)
{
request.AddressLinesIn[index] = new LineContent();
request.AddressLinesIn[index].strName = layout.Lines[index].strLineName;
Console.Write(layout.Lines[index].strLineName + ": ");
sLine = Console.ReadLine();
request.AddressLinesIn[index].strContent = sLine;
}
}
// check if the user wants to exit
if (shouldExit)
{
break;
}
// process the user request
using (new OperationContextScope((IClientChannel)(ws4c1.InnerChannel)))
{
WebOperationContext.Current.OutgoingRequest.Headers[HTTP_HEADER_NAME] = authtoken;
response = ws4c1.OneStopAnalyze(request); // perform the browsing
}
// verify the return code
if (!response.SuccessStatus)
{
// should not happen
message = "Unexpected Failure While Calling OneStopAnalyze().";
message += Environment.NewLine + "Reason: " + response.Message;
Console.WriteLine(message);
break;
}
else // normal flow
{
if (response.AddressComplete) // complete address
{
// present the message
Console.WriteLine();
Console.WriteLine(response.Message);
Console.WriteLine();
// see if LVR name is applicable
if (response.AddressDetails[0].LVRType != AES_TypeOfLVR.AES_NotAnLVR)
{
string lvrName = string.Empty;
if (response.AddressDetails[0].LVRType == AES_TypeOfLVR.AES_Building)
{
lvrName = "Building: " + response.AddressDetails[0].LVRName;
}
else if (response.AddressDetails[0].LVRType == AES_TypeOfLVR.AES_GovStreetLVR)
{
lvrName = "GOV. LVR: " + response.AddressDetails[0].LVRName;
lvrName += ", " + response.AddressDetails[0].BranchName;
}
else if (response.AddressDetails[0].LVRType == AES_TypeOfLVR.AES_GovPOBoxLVR)
{
lvrName = "GOV. LVR: " + response.AddressDetails[0].LVRName;
lvrName += ", " + response.AddressDetails[0].BranchName;
}
else
{
lvrName = "LVR: " + response.AddressDetails[0].LVRName;
}
// present the LVR information
Console.WriteLine(lvrName);
}
// present the address
for (int index = 0; index < response.AddressLinesOut.Length; index++)
{
sLine = response.AddressLinesOut[index].strName + ": ";
sLine += response.AddressLinesOut[index].strContent;
Console.WriteLine(sLine);
}
request.SelectedAlternative = string.Empty;
newAddress = true;
}
else if (response.AlternativeListType == AltListType.Empty) // the list of alternatives is empty
{
// just present the message
Console.WriteLine(response.Message);
request.SelectedAlternative = string.Empty;
newAddress = true;
}
else if (response.AlternativeListType == AltListType.Addresses && response.Alternatives.Count == 1) // one address alternative
{
// this means we should have the suggested address available
// present the alternative address record, since it will contain range information
Console.WriteLine(response.Alternatives[0]);
// present the suggested address
for (int index = 0; index < response.SuggestedLines.Length; index++)
{
sLine = response.SuggestedLines[index].strName + ": ";
sLine += response.SuggestedLines[index].strContent;
Console.WriteLine(sLine);
}
// get the intended range number from the user
Console.Write("Please Enter The Intended Number: ");
string sNumber = Console.ReadLine();
// redefine the user input
foreach (LineContent line in response.SuggestedLines)
{
if (line.strContent.Contains("?###"))
{
line.strContent = line.strContent.Replace("?###", sNumber);
}
}
request.AddressLinesIn = response.SuggestedLines;
request.SelectedAlternative = string.Empty;
newAddress = false;
}
else // present the list of alternatives and ask for a selection
{
newAddress = false;
if (response.AlternativeListType == AltListType.Addresses)
{
message = "A List Of " + response.Alternatives.Count + " Address Records Was Created:";
}
else if (response.AlternativeListType == AltListType.Names)
{
message = "A List Of " + response.Alternatives.Count + " Street/Station Names Was Created:";
}
else
{
message = "Invalid Alternative List Type (" + response.AlternativeListType.ToString() + ").";
}
Console.WriteLine(message);
if (response.Alternatives.Count != response.ActualAlternativesFound)
{
message = "The Number Of Items Actually Found Was " + response.ActualAlternativesFound + ".";
Console.WriteLine(message);
}
// present the list
Console.WriteLine();
for (int iIndex = 1; iIndex <= response.Alternatives.Count; iIndex++)
{
// get the alternative and present it
string lineNumber = iIndex.ToString() + ".";
message = lineNumber.PadRight(5) + response.Alternatives[iIndex - 1];
Console.WriteLine(message);
}
// separate the list from the rest
Console.WriteLine();
// ask for the index of the selected alternative
int iSelectedIndex;
if (response.Alternatives.Count == 1) // only one item in the list
{
iSelectedIndex = 1;
}
else if (response.Alternatives.Count > 1) // ask for the index
{
Console.Write("Please Enter The Index Of The Selected Alternative: ");
string number = Console.ReadLine();
if (number.Length > 0 && number[0] == '*')
{
request.SelectedAlternative = string.Empty;
shouldExit = false;
newAddress = true;
continue;
}
if (!int.TryParse(number, out iSelectedIndex) ||
iSelectedIndex < 1 ||
iSelectedIndex > response.Alternatives.Count)
{
message = "Invalid Index Was Selected.";
Console.WriteLine(message);
continue;
}
}
else
{
request.SelectedAlternative = string.Empty;
continue;
}
// define the selected alternative, no need to check the return value again
request.SelectedAlternative = response.Alternatives[iSelectedIndex - 1];
}
}
Console.WriteLine();
if (newAddress)
{
// ask if more oneStop address capture is needed
Console.Write("More oneStop Address Capture(Y=Yes,N=No): ");
string choice = Console.ReadLine();
if (choice.Equals("N", StringComparison.CurrentCultureIgnoreCase))
shouldExit = true;
}
} while (!shouldExit);
}
catch (Exception ex)
{
Console.WriteLine("Unexpected Exception: " + ex.ToString());
}
WaitBeforeContinuing();
}
public static void TestGetMethods(InCodeWS4C1Client ws4c1, string token)
{
WebServiceInfo wsiresponse = null;
ParamList paramlist = null;
AddressLayout layout = null;
const string LAYOUT_NAME = "SERP TEST";
Console.WriteLine(Environment.NewLine + "SOAP Get Methods Test " + Environment.NewLine);
try
{
// retrieve Web service information
using (new OperationContextScope((IClientChannel)(ws4c1.InnerChannel)))
{
WebOperationContext.Current.OutgoingRequest.Headers[HTTP_HEADER_NAME] = token;
wsiresponse = ws4c1.GetWebServiceInfo();
}
// print out Web service info
if (!wsiresponse.SuccessStatus) // failed, report the error
{
Console.WriteLine(wsiresponse.Message);
}
else // present the results
{
Console.WriteLine("Web Service Info:");
Console.WriteLine("Web Service Name: " + wsiresponse.WebServiceName);
Console.WriteLine("Web Service Version: " + wsiresponse.WebServiceVersion);
Console.WriteLine("Native Library Version: " + wsiresponse.NativeLibraryVersion);
Console.WriteLine("Address Data Version: " + wsiresponse.DataVersion);
}
WaitBeforeContinuing();
// list the address layouts
using (new OperationContextScope((IClientChannel)(ws4c1.InnerChannel)))
{
WebOperationContext.Current.OutgoingRequest.Headers[HTTP_HEADER_NAME] = token;
paramlist = ws4c1.GetParamList(NPAR_ParameterType.NPAR_AddressLayouts);
}
if (paramlist.intRetCode == 0) // failed, report the error
{
Console.WriteLine(paramlist.strMessage);
}
else // present the list of address layouts:
{
Console.WriteLine("Found " + paramlist.strParamName.Count + " Address Layouts: ");
for (int count = 0; count < paramlist.strParamName.Count; count++)
{
string sLine = (count + 1).ToString() + ". " + paramlist.strParamName[count];
Console.WriteLine(sLine);
}
}
WaitBeforeContinuing();
// list the analysis modes
using (new OperationContextScope((IClientChannel)(ws4c1.InnerChannel)))
{
WebOperationContext.Current.OutgoingRequest.Headers[HTTP_HEADER_NAME] = token;
paramlist = ws4c1.GetParamList(NPAR_ParameterType.NPAR_AnalysisModes);
}
if (paramlist.intRetCode == 0) // failed, report the error
{
Console.WriteLine(paramlist.strMessage);
}
else // present the list of analysis modes
{
Console.WriteLine("Found " + paramlist.strParamName.Count + " Analysis Modes: ");
for (int count = 0; count < paramlist.strParamName.Count; count++)
{
string sLine = (count + 1).ToString() + ". " + paramlist.strParamName[count];
Console.WriteLine(sLine);
}
}
WaitBeforeContinuing();
// list the correction styles
using (new OperationContextScope((IClientChannel)(ws4c1.InnerChannel)))
{
WebOperationContext.Current.OutgoingRequest.Headers[HTTP_HEADER_NAME] = token;
paramlist = ws4c1.GetParamList(NPAR_ParameterType.NPAR_CorrectionStyles);
}
if (paramlist.intRetCode == 0) // failed, report the error
{
Console.WriteLine(paramlist.strMessage);
}
else // present the list of correction styles
{
Console.WriteLine("Found " + paramlist.strParamName.Count + " Correction Styles: ");
for (int count = 0; count < paramlist.strParamName.Count; count++)
{
string sLine = (count + 1).ToString() + ". " + paramlist.strParamName[count];
Console.WriteLine(sLine);
}
}
WaitBeforeContinuing();
// present the properties of a specific address layout
using (new OperationContextScope((IClientChannel)(ws4c1.InnerChannel)))
{
WebOperationContext.Current.OutgoingRequest.Headers[HTTP_HEADER_NAME] = token;
layout = ws4c1.GetLayoutDetails(LAYOUT_NAME);
}
if (layout.intRetCode == 0) // failed, report the error
{
Console.WriteLine(layout.strMessage);
}
else // present the address layout details
{
Console.WriteLine("Address Layout '{0}' Details:", layout.strLayoutName);
Console.WriteLine("Record Length: {0}", layout.intRecordLength);
Console.WriteLine("Number Of Lines: {0}", layout.intTotalLines);
// present each address line details
for (int count = 0; count < layout.Lines.Length; count++)
{
AddressLine al = layout.Lines[count];
string line = ((count + 1) + ". ").PadLeft(5);
line += al.strLineName + " [" + al.intLineStart + ",";
line += (al.intLineStart + al.intLineLength - 1) + "]";
// present the list of address types associated with the line
foreach (NAT_AddressType at in al.Types)
{
line += " " + at.ToString();
}
// present the address line
Console.WriteLine(line);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Unexpected Exception: " + ex.ToString());
}
WaitBeforeContinuing();
}
// ws4tsurl is the url of the token service
// cn represents the customer name
// lk represents the license key related to the customer
// tl represents the token duration in minutes
public static GetTokenOutput GetSecurityToken(string ws4tsurl, string cn, string lk, int tl)
{
InCodeWS4TSClient ws4ts = null; // nCodeWS4TS proxy reference
string authtoken = string.Empty;
GetTokenOutput response = null;
try
{
// the credentials passed to the token web service must be in the <customer>|<license key> form
authtoken = cn + "|" + lk;
EndpointAddress endpointAddress = new EndpointAddress(ws4tsurl);
BasicHttpBinding binding = new BasicHttpBinding();
// set the timeouts
binding.MaxReceivedMessageSize = MAX_MESSAGE; // 10 MB, just in case
binding.OpenTimeout = new TimeSpan(0, 0, OPEN_TIMEOUT);
binding.CloseTimeout = new TimeSpan(0, 0, CLOSE_TIMEOUT);
binding.SendTimeout = new TimeSpan(0, 0, SEND_TIMEOUT);
binding.ReceiveTimeout = new TimeSpan(0, 0, RECIEVE_TIMEOUT);
// for better performance, do not use default web proxy
binding.UseDefaultWebProxy = false;
// this ensures it works in any environment
if (ws4tsurl.ToLower().StartsWith("https"))
{
binding.Security.Mode = BasicHttpSecurityMode.Transport;
}
// call the token web service
ws4ts = new InCodeWS4TSClient(binding, endpointAddress);
using (new OperationContextScope((IClientChannel)(ws4ts.InnerChannel)))
{
WebOperationContext.Current.OutgoingRequest.Headers[HTTP_HEADER_NAME] = authtoken;
response = ws4ts.GetToken(tl);
}
// verify the results
if (response.Outcome)
{
return response;
}
else // failed
{
string message = "Error getting security token. Reason: " + response.Message;
throw new Exception(message);
}
}
catch (Exception ex)
{
// possible error handling here, before rethrowing the exception
throw ex;
}
}
public static InCodeWS4C1Client GetWS4C1Client(string ws4c1url)
{
InCodeWS4C1Client ws4c1 = null;
try
{
EndpointAddress endpointAddress = new EndpointAddress(ws4c1url);
BasicHttpBinding binding = new BasicHttpBinding();
binding.MaxReceivedMessageSize = MAX_MESSAGE; // 10 MB, just in case
// set the timeouts
binding.OpenTimeout = new TimeSpan(0, 0, OPEN_TIMEOUT);
binding.CloseTimeout = new TimeSpan(0, 0, CLOSE_TIMEOUT);
binding.SendTimeout = new TimeSpan(0, 0, SEND_TIMEOUT);
binding.ReceiveTimeout = new TimeSpan(0, 0, RECIEVE_TIMEOUT);
// for better performance, do not use default web proxy
binding.UseDefaultWebProxy = false;
// additional action is needed for URL configured for https
if (ws4c1url.ToLower().StartsWith("https"))
{
binding.Security.Mode = BasicHttpSecurityMode.Transport;
}
// create the client proxy using the specific endpoint and binding you have created
ws4c1 = new InCodeWS4C1Client(binding, endpointAddress);
return ws4c1;
}
catch (Exception ex)
{
// possible error handling here, before rethrowing the exception
throw ex;
}
}
private static void WaitBeforeContinuing()
{
Console.WriteLine();
Console.Write(Environment.NewLine + "Please press Enter to continue: ");
Console.ReadLine(); // wait for the user's response
Console.WriteLine();
}
}
}
SDKs & helper bundles
For a complete C# or Java starter project, see Downloads — each zip contains a runnable sample app, the generated client proxy, and a README.