.NET C# Integration

.NET C# can be integrated using standard libraries, this example code was created using .NET framework 4.5.

The following name spaces were required to create the demo Windows application:

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Web;
using System.Web.Script.Serialization;
using System.Diagnostics;

Making a GET Request

This example uses the the API to load the name associated with an email address, the HandleAPIRequest function is used for code simplification.

// Creates and initializes a new NameValueCollection.
NameValueCollection data = System.Web.HttpUtility.ParseQueryString("");
data.Add("api_id", "cDSJwf6hECIjy_3XgoGv7q8PsgI.");
data.Add("api_key", "3Mu6rpQY6n0IQDUYVG5SyFRtIA1uOf3gpOuAdk9Uaa4.");
data.Add("email_address", "example@demo.com");

//Run the API request and unpack the results
Tuple<NameValueCollection, dynamic> response = HandleAPIRequest("GET", "https://control.instiller.co.uk/rest/users/details", data);
NameValueCollection Results = response.Item1;
dynamic User = response.Item2;

// Check the response to get the details
String Message = "";
if (Results.Get("valid").Equals("false")) {
    // Your error handling code
    if (Results.Get("http_code").Equals("false")) {
        // Problem connecting to the API
        Message = "Connection error";
    } else {
        // Show why we failed to load the details
        Message = "Error: " + User["code"] + " - " + User["reason"];
    }
} else {
    // Your User processing code
    Message = "Your contacts name is: " + User["first_name"] + " " + User["last_name"];
}

// Display the results of the search
GETResponse.Text = Message;

Making a POST Request

This example uses the the API to add or update a User and capture the unique ID allocated by the system, the HandleAPIRequest function is used for code simplification.

// Creates and initializes a new NameValueCollection.
NameValueCollection data = System.Web.HttpUtility.ParseQueryString("");
data.Add("api_id", "cDSJwf6hECIjy_3XgoGv7q8PsgI.");
data.Add("api_key", "3Mu6rpQY6n0IQDUYVG5SyFRtIA1uOf3gpOuAdk9Uaa4.");
data.Add("email_address", "example@demo.com");
data.Add("first_name", "Eric");
data.Add("last_name", "Example");
data.Add("reference_code", "MY-CUSTOMER-REF");

//Run the API request and unpack the results
Tuple<NameValueCollection, dynamic> response = HandleAPIRequest("POST", "https://control.instiller.co.uk/rest/users/add_or_update", data);
NameValueCollection Results = response.Item1;
dynamic User = response.Item2;


// Check the response to get the details
String Message = "";
if (Results.Get("valid").Equals("false"))
{
    // Your error handling code
    if (Results.Get("http_code").Equals("false"))
    {
        // Problem connecting to the API
        Message = "Connection error";
    }
    else
    {
        // Show why we failed to load the details
        Message = "Error: " + User["code"] + " - " + User["reason"];
    }
}
else
{
    // Your User processing code
    Message = "Your User has been created or updated our ID is: " + User["user_id"];
}

// Display the results of the search
POSTResponse.Text = Message;

Request Wrapper

Creating a single function to handle your API requests will simplify your code and allow you to centralise error handling.

    private Tuple<NameValueCollection, dynamic> HandleAPIRequest(String method, String url, NameValueCollection data, String ResponseType = "application/json")
    {
        // Initialise the results of the API request 
        NameValueCollection Results = new NameValueCollection();
        Results.Add("valid", "false");
        Results.Add("response", "");

        // Initialise a blank result we can pass back
        dynamic response_data = "";

        // Work out what request we need to process
        HttpWebRequest request;
        if (method.Equals("GET"))
        {
            // Create the web request  
            request = WebRequest.Create(url + "?" + data.ToString()) as HttpWebRequest;
        }
        else
        {
            // Create the web request  
            request = WebRequest.Create(url) as HttpWebRequest;

            // Set type to POST  
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            // Create a byte array of the data we want to send  
            byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());

            // Set the content headers and write data  
            request.ContentLength = byteData.Length;
            using (Stream postStream = request.GetRequestStream())
            {
                postStream.Write(byteData, 0, byteData.Length);
            }
        }

        // Get the response from the remove server
        try
        {
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                // Extract the response from the server
                StreamReader reader = new StreamReader(response.GetResponseStream());
                String raw_response = reader.ReadToEnd();
                Results.Add("http_code", response.StatusCode.ToString());
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    // We have got a 200 response from the server request is valid
                    Results.Set("valid", "true");
                }
                // Check to see if we need decode the response data
                response_data = raw_response;
                if (ResponseType.Equals("application/json"))
                {
                    // Use the native JS serializer to create dynamic object to avoid creating class declarations
                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    response_data = serializer.Deserialize<dynamic>(raw_response);
                }
            }
        }
        catch (WebException ex)
        {
            // Check to see if we can get the error code from the response
            if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
            {
                // Cast the exception as as HTTPResponse and grab the returned code
                var response = (HttpWebResponse)ex.Response;
                Results.Add("http_code", response.StatusCode.ToString());

                // Get the response stream  
                StreamReader reader = new StreamReader(response.GetResponseStream());
                String raw_response = reader.ReadToEnd();

                // Check to see if we need decode the response data
                response_data = raw_response;
                if (ResponseType.Equals("application/json"))
                {
                    // Use the native JS serializer to create dynamic object to avoid creating class declarations
                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    response_data = serializer.Deserialize<dynamic>(raw_response);
                }
            }
        }


        // Return the information from the request and decoded data in a Tuple
        return new Tuple<NameValueCollection, dynamic>(Results, response_data);
    }

What Next?

This example code can be customised to access any API endpoint:

  • Locate the API endpoint you require using the API explorer
  • Change the URL used to request the API
  • Change the fields used in the request to match the API documentation