Page tree

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Localtab Group



Localtab
titleC#



Code Block
languagec#
titleEmail Validation C# Code Address GeoCoder Canada C# Rest Snippet
linenumberstrue
EV3Response  try
            {
                result = nullHttpGet(mainURL);
string mainURL = "https://trial.serviceobjects.com/ev3/web.svc/json/ValidateEmailInfo?" + "EmailAddress=" + email + "&AllowCorrections=" + allowcorrections + "&Timeout=" + timeout + "&LicenseKey=" + licenseKey;
string backupURL = "https://trial.serviceobjects.com/ev3/web.svc/json/ValidateEmailInfo?" + "EmailAddress=" + email + "&AllowCorrections=" + allowcorrections + "&Timeout=" + timeout + "&LicenseKey=" + licenseKey;
try
{
    HttpWebRequest request = WebRequest.Create(mainURL) as HttpWebRequest;
    request.Timeout = 5000;//timeout for get operation
    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
    {              //NULL ERROR || FATAL ERROR RETURNED -- TRY BACKUP 
                if (result == null || (result.Error != null && result.Error.Number == "3"))
                {
                    return HttpGet(backupURL);
               if (response.StatusCode != HttpStatusCode.OK)}
          {      else
      throw new Exception(String.Format("Server error (HTTP {0}: {1}).",response.StatusCode,response.StatusDescription));     {
        }         //parse response  return result;
     DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(EV3Response));       }
 object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());        }
result = objResponse as EV3Response;     } }  catch (Exception e)
            {   //ERROR IN MAIN URL - USING BACKUP
                return HttpGet(backupURL);
            }
  
    public static GCCResponse HttpGet(string requestUrl)
        {
            try
            {
                System.Diagnostics.Debug.Write(requestUrl);
                HttpWebRequest request = WebRequest.Create(backupURLrequestUrl) as HttpWebRequest;
                request.Timeout = 5000WEB_SERVICE_REQUEST_TIMEOUT;//timeout for get operation
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    if (response.StatusCode != HttpStatusCode.OK)
        {                throw new Exception(String.Format(
                        "Server error (HTTP {0}: {1}).",
                        response.StatusCode,
                        response.StatusDescription));
        }            //parseprrocessing response
                    DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(EV3ResponseGCCResponse));
                    object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
        result             GCCResponse jsonResponse = objResponse as EV3ResponseGCCResponse;
    } }
Localtab
titleJava
Code Block
languagejava
titleEmail Validation 3 Java Code Snippet
linenumberstrue
ValidateEmailResponse.Error error = null; ValidateEmailResponse.ValidateEmailInfo info = null; try {      return StringjsonResponse;
email = request.getParameter("iEmail");     String allowcorrections = request.getParameter("iAllowCorrections");     String timeout}
= request.getParameter("iTimeout");     String licenseKey = request.getParameter("iKey");   }
   EV3RestClient EV3Client = new EV3RestClient();      catch (Exception e)
    ValidateEmailResponse result = EV3Client.ValidateEmailResponse(email, allowcorrections, timeout, licenseKey);  {
  if (result != null) {         error =throw result.errore;
        info = result.ValidateEmailInfo;  }
        }



Localtab
titlePHPJava



Code Block
languagephpjava
titleEmail Validation 3 PHP Address GeoCoder Canada Java Code Snippet
linenumberstrue
//JSONObject variableresults cleanup before generating url
$Email = trim($Email);
$AllowCorrections = trim($AllowCorrections);
$Timeout = trim($Timeout);
$LicenseKey = trim($LicenseKey);
 
 
= RestClient(mainURL);   
if (ErrorMessages != null || (results.has("Error") && results.getJSONObject("Error").get("Number") == "3")) {
    // BACKUP
    results = RestClient(backupURL);
}
 
 
return results;



Localtab
titlePHP



Code Block
languagephp
titleAddress GeoCoder Canada PHP Code Snippet
linenumberstrue
$URL = "https://trial.serviceobjects.com/ev3GCC/webapi.svc/jsonxml/ValidateEmailInfoGetGeoLocation?EmailAddressAddress=".urlencode($Email$Address)."&AllowCorrectionsMunicipality=".urlencode($AllowCorrections$Municipality)."&TimeoutProvince=".urlencodeurldecode($Timeout$Province)."&PostalCode=".urldecode($PostalCode)."&LicenseKey=".urlencode($LicenseKey);
 
//use backup url once given purchased license key
$backupURL = "https://trial.serviceobjects.com/ev3GCC/webapi.svc/jsonxml/ValidateEmailInfoGetGeoLocation?EmailAddressAddress=".urlencode($Email$Address)."&AllowCorrectionsMunicipality=".urlencode($AllowCorrections$Municipality)."&TimeoutProvince=".urlencodeurldecode($Timeout$Province)."&PostalCode=".urldecode($PostalCode)."&LicenseKey=".urlencode($LicenseKey);
 
      // Get cURL resource
    $curl = curl_init();
    curl_setopt_array($curl, array(CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => $URL, CURLOPT_USERAGENT => 'Service Objects EmailGeocoder Validation 3Canada'));
    curl_setopt($curl, CURLOPT_TIMEOUT, 50); //timeout in seconds
    // Send the request & save response to $resp
    $resp = curl_exec($curl);
     
    // Close request to clear up some resources
    if($resp == false)
    {
        echo "IN back up block";
        curl_setopt_array($curl, array(CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => $backupURL, CURLOPT_USERAGENT => 'Service Objects EmailGeocoder Validation 3Canada'));
        curl_setopt($curl, CURLOPT_TIMEOUT, 50); //timeout in seconds
        // Send the request & save response to $resp
        $resp = curl_exec($curl);
        if($resp == false)
        {
            echo "<b> Both rest calls failed </b>";
            curl_close($curl);
            return;
        }
     
     
    }
curl_close($curl);



Localtab
titleRoR



Code Block
languageruby
titleEmail Validation 3 Address GeoCoder Canada RoR Code Snippet
linenumberstrue
@request = Request.find(params[:id])
 
#This sets the default timeout for HTTParty get operation. This must be set in order to use the gem
    default_timeout = 10
 
address = @request.address
municipality licensekey = @request.licensekeymunicipality
province    timeout = @request.timeoutprovince
postalcode    allowcorrections = @request.allowcorrectionspostalcode
licensekey    email = @request.emaillicensekey
 
#Set  #Checks the users input Primary and setsBackup valuesURLs equalas toneeded. anNormalizes underscore if the userURL enteredto nil.that it    #These can be changedpassed to whateverthe your application might need.
    email = "" if @request.email == nil
    timeout = "" if @request.timeout == nil
    allowcorrections = "" if @request.allowcorrections == nil
    licensekey = "" if @request.licensekey == nil
 
   #Set Primary and Backup URLs as needed
    web service.
primaryURL = URI.encode("https://trial.serviceobjects.com/ev3GCC/webapi.svc/jsonxml/ValidateEmailAddressGetGeoLocation?EmailAddressAddress=" + emailaddress + "&AllowCorrectionsMunicipality=" + allowcorrectionsmunicipality + "&TimeoutProvince=" + timeoutprovince + "&LicenseKeyPostalCode=" + licensekeypostalcode )+ "&LicenseKey=" + licensekey)
 backupURL = URI.encode("https://trial.serviceobjects.com/ev3GCC/webapi.svc/jsonxml/ValidateEmailAddress?EmailAddressGetGeoLocation=" + emailaddress + "&AllowCorrectionsMunicipality=" + allowcorrectionsmunicipality + "&TimeoutProvince=" + timeoutprovince + "&LicenseKeyPostalCode=" + licensekeypostalcode )+ "&LicenseKey=" + licensekey)
 
   #These are set to access the hash that is returned
@agcaresult    @validateemailresponse = "ValidateEmailResponseLocation"
@agcaerror    @validateemailinfo = "ValidateEmailInfo"
    @error = "Error"
 
    #Begins the call the RESTful web service
    begin
   
  response = HTTParty.get(primaryURL, timeout: default_timeout)
      #processes the response to display to the screen
   
   
      #Passes the response returned from HTTParty and theprocesses hashthem keydepending valueson tothe thisresults
method       processresults(response)
 
   
 rescue StandardError => e
          begin
          #uses the backupURl in the event that the service encountered an error
          response = HTTParty.get(URI.encode(backupURL), timeout: default_timeout)
     
            #processes the response returned from using the backupURL
         processresults(response)
          #If the backup url railed this will raise an error and display the 
        #error message returned from the HTTParty gem.
          rescue StandardError => error
          end@status = error.message
  end end   private    @displaydata = def processresults(response)  
    #Processes Error Response from rest Client{"Error" => "A Big Error Occured"}
      end
 
  #Processes Valid response from rest client  
   end



Localtab
titlePython



Code Block
languagepy
titleEmail Validation 3 Address GeoCoder Canada Python Code Snippet
linenumberstrue
mEmailAddress#Set =the primary EmailAddress.get()
if mEmailAddress is None or  mEmailAddress == "":
     mEmailAddress = " "
mAllowCorrections =  AllowCorrections.get()
if mAllowCorrections is None or  mAllowCorrections == "":
     mAllowCorrections = " "
mTimeout =  Timeout.get()
if mTimeout is None or  mTimeout == "":
     mTimeout = " "
mLicenseKey = LicenseKey.get()
if mLicenseKey is None or mLicenseKey == "":
    mLicenseKey = " "
#Set the primary and backup URL as needed.
primaryURL = 'https://trial.serviceobjects.com/ev3/web.svc/xml/ValidateEmailAddress?'
backupURL = 'https://trial.serviceobjects.com/ev3/web.svc/xml/ValidateEmailAddress?'
#The
 Requests package allows the user to format the path parameters like so 
instead of having to manually insert them into the URL
inputs = {'EmailAddress': mEmailAddress, 'AllowCorrections': mAllowCorrections, 'Timeout': mTimeout, 'LicenseKey': mLicenseKey}
try:
    and backup URLs as necessary
primaryURL = 'https://trial.serviceobjects.com/GCC/api.svc/xml/GetGeoLocation?'
backupURL = 'https://trial.serviceobjects.com/GCC/api.svc/xml/GetGeoLocation?'
 
#The
 Requests package allows the user to format the path parameters like so 
instead of having to manually insert them into the URL
inputs = {'Address': mAddress, 'Municipality': mMunicipality, 'Province': mProvince, "PostalCode": mPostalCode, 'LicenseKey': mLicenseKey}
try:
    result = requests.get(primaryURL, params=inputs)
    #Parses the XML response from the service into a python dictionary type
    outputs = xmltodict.parse(result.content)
    #checks the output for Errors and displays the info accordingly
    if 'Error' in outputs['Location']:
        #loops through the response from the service and prints the values to the screen.
        for key, value in outputs['Location']['Error'].iteritems():
            Label(swin.window, text=str(key) + " : " + str(value)).pack()
    else:
        #Removes unnecessary values that were parsed from the original xml response
        outputs['Location'].pop("@xmlns:xsi", None)
        outputs['Location'].pop("@xmlns:xsd", None)
        outputs['Location'].pop("@xmlns", None)
        for key, value in outputs['Location'].iteritems():
            Label(swin.window, text=str(key) + " : " + str(value)).pack()
 
#Uses the backup URL in the event that the primary URL failed
except:
    try:
        result = requests.get(primaryURLbackupURL, params=inputs)
        #Parses the XML response from the service into a python dictionary type
        outputs = xmltodict.parse(result.content)
        #checks the output for Errors and displays the info accordingly
        if 'Error' in outputs['ValidateEmailResponseLocation']:
            #loops through the response from the service and prints the values to the screen.
            for key, value in outputs['ValidateEmailResponseLocation']['Error'].iteritems():
                Label(swin.window, text=str(key) + " : " + str(value)).pack()
        else:
        for key, value in outputs['ValidateEmailResponse']['ValidateEmailInfo'].    #Removes unnecessary values that were parsed from the original xml response
            outputs['Location'].pop("@xmlns:xsi", None)
            outputs['Location'].pop("@xmlns:xsd", None)
            outputs['Location'].pop("@xmlns", None)
            for key, value in outputs['Location'].iteritems():
                Label(swin.window, text=str(key) + " : " + str(value)).pack()



Localtab
titleColdFusion



Code Block
languagecoldfusion
titleEmail Validation 3 Address GeoCoder Canada ColdFusion Code Snippet
linenumberstrue
<!--Makes Request to web service --->
<cfIf isDefined("form.Action") AND Action neq ""  >
    <cftry>
        <cfset primaryURL = "https://trial.serviceobjects.com/ev3GCC/webapi.svc/xml/ValidateEmailAddressGetGeoLocation?EmailAddressAddress=#EmailAddress##Address#&AllowCorrectionsMunicipality=#AllowCorrections##Municipality#&TimeoutProvince=#Timeout##Province#&PostalCode=#PostalCode#&LicenseKey=#LicenseKey#">
        <cfhttp url="#primaryURL#" method="get" result="response">
        <cfset outputs = XmlParse(response.FileContent)>
    <cfcatch >   <cfcatch>
            <cftry>
                <cfset backupURL = "https://trial.serviceobjects.com/ev3GCC/webapi.svc/xml/ValidateEmailAddressGetGeoLocation?EmailAddressAddress=#EmailAddress##Address#&AllowCorrectionsCity=#AllowCorrections##City#&TimeoutState=#Timeout##State#&PostalCode=#PostalCode#&LicenseKey=#LicenseKey#">
                <cfhttp url="#backupURL#" method="get" result="response">
                <cfset outputs = XmlParse(outputsresponse.FileContent)>              
                <cfcatch >
                    <cfoutput >
                        The Following Error Occured: #response.StatusCode#
                    </cfoutput>
                </cfcatch>
            </cftry>
        </cfcatch>
    </cftry>
</cfif>



Localtab
titleVB



Code Block
languagevb
titleEmail Validation 3 Address GeoCoder Canada VB Code Snippet
linenumberstrue
email = Me.EmailAddress.Text
licensekey = Me.LicenseKey.Text
allowcorrections = Me.AllowCorrections.Text
timeout = Me.Timeout.Text
Try
    'encodes the URLs for the get Call. Set the primary and back urls as necessary
    Dim primaryurl As String = "https://trial.serviceobjects.com/ev3GCC/webapi.svc/xml/ValidateEmailAddressGetGeoLocation?EmailAddressAddress=" &+ emailaddress + "&AllowCorrectionsMunicipality=" + allowcorrectionsmunicipality + "&TimeoutProvince=" + timeoutprovince + "&LicenseKeyPostalCode=" &+ licensekeypostalcode + "&LicenseKey=" + licensekey
Dim backupurl As String = "https://trial.serviceobjects.com/ev3GCC/webapi.svc/xml/ValidateEmailAddressGetGeoLocation?EmailAddressAddress=" &+ emailaddress + "&AllowCorrectionsMunicipality=" + allowcorrectionsmunicipality + "&TimeoutProvince=" + timeoutprovince + "&LicenseKeyPostalCode=" &+ licensekeypostalcode + "&LicenseKey=" + licensekey
Dim wsresponse As EV3ResponseAGCAResponse.ValidateEmailResponseLocation = httpGet(primaryurl)
 
    'checks if a response was returned from the service, uses the backup url if response is null or a fatal error occured.
    If wsresponse Is Nothing OrElse (wsresponse.[Error] IsNot Nothing AndAlso wsresponse.[Error].TypeCodeNumber = "3") Then
        wsresponse = httpGet(backupurl)
    End If
    If wsresponse.[Error] IsNot Nothing Then
        ProcessErrorResponse(wsresponse.[Error])
    Else
        ProcessSuccessfulResponse(wsresponse)
 
  End If
Catch ex As Exception
    'Displays the relevant error mesasge if both backup and primary urls failed.
    resultsLabel.Text = ex.Message
    resultsLabel.Visible = True
End Try



Localtab
titleTSQL



Code Block
languagesql
titleEmail Validation 3 Address GeoCoder Canada TSQL Code Snippet
linenumberstrue
--If a production key is purchased, this will execute the failover 
IF @isLiveKey = 1
BEGIN
    SET @sUrl = 'https://trial.serviceobjects.com/ev3GCC/webapi.svc/xml/ValidateEmailAddressGetGeoLocation?EmailAddressAddress=' + @email@address + '&AllowCorrectionsMunicipality=' + @allowcorrections@municipality + '&TimeoutProvince=' + @timeout@province + '&PostalCode=' + @postalcode + '&LicenseKey=' + @key
    EXEC sp_OACreate 'MSXML2.ServerXMLHttp', @obj OUT
    EXEC sp_OAMethod @obj, 'Open', NULL, 'Get', @sUrl, false
    EXEC sp_OAMethod @obj, 'send'
    EXEC sp_OAGetProperty @obj, 'responseText', @response OUT
             
    --Checks the Response for a fatal error or if null. 
    IF @response IS NULL
    BEGIN
        SET @sBackupUrl = 'https://trial.serviceobjects.com/ev3GCC/webapi.svc/xml/ValidateEmailAddressGetGeoLocation?EmailAddressAddress=' + @email@address + '&AllowCorrectionsMunicipality=' + @allowcorrections@municipality + '&TimeoutProvince=' + @timeout@province + '&PostalCode=' + @postalcode + '&LicenseKey=' + @key
        EXEC sp_OACreate 'MSXML2.ServerXMLHttp', @obj OUT
        EXEC sp_OAMethod @obj, 'Open', NULL, 'Get', @sBackupUrl, false
        EXEC sp_OAMethod @obj, 'send'
        EXEC sp_OAGetProperty @obj, 'responseText', @response OUT
    END
END



Localtab
titleNodeJS



Code Block
languagejs
titleAddress GeoCoder Canada NodeJS Code Snippet
linenumberstrue
var Address = 'Address';
var Municipality ='Municipality';
var Province ='Province'; 
var PostalCode ='PostalCode';
var LicenseKey ='LicenseKey';
//Set backup and primary URL as necessary
var primaryUrl = 'https://trial.serviceobjects.com/GCC/api.svc/xml/GetGeoLocation?Address=' + Address + '&Municipality=' + Municipality +'&Province=' + Province +'&PostalCode=' + PostalCode +'&LicenseKey=' + LicenseKey;
var backupUrl = 'https://trial.serviceobjects.com/GCC/api.svc/xml/GetGeoLocation?Address=' + Address + '&Municipality=' + Municipality +'&Province=' + Province +'&PostalCode=' + PostalCode +'&LicenseKey=' + LicenseKey;
 
var req = http.get(primaryUrl, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (results) {
        var parser = require('xml2js').Parser({explicitArray: false,ignoreAttrs: true});
        parser.parseString(results, function (err, outputs) {
            if (outputs.Location.Error !=  null)
            {
                //Indicates a Fatal error has occured. If this happens, the logic will then failover to the backup url
                if (outputs.Location.Error.Number == "4")
                {
                    var backupReq = http.get(backupUrl, function(backupRes) {
                        backupRes.setEncoding('utf8');
                        backupRes.on('data', function (results) {
                            var parser = require('xml2js').Parser({explicitArray: false,ignoreAttrs: true});
                            parser.parseString(results, function (err, outputs) {
                                console.log("Backup Call Was Used.");
                                response.end(JSON.stringify(outputs , null, 3));
                                });
                            });
                        });
                }
                else
                {
                    //Will Display the JSON Formatted Error Response here
                    response.end(JSON.stringify(outputs, null, 3));
                    return;
                }
            }
            else
            {
                //Will Display the JSON Formatted Valid Response here
                response.end(JSON.stringify(outputs, null, 3));
                return;
            }
        });
    });
});







  
We want to hear from you! We're always looking to improve our developer guides. 
Please email your suggestions to devguidefeedback@serviceobjects.com.