DEMO 2: C# Visual Studio 2015 or older

An example of how to call the API using C#

Prerequisites

For this demonstration we are using Visual Studio 2015, but you should be able to perform the same steps in Visual Studio 2013 and Visual Studio 2012. You can download the code sample from the link below. We are going to walk through setting up a simple solution with a few basic components to call the service.

 Download the code

Step One: Setup the solution

For this demo we are going to create a class library that wraps the service call and a simple console app that uses this library to call the service.

1. From the Start page of visual studio click on File -> New -> Project...

file new project

2. Create a new Blank Solution project. You can find it by typing "Blank Solution" in the search box in the top right of the screen.

new blank solution 

3. When the project opens in Visual Studio go to the solution explorer and right click on the solution and select Add -> New Project

new project 

4. Name the class library W2Demo.DataAccess.ThirdPartyServices.

new class library

5. Delete the Class1.cs file as it is not required.

6. Repeat the above process and create a new console app. Call it W2Demo.KycChecker

new console app

 

Step Two: Add the service reference

Now we need to add a web service reference for the W2 API.

1. Expand the Third Party Services Class Library we added earlier and right click on references then click on Add Service Reference:

add service reference 

2. You should see a screen like this:

new service ref 

3. In the Address box fill in the UAT service URL: 

https://apiv3-uat.w2globaldata.com/service.svc?wsdl

and click on Go. After the service is done loading change the Namespace to W2GlobalDataService and click on OK

w2 service

4. This will add a ServiceReferences folder and an app.config file.

solution 2

5. The app.config file contains binding information for the service. Add a new folder to the project and add a new class call W2Client. It is good practice to incorporate service calls in separate clients and the use of interfaces which support unit testing best practices.

new client

6. Replace the code in the W2Client class with the following.

NOTE: You will need to replace the Api Key and the Client Reference with your own

namespace W2Demo.DataAccess.ThirdPartyServices.W2
{
    using System.Collections.Generic;
    using W2GlobalDataService;

    public class W2Client
    {
        public ServiceResponse SanctionsCheck(string nameQuery, bool isSandbox = false)
        {
            // Create a client for calling the service. 
using (var proxy = new ServiceClient()) { // build a request object to send to the service var serviceRequest = BuildSanctionsServiceRequest(nameQuery, isSandbox); return proxy.KYCCheck(serviceRequest); } } private ServiceRequest BuildSanctionsServiceRequest(string nameQuery, bool isSandbox = false) { var request = new ServiceRequest(); // Set the name of the bundle we are calling. In this case request.BundleData = new BundleData { BundleName = "DEMO_KYC_SIS" }; // Build up the query data. For SIS only name query is required. // This will vary for other services request.QueryData = new QueryData { NameQuery = nameQuery }; // The service authorization is the same for all services. // You can also fill in the optional client reference. request.ServiceAuthorisation = new ServiceAuthorisation { APIKey = "{YOU API KEY GOES HERE}", ClientReference = "{AN OPTIONAL REFERENCE FIELD GOES HERE}" }; // To call the sandbox version of any service you will need to add the // query option like this. And call the service using the sandbox query data // that you can find in our documentation. if (isSandbox) { request.QueryOptions = new Dictionary<string, string> { { "Sandbox", "True" } }; } return request; } } }

Build the solution (Ctrl+Shift+B, or right click on the solution and click on build) to make sure everything is working correctly.

Step Three: The Console App

Now we need to add our new class library as a reference to our console app and start calling the service.

1. Expand the W2Demo.KycChecker project and right click on References and click on add reference:

add reference

2. In the Reference Manager window expand Projects, click on Solution and tick the box next to W2Demo.DataAccess.ThirdPartyServices and click on OK:

add new ref

3. Open up the Program.cs file and replace the contents with the following:

namespace W2Demo.KycChecker
{
    using System;
    using DataAccess.ThirdPartyServices.W2;

    class Program
    {
        static void Main(string[] args)
        {
            // Get the name to search for from the console
            string nameQuery = string.Empty;
            while (string.IsNullOrEmpty(nameQuery))
            {
                Console.WriteLine("Please enter the name you want to search for:");
                nameQuery = Console.ReadLine();
            }

            // Create a new client
            var client = new W2Client();
            try
            {
                // Call the service
                var result = client.SanctionsCheck(nameQuery, false);
                if (result != null)
                {
                    // Here we break down the service response into it's components
                    Console.WriteLine("Service Response:");
                    Console.WriteLine("-------------------------------------------------");

                    // 1. Client Data - this simply reflects back the submitted client data
                    var clientData = result.ClientProvidedData;
                    Console.WriteLine("Client Reference: {0}", clientData.ClientReference);
                    Console.WriteLine("-------------------------------------------------");

                    // 2. Interpret Result - the API returns an interpret result 
// which combines the interpretation
// for all the service in the call. Console.WriteLine("Interpret Result",
result.ProcessRequestResult.TransactionInformation.InterpretResult); Console.WriteLine("Unique Call Reference",
result.ProcessRequestResult.TransactionInformation.ServiceCallReference); // 3. Service Transaction Information - this collection contains
// meta information about every service call
// in this example we are only calling one service
// so we are just looking at the first one but for
// more complicated bundles there will be one of these for each service. var serviceTransactions
= result.ProcessRequestResult.TransactionInformation.ServiceTransactions; // The next object contains the interpretation of the service call
// and is important to examine it thoroughly
// The name of the service Console.WriteLine("Service Name: {0}",
serviceTransactions[0].Service); // Whether the transaction was succesful Console.WriteLine("Service Transaction Result: {0}",
serviceTransactions[0].ServiceTransactionResult); // The interpretation of the service i.e. PASS, FAIL etc.. Console.WriteLine("Service Interpret Result: {0}",
serviceTransactions[0].ServiceInterpretResult); // Any messages the service returns (mostly used for error messages) Console.WriteLine("Message: {0}",
serviceTransactions[0].ServiceTransactionResultMessage); // Each service will validate the supplied query data
// and show the results of that validation here:
Console.WriteLine("Validation Details: {0}",
serviceTransactions[0].ServiceValidationDetails); Console.WriteLine("Validation Result: {0}",
serviceTransactions[0].ValidationResult); // 4. The service result - This object is different for every
// service and contains the "raw" response for the
// service and is useful to look at for more information about the service result. // In this example we are just looking at the SIS response var sisResult = result.ProcessRequestResult.ServiceResult.SISPlusCheckResult; if (sisResult != null && sisResult.MatchResults != null) { Console.WriteLine("Found {0} results for: {1}",
sisResult.MatchResults.Length,
nameQuery); // Each match will contain the following information foreach (var match in sisResult.MatchResults) { Console.WriteLine("-------------------------------------------------"); Console.WriteLine("DOB: {0}-{1}-{2}",
match.BirthDay, match.BirthMonth, match.BirthYear); Console.WriteLine("Date of birth match score: {0}",
match.DateOfBirthMatchScore); Console.WriteLine("Match type: {0}", match.MatchType); Console.WriteLine("Name: {0}", match.Name); Console.WriteLine("Name match score: {0}", match.NameMatchScore); Console.WriteLine("ProfileId {0}", match.ProfileId); Console.WriteLine("Match type {0}", match.MatchType); } } else { Console.WriteLine("Nothing found in SIS search"); } Console.WriteLine("-------------------------------------------------"); Console.WriteLine("\nPress any key to exit"); Console.ReadKey(); } else { throw new Exception("No response from the service"); } } catch (Exception ex) { Console.WriteLine(ex.Message); Console.ReadLine(); } } } }

4. The App.config file in the console app needs to be updated to contain the correct information to connect to the service. Open the file, there isn't much in there aside from a <configuration> tag, and a <startup> tag. If you open the app.config located in the class library, you can copy the binding information over from there. You'll need to copy/paste everything within and including the <system.serviceModel> tags.

 

Paste this back into the console App.config, within the <configuration> tags, after the <startup> tag.

When you're finished, your file should be similar to this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
    <system.serviceModel>
      <bindings>
        <basicHttpBinding>
          <binding name="BasicHttpsBinding_IService">
            <security mode="Transport" />
          </binding>
        </basicHttpBinding>
      </bindings>
      <client>
        <endpoint address="https://apiv3-uat.w2globaldata.com/Service.svc"
                  binding="basicHttpBinding"
                  bindingConfiguration="BasicHttpsBinding_IService"
                  contract="W2GlobalDataService.IService"
                  name="BasicHttpsBinding_IService" />
      </client>
    </system.serviceModel>
</configuration>

 Step Four: Run the program

We are now ready to call the service. Right click on the Console App and Click on "Set as Startup project".

set as startup 

The project name should now appear in bold.

1. Press F5 to run the program. You will be asked to enter a name. Try "Robert Mugabe" and you should see several results. The code samples explain what the elements of the response do.

run it

2. Try running the program again with a few different names and see what happens.

Step Five: Diagnostics

Hopefully by now you should have a basic understanding of how to call the API. If you have any problems, check the API key and the bundle name being used and make sure these are correct.

It can be useful for debugging to collect some more information about what is going on under the hood. For SOAP calls this can be done by adding the following two elements to your app.config file. This will create a Traces.svclog file in the C:\Temp folder that contains the XML output.

1. Add this inside the <configuration> element

<system.diagnostics>
    <trace autoflush="true" />
    <sources>
      <source name="System.ServiceModel" 
switchValue="All"> <listeners> <add name="traceListener" /> </listeners> </source> <source name="System.ServiceModel.MessageLogging"
switchValue="All" > <listeners> <add name="traceListener" /> </listeners> </source> </sources> <sharedListeners> <add name="traceListener"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData="c:\temp\Traces.svclog" /> </sharedListeners> </system.diagnostics>

2. Add this inside the <system.serviceModel>l element

<diagnostics>
      <messageLogging logEntireMessage="true" 
                      logMalformedMessages="true" 
                      logMessagesAtServiceLevel="true" 
                      logMessagesAtTransportLevel="true" 
                      maxMessagesToLog="500"/>
    </diagnostics>